@typesol/cli 0.45.0 → 0.47.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 (72) hide show
  1. package/CHANGELOG.md +250 -0
  2. package/README.md +63 -17
  3. package/SECURITY.md +9 -7
  4. package/dist/bin.d.ts +2 -0
  5. package/dist/bin.js +9 -0
  6. package/dist/cli.js +33 -15
  7. package/dist/compiler/analyze.js +57 -6
  8. package/dist/compiler/diagnostics.d.ts +4 -3
  9. package/dist/compiler/diagnostics.js +10 -6
  10. package/dist/compiler/emit/base.d.ts +1 -1
  11. package/dist/compiler/emit/calls.js +18 -5
  12. package/dist/compiler/emit/cpi-core.d.ts +3 -1
  13. package/dist/compiler/emit/cpi-core.js +8 -4
  14. package/dist/compiler/emit/expressions.d.ts +14 -0
  15. package/dist/compiler/emit/expressions.js +52 -4
  16. package/dist/compiler/emit/shared.d.ts +8 -1
  17. package/dist/compiler/emit/shared.js +8 -1
  18. package/dist/compiler/emit/statements.d.ts +8 -3
  19. package/dist/compiler/emit/statements.js +68 -3
  20. package/dist/compiler/emit/storage.js +5 -1
  21. package/dist/compiler/hints.d.ts +7 -0
  22. package/dist/compiler/hints.js +58 -9
  23. package/dist/compiler/index.d.ts +5 -0
  24. package/dist/compiler/index.js +10 -1
  25. package/dist/compiler/model.js +3 -2
  26. package/dist/compiler/toolchain.d.ts +50 -2
  27. package/dist/compiler/toolchain.js +96 -11
  28. package/dist/idl-coder.d.ts +110 -0
  29. package/dist/idl-coder.js +529 -0
  30. package/dist/node-version.d.ts +4 -0
  31. package/dist/node-version.js +12 -0
  32. package/dist/testing.d.ts +44 -7
  33. package/dist/testing.js +30 -19
  34. package/dist/tools/doctor.d.ts +41 -0
  35. package/dist/tools/doctor.js +96 -14
  36. package/dist/workspace.d.ts +9 -2
  37. package/dist/workspace.js +13 -4
  38. package/docker/deps/0.46.0.lock.json +1206 -0
  39. package/docker/deps/0.47.0.lock.json +1206 -0
  40. package/docs/ai.md +2 -1
  41. package/docs/architecture.md +7 -3
  42. package/docs/audit.md +6 -6
  43. package/docs/case-study-phoenix.md +1 -1
  44. package/docs/case-study-raydium-amm.md +1 -1
  45. package/docs/case-study-spl-stake-pool.md +1 -1
  46. package/docs/cli.md +42 -4
  47. package/docs/errors.md +22 -8
  48. package/docs/glossary.md +210 -0
  49. package/docs/language-accounts.md +499 -0
  50. package/docs/language-basics.md +389 -0
  51. package/docs/language-builtins.md +411 -0
  52. package/docs/language-chain.md +198 -0
  53. package/docs/language-cpi.md +470 -0
  54. package/docs/language-errors-events.md +184 -0
  55. package/docs/language-native.md +493 -0
  56. package/docs/language-pdas.md +198 -0
  57. package/docs/language-statements.md +620 -0
  58. package/docs/language-types.md +601 -0
  59. package/docs/language.md +190 -467
  60. package/docs/mainnet.md +18 -3
  61. package/docs/migrate-from-anchor.md +7 -6
  62. package/docs/security-model.md +3 -3
  63. package/docs/stability.md +3 -1
  64. package/docs/test-your-program.md +54 -15
  65. package/docs/troubleshooting.md +222 -100
  66. package/lib/typesol.d.ts +67 -22
  67. package/llms-full.txt +4920 -638
  68. package/llms.txt +12 -1
  69. package/package.json +2 -6
  70. package/releases/0.45.0.json +732 -0
  71. package/releases/0.46.0.json +817 -0
  72. package/ts-plugin/index.js +16 -5
@@ -5,7 +5,8 @@ import { fileURLToPath } from "node:url";
5
5
  import { CompileError, Reporter, markAliasUse } from "./diagnostics.js";
6
6
  import { decodeAddress } from "../keys.js";
7
7
  import { borshIdentical } from "./emit/borsh.js";
8
- import { hintForTypeScript, unsupportedSyntax } from "./hints.js";
8
+ import { MAX_SEEDS } from "./emit/shared.js";
9
+ import { ASYNC_HINT, fieldTypeHint, hintForTypeScript, messageForTypeScript, unsupportedSyntax } from "./hints.js";
9
10
  import { optionKey, INT_INFO, INT_NAMES, scalarKey, fixedVecName, isScalar, scalarSize, typeName, } from "./model.js";
10
11
  export const LIB_PATH = fileURLToPath(new URL("../../lib/typesol.d.ts", import.meta.url));
11
12
  /** Names a struct field may not use because account parameters already expose them. */
@@ -272,7 +273,8 @@ function typecheck(entry, files) {
272
273
  const diagnostics = tsDiagnostics.map((d) => {
273
274
  const flat = ts.flattenDiagnosticMessageText(d.messageText, "\n");
274
275
  const hint = hintForTypeScript(d, flat, LIB_PATH);
275
- const message = hint ? `${flat}\nhint: ${hint}` : flat;
276
+ const shown = messageForTypeScript(d, flat);
277
+ const message = hint ? `${shown}\nhint: ${hint}` : shown;
276
278
  const extra = hint ? { hint } : {};
277
279
  if (!d.file || d.start === undefined)
278
280
  return { file: entry, line: 1, column: 1, message, ...extra };
@@ -443,6 +445,50 @@ export function analyze(entry, files) {
443
445
  if (isError) {
444
446
  // String enum: program errors, codes 6000+ in declaration order (imported files first).
445
447
  const members = new Map();
448
+ // A doc comment belongs to the member that starts on a later line. `A = "a", /** @code 6200 */ B = "b"`
449
+ // leaves the tag on no member (TypeScript reads it as trailing A's comma), so B would silently take the
450
+ // next code: refuse it instead, and a tag in a comment that is not a doc comment, or in a doc comment that
451
+ // another one follows (only the last is read). In a doc comment, as TypeScript reads it, a tag is any
452
+ // `@code` after the start, whitespace or `*` (`/** The second. @code 6200 */` is one); in a // or /* … */
453
+ // comment, only one first on a line of the comment is reported, so prose (`// see the @code docs`) is not.
454
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, file.text);
455
+ scanner.resetTokenState(stmt.members.pos);
456
+ const isDoc = (text) => text.startsWith("/**") && text !== "/**/";
457
+ const tagged = (text) => isDoc(text) ? /(?:^|[\s*])@code\b/.test(text) : /^\/[*/]\**\s*@code\b/.test(text) || /\n\s*\*?\s*@code\b/.test(text);
458
+ // A tag above the enum itself numbers no member: refused, not ignored.
459
+ for (const r of ts.getLeadingCommentRanges(file.text, stmt.pos) ?? []) {
460
+ const text = file.text.slice(r.pos, r.end);
461
+ if (r.kind === ts.SyntaxKind.MultiLineCommentTrivia && isDoc(text) && tagged(text)) {
462
+ const first = stmt.members[0] ? `, ${stmt.members[0].name.getText(file)}` : "";
463
+ reporter.fail(stmt.name, `this @code tag is not read: a tag above the enum numbers no member; put /** @code … */ above its first member${first}`);
464
+ }
465
+ }
466
+ for (let k = scanner.scan(); k !== ts.SyntaxKind.EndOfFileToken && scanner.getTokenStart() < stmt.end; k = scanner.scan()) {
467
+ if (k !== ts.SyntaxKind.MultiLineCommentTrivia && k !== ts.SyntaxKind.SingleLineCommentTrivia)
468
+ continue;
469
+ const text = scanner.getTokenText();
470
+ if (!tagged(text))
471
+ continue;
472
+ const at = scanner.getTokenStart();
473
+ const next = stmt.members.find((m) => m.getStart(file) > at);
474
+ const above = next ? `above ${next.name.getText(file)}` : "above the member it numbers";
475
+ const doc = k === ts.SyntaxKind.MultiLineCommentTrivia && isDoc(text);
476
+ if (!doc) {
477
+ reporter.fail(next ?? stmt, `this @code tag is not read: only a doc comment (/** … */) is, not a ${text.startsWith("//") ? "// comment" : "/* … */ comment"}; write /** @code … */ ${above}`);
478
+ continue;
479
+ }
480
+ const docs = next ? ts.getJSDocCommentsAndTags(next).filter((d) => ts.isJSDoc(d)) : [];
481
+ if (docs.some((d) => d.getStart(file) === at))
482
+ continue;
483
+ const lineStart = file.text.lastIndexOf("\n", at - 1) + 1;
484
+ reporter.fail(next ?? stmt, !next
485
+ ? "this @code tag is not read: it follows the last member; put /** @code … */ on its own line above the member it numbers"
486
+ : file.text.slice(lineStart, at).trim()
487
+ ? `this @code tag is not read: other code comes before it on its line; put /** @code … */ on its own line ${above}`
488
+ : docs.some((d) => d.getStart(file) > at)
489
+ ? `this @code tag is not read: another doc comment follows it, and only the last one above ${next.name.getText(file)} is read; put the tag in that one`
490
+ : `this @code tag is not read; put /** @code … */ on its own line ${above}`);
491
+ }
446
492
  for (const m of stmt.members) {
447
493
  if (!m.initializer || !ts.isStringLiteral(m.initializer))
448
494
  reporter.fail(m, 'error enum members need a string message: Name = "message"');
@@ -1587,7 +1633,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1587
1633
  }
1588
1634
  if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && names.has(node.typeName.text) && !targs.length)
1589
1635
  return { kind: "struct", name: node.typeName.text };
1590
- reporter.fail(node, "field type must be an integer, boolean, Pubkey, FixedArray<T, N>, FixedString<N>, FixedVec<T, N>, Vec<T>, string (events only) or another struct");
1636
+ reporter.fail(node, "field type must be an integer, boolean, Pubkey, FixedArray<T, N>, FixedString<N>, FixedVec<T, N>, Vec<T>, string (events only) or another struct", fieldTypeHint(node));
1591
1637
  };
1592
1638
  // `BigVec<T>`: a u32 length, then elements to the end of the account (SPL's big_vec). Only the last field, so its
1593
1639
  // elements are the account's remaining bytes; T is a scalar or a fixed-size struct.
@@ -2071,9 +2117,9 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
2071
2117
  if (!fn.body)
2072
2118
  reporter.fail(fn, "helper functions need a body");
2073
2119
  if (fn.asteriskToken)
2074
- reporter.fail(fn, "helper functions cannot be generators");
2120
+ reporter.fail(fn, "helper functions cannot be generators", ASYNC_HINT);
2075
2121
  if ((ts.getModifiers(fn) ?? []).some((m) => m.kind === ts.SyntaxKind.AsyncKeyword))
2076
- reporter.fail(fn, "helper functions cannot be async");
2122
+ reporter.fail(fn, "helper functions cannot be async", ASYNC_HINT);
2077
2123
  if (!fn.type)
2078
2124
  reporter.fail(fn.name ?? fn, "helper functions need an explicit return type (void, an integer, boolean, Pubkey or a struct)");
2079
2125
  let returns = fn.type.kind === ts.SyntaxKind.VoidKeyword
@@ -2325,7 +2371,7 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
2325
2371
  if (fn.typeParameters?.length)
2326
2372
  reporter.fail(fn, "instructions cannot be generic");
2327
2373
  if (fn.asteriskToken || (ts.getModifiers(fn) ?? []).some((m) => m.kind === ts.SyntaxKind.AsyncKeyword))
2328
- reporter.fail(fn, "instructions cannot be async or generators");
2374
+ reporter.fail(fn, "instructions cannot be async or generators", ASYNC_HINT);
2329
2375
  let returns;
2330
2376
  if (fn.type && fn.type.kind !== ts.SyntaxKind.VoidKeyword) {
2331
2377
  returns = fn.type.kind === ts.SyntaxKind.StringKeyword ? { kind: "string" } : resolveScalarType(fn.type, scope);
@@ -2751,6 +2797,11 @@ function unwrapConstraints(node, reporter, imports, out) {
2751
2797
  const program = args[3] ? lit(args[3])[0] : undefined;
2752
2798
  if (program && !program.startsWith("@") && !decodeAddress(program))
2753
2799
  reporter.fail(args[3], `Seeds program: "${program}" is neither "@param" nor a base58 address`);
2800
+ // The same limits as a seed list in code: a stored bump ends the list, a canonical one the derivation adds.
2801
+ if (bump !== undefined && names.length + 1 > MAX_SEEDS)
2802
+ reporter.fail(tuple, `at most ${MAX_SEEDS} seeds, the bump included (Solana's limit)`);
2803
+ if (bump === undefined && names.length > MAX_SEEDS - 1)
2804
+ reporter.fail(tuple, `at most ${MAX_SEEDS - 1} seeds: the bump the derivation adds makes ${MAX_SEEDS}, Solana's limit`);
2754
2805
  out.seeds = { names, bump, program };
2755
2806
  }
2756
2807
  if (!args[0])
@@ -15,12 +15,13 @@ export declare class CompileError extends Error {
15
15
  }
16
16
  export declare function formatDiagnostic(d: Diagnostic): string;
17
17
  export declare function markAliasUse(copy: ts.Node, use: ts.Node): void;
18
- export declare function diagnosticAt(node: ts.Node, message: string): Diagnostic;
18
+ export declare function diagnosticAt(node: ts.Node, message: string, hint?: string): Diagnostic;
19
19
  /** Collects diagnostics; `fail` records one and throws to unwind the current construct. */
20
20
  export declare class Reporter {
21
21
  readonly diagnostics: Diagnostic[];
22
- error(node: ts.Node, message: string): void;
23
- fail(node: ts.Node, message: string): never;
22
+ /** `hint`: what to write instead, shown as the message's last line ("hint: …") and given to tools as `hint`. */
23
+ error(node: ts.Node, message: string, hint?: string): void;
24
+ fail(node: ts.Node, message: string, hint?: string): never;
24
25
  /** Run `fn`, swallowing a `fail` so analysis can continue with the next construct. */
25
26
  guard<T>(fn: () => T): T | undefined;
26
27
  throwIfAny(): void;
@@ -14,7 +14,7 @@ const aliasUses = new WeakMap();
14
14
  export function markAliasUse(copy, use) {
15
15
  aliasUses.set(copy, use);
16
16
  }
17
- export function diagnosticAt(node, message) {
17
+ export function diagnosticAt(node, message, hint) {
18
18
  // A problem with an aliased type is reported where the alias is used.
19
19
  for (let n = node; n; n = n.parent) {
20
20
  const use = aliasUses.get(n);
@@ -26,16 +26,20 @@ export function diagnosticAt(node, message) {
26
26
  const sf = node.getSourceFile();
27
27
  const start = node.getStart(sf);
28
28
  const { line, character } = sf.getLineAndCharacterOfPosition(start);
29
- return { file: sf.fileName, line: line + 1, column: character + 1, message, length: Math.max(1, node.getEnd() - start) };
29
+ const length = Math.max(1, node.getEnd() - start);
30
+ if (!hint)
31
+ return { file: sf.fileName, line: line + 1, column: character + 1, message, length };
32
+ return { file: sf.fileName, line: line + 1, column: character + 1, message: `${message}\nhint: ${hint}`, length, hint };
30
33
  }
31
34
  /** Collects diagnostics; `fail` records one and throws to unwind the current construct. */
32
35
  export class Reporter {
33
36
  diagnostics = [];
34
- error(node, message) {
35
- this.diagnostics.push(diagnosticAt(node, message));
37
+ /** `hint`: what to write instead, shown as the message's last line ("hint: …") and given to tools as `hint`. */
38
+ error(node, message, hint) {
39
+ this.diagnostics.push(diagnosticAt(node, message, hint));
36
40
  }
37
- fail(node, message) {
38
- this.error(node, message);
41
+ fail(node, message, hint) {
42
+ this.error(node, message, hint);
39
43
  throw new Bail();
40
44
  }
41
45
  /** Run `fn`, swallowing a `fail` so analysis can continue with the next construct. */
@@ -173,7 +173,7 @@ export declare abstract class EmitterBase {
173
173
  protected abstract accountChoice(node: ts.ConditionalExpression): Value;
174
174
  protected abstract instructionsParam(node: ts.Expression): AccountParam | undefined;
175
175
  protected abstract isTxIx(node: ts.Expression): boolean;
176
- protected abstract seeds(node: ts.Expression, extra: number, bound?: boolean): {
176
+ protected abstract seeds(node: ts.Expression, extra: number, bound?: boolean, withBump?: boolean): {
177
177
  name: string;
178
178
  count: number;
179
179
  idl: IdlSeed[] | undefined;
@@ -166,6 +166,7 @@ export class CallEmitter extends ExpressionEmitter {
166
166
  this.line(`sol_log_((const char *)${t}.ptr, ${t}.len);`);
167
167
  }
168
168
  else {
169
+ this.refuseF64Text(args[0], v.type);
169
170
  let value = v.literal !== undefined ? this.expect(v, U64, args[0]) : v;
170
171
  // An Option TypeScript has narrowed to its value (after `x === null` was ruled out): log the value.
171
172
  if (value.type.kind === "option") {
@@ -319,6 +320,7 @@ export class CallEmitter extends ExpressionEmitter {
319
320
  vals[j] = this.settle(vals[j], mark);
320
321
  vals.push(v);
321
322
  }
323
+ this.refuseF64(node, `${builtin}()`, ...vals);
322
324
  const typed = vals.find((v) => v.literal === undefined);
323
325
  if (typed?.type.kind === "int" && typed.type.name === "u256") {
324
326
  // u256: a 512-bit product in the runtime.
@@ -344,13 +346,16 @@ export class CallEmitter extends ExpressionEmitter {
344
346
  if (args.length !== 1)
345
347
  this.fail(node, `${builtin}(x) takes one ${builtin === "f64Bits" ? "f64" : "u64"}`);
346
348
  const v = this.expr(args[0]);
347
- const x = v.literal !== undefined ? this.literal(v.literal, U64, args[0]) : this.expect(v, U64, args[0]);
348
- return { c: x.c, type: builtin === "f64Bits" ? U64 : { kind: "int", name: "u64", f64: true } };
349
+ const f64 = { kind: "int", name: "u64", f64: true };
350
+ const from = builtin === "f64Bits" ? f64 : U64;
351
+ const x = v.literal !== undefined && builtin === "f64FromBits" ? this.literal(v.literal, U64, args[0]) : this.expect(v, from, args[0]);
352
+ return { c: x.c, type: builtin === "f64Bits" ? U64 : f64 };
349
353
  }
350
354
  case "isqrt": {
351
355
  if (args.length !== 1)
352
356
  this.fail(node, "isqrt(x) takes one unsigned integer");
353
357
  const v = this.expr(args[0]);
358
+ this.refuseF64(node, "isqrt()", v);
354
359
  const x = v.literal !== undefined ? this.literal(v.literal, U64, args[0]) : v;
355
360
  if (x.type.kind !== "int" || INT_INFO[x.type.name].signed)
356
361
  this.fail(args[0], "isqrt needs an unsigned integer (u8 … u256)");
@@ -367,6 +372,7 @@ export class CallEmitter extends ExpressionEmitter {
367
372
  const mark = this.lines.length;
368
373
  let b = this.expr(args[1], a.type.kind === "int" && a.literal === undefined ? a.type : undefined);
369
374
  a = this.settle(a, mark);
375
+ this.refuseF64(node, `${builtin}()`, a, b);
370
376
  if (a.literal !== undefined && b.literal !== undefined) {
371
377
  a = this.literal(a.literal, U64, args[0]);
372
378
  b = this.literal(b.literal, U64, args[1]);
@@ -655,7 +661,7 @@ export class CallEmitter extends ExpressionEmitter {
655
661
  // on the curve (Rust's Err(PubkeyError::InvalidSeeds)) or are too many / too long.
656
662
  if (args.length !== 2)
657
663
  this.fail(node, "createProgramAddress(seeds, program) takes the seeds (bump last) and the program's address");
658
- const seeds = this.seeds(args[0], 0);
664
+ const seeds = this.seeds(args[0], 0, false, true);
659
665
  const program = this.expect(this.expr(args[1], PUBKEY), PUBKEY, args[1]);
660
666
  const t = this.tmp("cpa");
661
667
  this.model.options.set("pubkey", PUBKEY);
@@ -1086,12 +1092,19 @@ export class CallEmitter extends ExpressionEmitter {
1086
1092
  "Math.min": "min(a, b)",
1087
1093
  "Math.max": "max(a, b)",
1088
1094
  "Date.now": "now() (the Clock's unix timestamp)",
1095
+ "Math.floor": "integer division (a / b with bigints rounds toward zero)",
1096
+ "Math.trunc": "integer division (a / b with bigints rounds toward zero)",
1097
+ "Math.ceil": "integer division rounded up: (a + b - 1n) / b",
1098
+ "Math.round": "integer division rounded: (a + b / 2n) / b",
1089
1099
  "JSON.stringify": "log(…) with the values",
1090
1100
  Number: "u64(x) or another integer cast",
1091
1101
  BigInt: "u64(x) or another integer cast",
1092
1102
  String: "a FixedString<N> field, or log(…)",
1093
1103
  };
1094
- const hint = hints[text];
1104
+ // Math.floor(Date.now() / 1000): the time in seconds, which is what now() gives.
1105
+ if (/^Math\.(floor|trunc|round|ceil)$/.test(text) && ts.isCallExpression(callee.parent) && /\bDate\.now\(/.test(callee.parent.getText()))
1106
+ return `unsupported call: ${text}(Date.now() …); use now() from "typesol", the cluster's clock in Unix seconds (an i64)`;
1107
+ const hint = Object.hasOwn(hints, text) ? hints[text] : undefined;
1095
1108
  if (hint)
1096
1109
  return `unsupported call: ${text}; use ${hint}`;
1097
1110
  if (ts.isPropertyAccessExpression(callee) && this.accountAt(callee.expression))
@@ -3043,7 +3056,7 @@ export class CallEmitter extends ExpressionEmitter {
3043
3056
  if (n.arguments.length !== 1)
3044
3057
  this.fail(n, "signer([...seeds]) takes the seeds (with the bump) as an array; signer([]) signs for nothing");
3045
3058
  // 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);
3059
+ return this.seeds(n.arguments[0], 0, true, true);
3047
3060
  }
3048
3061
  this.fail(n, "pass signer([...seeds with the bump]) or a SignerSeeds parameter");
3049
3062
  }
@@ -7,8 +7,10 @@ export declare abstract class CpiCoreEmitter extends ViewEmitter {
7
7
  /**
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
+ * `withBump`: the list ends with its bump (signer seeds, createProgramAddress), so it may hold MAX_SEEDS entries;
11
+ * otherwise the derivation adds the bump, and the list holds one fewer.
10
12
  */
11
- protected seeds(node: ts.Expression, extra: number, bound?: boolean): {
13
+ protected seeds(node: ts.Expression, extra: number, bound?: boolean, withBump?: boolean): {
12
14
  name: string;
13
15
  count: number;
14
16
  idl: IdlSeed[] | undefined;
@@ -9,12 +9,16 @@ export class CpiCoreEmitter extends ViewEmitter {
9
9
  /**
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
+ * `withBump`: the list ends with its bump (signer seeds, createProgramAddress), so it may hold MAX_SEEDS entries;
13
+ * otherwise the derivation adds the bump, and the list holds one fewer.
12
14
  */
13
- seeds(node, extra, bound = false) {
15
+ seeds(node, extra, bound = false, withBump = false) {
14
16
  if (!ts.isArrayLiteralExpression(node))
15
17
  this.fail(node, "seeds must be an array literal");
16
- if (node.elements.length > MAX_SEEDS)
17
- this.fail(node, `at most ${MAX_SEEDS} seeds`);
18
+ if (withBump && node.elements.length > MAX_SEEDS)
19
+ this.fail(node, `at most ${MAX_SEEDS} seeds, the bump included (Solana's limit)`);
20
+ if (!withBump && node.elements.length > MAX_SEEDS - 1)
21
+ this.fail(node, `at most ${MAX_SEEDS - 1} seeds: the bump the derivation adds makes ${MAX_SEEDS}, Solana's limit`);
18
22
  const parts = [];
19
23
  let idl = [];
20
24
  // The array points at its seeds, which are read when the CPI runs. Seeds that are not constants are copied when
@@ -240,7 +244,7 @@ export class CpiCoreEmitter extends ViewEmitter {
240
244
  if (l?.type.kind === "signerSeeds")
241
245
  return { name: l.c, count: `${l.c}__n` };
242
246
  }
243
- return this.seeds(node, 0);
247
+ return this.seeds(node, 0, false, true);
244
248
  }
245
249
  /**
246
250
  * Several PDAs signing one CPI: `[["vault", owner.key, vaultBump], ["fees", feeBump]]` (or SignerSeeds parameters
@@ -6,7 +6,21 @@ import { StorageEmitter } from "./storage.js";
6
6
  * Expressions: literals, operators with checked arithmetic, property reads, conditionals, text and casts.
7
7
  */
8
8
  export declare abstract class ExpressionEmitter extends StorageEmitter {
9
+ /**
10
+ * An f64 is held as its IEEE 754 bits in a u64 and TypeSOL has no float arithmetic: an integer operator on one
11
+ * would work on the bits (1.0 + 1.0 would add 0x3FF0… twice), so every operator with an f64 operand is refused.
12
+ * Equality too: the bits are not the number (NaN would equal itself, 0 would not equal -0), so comparing them is
13
+ * written out as f64Bits(a) === f64Bits(b).
14
+ */
15
+ protected refuseF64(node: ts.Node, what: string, ...values: Value[]): void;
9
16
  protected expect(v: Value, want: ValueType | undefined, node: ts.Node): Value;
17
+ /**
18
+ * An f64 is not an integer: its u64 of bits never becomes an integer's value, nor an integer an f64's, without
19
+ * saying so with f64Bits(x) / f64FromBits(bits). (Options are compared by their inner types.)
20
+ */
21
+ /** An f64 as text (a template, log()): the digits would be its bits' integer, not the number. */
22
+ protected refuseF64Text(node: ts.Node, t: ValueType): void;
23
+ protected refuseF64Conversion(node: ts.Node, from: ValueType, to: ValueType): void;
10
24
  /**
11
25
  * Use an Option's value. TypeScript only allows this after narrowing (`x !== null`), so the runtime
12
26
  * check is a backstop: an empty option aborts with 5108.
@@ -2,13 +2,27 @@ import ts from "typescript";
2
2
  import { base58 } from "../../keys.js";
3
3
  import { calleeName, resolveValueType } from "../analyze.js";
4
4
  import { INT_INFO, unsignedC, optionKey, sameType, typeName } from "../model.js";
5
- import { U64, U8, I64, BOOL, PUBKEY, STRING, HASH, cString, intLiteral, scalarStorageC, optC, valueC, vecCount } from "./shared.js";
5
+ import { U64, U8, I64, BOOL, PUBKEY, STRING, HASH, F64_TEXT, F64_TO_INT, INT_TO_F64, cString, intLiteral, scalarStorageC, optC, valueC, vecCount, } from "./shared.js";
6
6
  import { StorageEmitter } from "./storage.js";
7
7
  import { unsupportedSyntax } from "../hints.js";
8
8
  /**
9
9
  * Expressions: literals, operators with checked arithmetic, property reads, conditionals, text and casts.
10
10
  */
11
11
  export class ExpressionEmitter extends StorageEmitter {
12
+ /**
13
+ * An f64 is held as its IEEE 754 bits in a u64 and TypeSOL has no float arithmetic: an integer operator on one
14
+ * would work on the bits (1.0 + 1.0 would add 0x3FF0… twice), so every operator with an f64 operand is refused.
15
+ * Equality too: the bits are not the number (NaN would equal itself, 0 would not equal -0), so comparing them is
16
+ * written out as f64Bits(a) === f64Bits(b).
17
+ */
18
+ refuseF64(node, what, ...values) {
19
+ const isF64 = (t) => (t.kind === "int" && t.f64 === true) || (t.kind === "option" && isF64(t.inner));
20
+ if (!values.some((v) => isF64(v.type)))
21
+ return;
22
+ if (what === "===" || what === "!==" || what === "==" || what === "!=" || what === "switch")
23
+ this.fail(node, `${what} on an f64 is not supported: an f64 is held as its IEEE 754 bits, and equal bits are not equal numbers (NaN would equal itself, 0 would not equal -0); to compare the bits, write f64Bits(a) === f64Bits(b)`);
24
+ this.fail(node, `${what} on an f64 is not supported: an f64 is held as its IEEE 754 bits and there is no float arithmetic (this would compute on the bits); compute in integers and make the result with f64FromBits(bits), or take an f64's bits with f64Bits(x)`);
25
+ }
12
26
  expect(v, want, node) {
13
27
  if (v.isNull) {
14
28
  if (want?.kind !== "option")
@@ -28,12 +42,33 @@ export class ExpressionEmitter extends StorageEmitter {
28
42
  }
29
43
  if (v.type.kind === "option" && want.kind !== "option")
30
44
  return this.expect(this.unwrap(v, node), want, node);
45
+ this.refuseF64Conversion(node, v.type, want);
31
46
  if (v.literal !== undefined && want.kind === "int")
32
47
  return this.literal(v.literal, want, node);
33
48
  if (!sameType(v.type, want))
34
49
  this.fail(node, `expected ${typeName(want)}, got ${typeName(v.type)}`);
35
50
  return v;
36
51
  }
52
+ /**
53
+ * An f64 is not an integer: its u64 of bits never becomes an integer's value, nor an integer an f64's, without
54
+ * saying so with f64Bits(x) / f64FromBits(bits). (Options are compared by their inner types.)
55
+ */
56
+ /** An f64 as text (a template, log()): the digits would be its bits' integer, not the number. */
57
+ refuseF64Text(node, t) {
58
+ const inner = t.kind === "option" ? t.inner : t;
59
+ if (inner.kind === "int" && inner.f64)
60
+ this.fail(node, F64_TEXT);
61
+ }
62
+ refuseF64Conversion(node, from, to) {
63
+ const inner = (t) => (t.kind === "option" ? t.inner : t);
64
+ const a = inner(from);
65
+ const b = inner(to);
66
+ if (a.kind !== "int" || b.kind !== "int" || !a.f64 === !b.f64)
67
+ return;
68
+ if (a.f64)
69
+ this.fail(node, F64_TO_INT(typeName(b)));
70
+ this.fail(node, INT_TO_F64(typeName(a)));
71
+ }
37
72
  /**
38
73
  * Use an Option's value. TypeScript only allows this after narrowing (`x !== null`), so the runtime
39
74
  * check is a backstop: an empty option aborts with 5108.
@@ -200,6 +235,8 @@ export class ExpressionEmitter extends StorageEmitter {
200
235
  if (!t || t.kind === "vecArg" || t.kind === "dataEnumArg")
201
236
  this.fail(node.type, "`as` names an integer, boolean, Pubkey, enum, option or string type the value already has");
202
237
  const v = this.expr(node.expression, t);
238
+ if (!v.isNull)
239
+ this.refuseF64Conversion(node, v.type, t);
203
240
  // Not a conversion: `x as u64 | null` does not make an Option of a u64.
204
241
  if (v.literal === undefined && !v.isNull && !sameType(v.type, t))
205
242
  this.fail(node, `this is a ${typeName(v.type)}, not a ${typeName(t)}: \`as\` does not convert (use u64(x) and the like for integers)`);
@@ -312,6 +349,7 @@ export class ExpressionEmitter extends StorageEmitter {
312
349
  return this.literal(value, hint?.kind === "int" ? hint : I64, node);
313
350
  }
314
351
  const v = this.expr(node.operand, hint);
352
+ this.refuseF64(node, "unary -", v);
315
353
  if (v.type.kind !== "int" || !INT_INFO[v.type.name].signed)
316
354
  this.fail(node, "unary minus needs a signed integer (i8 … i128)");
317
355
  return this.arith(ts.SyntaxKind.MinusToken, { c: intLiteral(0n, v.type.name), type: v.type }, v, node);
@@ -319,6 +357,7 @@ export class ExpressionEmitter extends StorageEmitter {
319
357
  if (node.operator === ts.SyntaxKind.TildeToken) {
320
358
  // Bitwise not within the type's width (for signed types this equals JS's -(x + 1)).
321
359
  const v = this.expr(node.operand, hint);
360
+ this.refuseF64(node, "~", v);
322
361
  const typed = v.literal !== undefined ? this.literal(v.literal, hint?.kind === "int" ? hint : U64, node) : v;
323
362
  if (typed.type.kind !== "int")
324
363
  this.fail(node, "~ needs an integer");
@@ -707,6 +746,7 @@ export class ExpressionEmitter extends StorageEmitter {
707
746
  const v = this.expr(node);
708
747
  if (v.type.kind === "string")
709
748
  return v.c;
749
+ this.refuseF64Text(node, v.type);
710
750
  if (converted)
711
751
  converted.yes = true;
712
752
  if (v.type.kind === "option" && v.type.inner.kind === "pubkey") {
@@ -825,7 +865,9 @@ export class ExpressionEmitter extends StorageEmitter {
825
865
  if (inner.kind === "struct")
826
866
  this.fail(node, "?? works on Options of integers, booleans and Pubkeys");
827
867
  const nullable = (t) => !!(t.flags & ts.TypeFlags.Null) || (t.isUnion() && t.types.some(nullable));
828
- const type = hint ?? (nullable(this.checker.getTypeAtLocation(node)) ? left.type : inner);
868
+ // Over an Option<f64> the result is an f64 whatever the context expects: an integer hint would make it the bits.
869
+ const f64 = inner.kind === "int" && inner.f64 === true;
870
+ const type = (f64 ? undefined : hint) ?? (nullable(this.checker.getTypeAtLocation(node)) ? left.type : inner);
829
871
  const lo = this.tmp("opt");
830
872
  this.line(`${optC(inner)} ${lo} = ${left.c};`);
831
873
  const t = this.tmp("nn");
@@ -856,6 +898,7 @@ export class ExpressionEmitter extends StorageEmitter {
856
898
  const exp = this.expr(node.right);
857
899
  // JS reads the base first: if the exponent ran statements (a helper that changes it), use the value read before.
858
900
  base = this.settle(base, mark);
901
+ this.refuseF64(node, "**", base, exp);
859
902
  if (base.literal !== undefined)
860
903
  base = this.literal(base.literal, hint?.kind === "int" ? hint : U64, node.left);
861
904
  if (base.type.kind !== "int")
@@ -985,6 +1028,7 @@ export class ExpressionEmitter extends StorageEmitter {
985
1028
  if (right.literal !== undefined)
986
1029
  right = this.literal(right.literal, U64, node.right);
987
1030
  left = this.settle(left, mark);
1031
+ this.refuseF64(node, ts.tokenToString(op) ?? "this operator", left, right);
988
1032
  if (left.type.kind !== "int" || right.type.kind !== "int")
989
1033
  this.fail(node, "shifts need integer operands");
990
1034
  return this.arith(op, left, right, node);
@@ -1008,6 +1052,7 @@ export class ExpressionEmitter extends StorageEmitter {
1008
1052
  right = this.expr(node.right, left.type.kind === "int" ? left.type : left.type.kind === "option" && left.type.inner.kind === "int" ? left.type.inner : undefined);
1009
1053
  left = this.settle(left, mark);
1010
1054
  }
1055
+ this.refuseF64(node, ts.tokenToString(op) ?? "this operator", left, right);
1011
1056
  // Option equality follows JS: null equals null, and an empty option equals no value.
1012
1057
  if (isEq && (left.type.kind === "option" || right.type.kind === "option")) {
1013
1058
  const neg = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
@@ -1074,6 +1119,7 @@ export class ExpressionEmitter extends StorageEmitter {
1074
1119
  }
1075
1120
  /** Checked integer arithmetic into a fresh temporary. */
1076
1121
  arith(op, left, right, node) {
1122
+ this.refuseF64(node, ts.tokenToString(op) ?? "arithmetic", left, right);
1077
1123
  if (left.type.kind !== "int")
1078
1124
  this.fail(node, "arithmetic needs integer operands");
1079
1125
  const type = left.type;
@@ -1135,7 +1181,7 @@ export class ExpressionEmitter extends StorageEmitter {
1135
1181
  if (right.type.kind !== "int")
1136
1182
  this.fail(node, "shift amounts must be integers");
1137
1183
  if (right.type.name === "u256")
1138
- this.fail(node, "shift by a u64 (or smaller) amount");
1184
+ this.fail(node, "a shift amount is a u128 or smaller integer: convert it (u64(n))");
1139
1185
  const bits = INT_INFO[type.name].bytes * 8;
1140
1186
  const sh = this.tmp("sh");
1141
1187
  const rinfo = INT_INFO[right.type.name];
@@ -1183,7 +1229,7 @@ export class ExpressionEmitter extends StorageEmitter {
1183
1229
  if (right.type.kind !== "int")
1184
1230
  this.fail(node, "shift amounts must be integers");
1185
1231
  if (right.type.name === "u256")
1186
- this.fail(node, "shift by a u64 (or smaller) amount");
1232
+ this.fail(node, "a shift amount is a u128 or smaller integer: convert it (u64(n))");
1187
1233
  const sh = this.tmp("sh");
1188
1234
  this.line(`if (${INT_INFO[right.type.name].signed ? `${right.c} < 0 || ` : ""}${right.c} >= 256) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: shift amount out of range");`);
1189
1235
  this.line(`uint64_t ${sh} = (uint64_t)(${right.c});`);
@@ -1206,6 +1252,8 @@ export class ExpressionEmitter extends StorageEmitter {
1206
1252
  return this.literal(v.literal, to, arg);
1207
1253
  if (v.type.kind !== "int")
1208
1254
  this.fail(arg, `${to.name}() needs an integer`);
1255
+ if (v.type.f64)
1256
+ this.fail(arg, F64_TO_INT(to.name));
1209
1257
  if (v.type.name === to.name)
1210
1258
  return v;
1211
1259
  const from = INT_INFO[v.type.name];
@@ -4,7 +4,8 @@ import { type OptionInner, type AccountParam, type FieldType, type ProgramModel,
4
4
  export declare const MAX_ACCOUNTS = 32;
5
5
  /** The most accounts one instruction takes: 32, or what the program declares with `const MAX_ACCOUNTS = …n` (33–255). */
6
6
  export declare function accountLimit(model: Pick<ProgramModel, "constants">): number;
7
- export declare const MAX_SEEDS = 15;
7
+ /** Solana's limit on the seeds of one address, the bump included (MAX_SEEDS of solana-pubkey; each seed at most 32 bytes). */
8
+ export declare const MAX_SEEDS = 16;
8
9
  /** Max instruction data an invoke() may build, and max event payload. */
9
10
  export declare const MAX_CPI_DATA = 1024;
10
11
  export declare const MAX_EVENT = 1024;
@@ -230,3 +231,9 @@ export declare function fixedVecC(t: FieldType & {
230
231
  * again after it: writeData, storeBorsh, another view). A BigVec slice's length is in range already.
231
232
  */
232
233
  export declare function vecCount(v: NonNullable<Ref["vec"]>): string;
234
+ /** An f64 used where an integer is expected (an assignment, an argument, a return, an index, a cast). */
235
+ export declare const F64_TO_INT: (to: string) => string;
236
+ /** An f64 in a template string or log(). */
237
+ export declare const F64_TEXT = "an f64 cannot be written as text: there is no float formatting, and the digits would be its IEEE 754 bits read as an integer; to show the bits, write f64Bits(x)";
238
+ /** An integer used where an f64 is expected. */
239
+ export declare const INT_TO_F64: (from: string) => string;
@@ -7,7 +7,8 @@ export function accountLimit(model) {
7
7
  const c = model.constants.get("MAX_ACCOUNTS");
8
8
  return c && typeof c.value === "bigint" && c.value >= 32n && c.value <= 255n ? Number(c.value) : MAX_ACCOUNTS;
9
9
  }
10
- export const MAX_SEEDS = 15; // + bump = 16, the runtime limit
10
+ /** Solana's limit on the seeds of one address, the bump included (MAX_SEEDS of solana-pubkey; each seed at most 32 bytes). */
11
+ export const MAX_SEEDS = 16;
11
12
  /** Max instruction data an invoke() may build, and max event payload. */
12
13
  export const MAX_CPI_DATA = 1024;
13
14
  export const MAX_EVENT = 1024;
@@ -323,3 +324,9 @@ export function vecCount(v) {
323
324
  return `((uint64_t)${v.len} < ${v.big} ? (uint64_t)${v.len} : ${v.big})`;
324
325
  return v.cap === undefined || v.heap ? `((uint64_t)${v.len})` : `((uint64_t)(${v.len} < ${v.cap} ? ${v.len} : ${v.cap}))`;
325
326
  }
327
+ /** An f64 used where an integer is expected (an assignment, an argument, a return, an index, a cast). */
328
+ export const F64_TO_INT = (to) => `an f64 is not an integer, so it is not converted to ${to}: it is held as its IEEE 754 bits, and the integer would be those bits; to use the bits, write f64Bits(x)`;
329
+ /** An f64 in a template string or log(). */
330
+ export const F64_TEXT = "an f64 cannot be written as text: there is no float formatting, and the digits would be its IEEE 754 bits read as an integer; to show the bits, write f64Bits(x)";
331
+ /** An integer used where an f64 is expected. */
332
+ export const INT_TO_F64 = (from) => `a ${from} is not an f64, so it is not converted: an f64 is made from its IEEE 754 bits with f64FromBits(bits)`;
@@ -3,9 +3,6 @@ import { type TypeScope } from "../analyze.js";
3
3
  import { type FieldType } from "../model.js";
4
4
  import { type Value, type Local, type Closure, type FunctionChoice, type Ref } from "./shared.js";
5
5
  import { CpiEmitter } from "./cpi.js";
6
- /**
7
- * Statements: variables, assignment, control flow and return.
8
- */
9
6
  export declare abstract class StatementEmitter extends CpiEmitter {
10
7
  protected statement(stmt: ts.Statement, topLevel?: boolean): void;
11
8
  protected statementInner(stmt: ts.Statement, topLevel: boolean): void;
@@ -172,6 +169,14 @@ export declare abstract class StatementEmitter extends CpiEmitter {
172
169
  * a field path (no calls), so reading it once per name reads the same thing JS reads once.
173
170
  */
174
171
  protected destructure(list: ts.VariableDeclarationList, d: ts.VariableDeclaration, pattern: ts.ObjectBindingPattern, init: ts.Expression, topLevel: boolean): void;
172
+ /** merkleVerify, verifyEd25519 or verifySecp256k1 when `e` (in parentheses, or under `!` if `negated`) calls one. */
173
+ protected verifierCall(e: ts.Expression, negated?: boolean): string | undefined;
174
+ /**
175
+ * `const ok = merkleVerify(…)` (or `ok = …`, the call in parentheses or under `as`) where the function that
176
+ * declares `ok` never reads it: nothing is checked. A read anywhere in that function counts, in a closure inside it
177
+ * and before the assignment too: this catches a result left unused, not every path.
178
+ */
179
+ protected refuseUnreadVerifier(name: ts.Identifier, value: ts.Expression): void;
175
180
  protected expressionStatement(e: ts.Expression, topLevel: boolean): void;
176
181
  protected assign(target: ts.Expression, valueNode: ts.Expression, op?: ts.BinaryOperator, topLevel?: boolean): void;
177
182
  }