@typesol/cli 0.47.0 → 0.49.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 (53) hide show
  1. package/CHANGELOG.md +299 -0
  2. package/NOTICE +17 -0
  3. package/README.md +106 -37
  4. package/SECURITY.md +5 -0
  5. package/dist/compiler/emit/base.d.ts +12 -4
  6. package/dist/compiler/emit/base.js +19 -5
  7. package/dist/compiler/emit/calls.js +59 -1
  8. package/dist/compiler/emit/cpi.js +3 -1
  9. package/dist/compiler/emit/expressions.js +3 -1
  10. package/dist/compiler/emit/function.js +7 -2
  11. package/dist/compiler/emit/program.js +9 -4
  12. package/dist/compiler/emit/statements.d.ts +29 -2
  13. package/dist/compiler/emit/statements.js +149 -6
  14. package/dist/compiler/emit/storage.js +8 -3
  15. package/dist/compiler/emit/token.js +18 -1
  16. package/dist/compiler/hints.js +3 -0
  17. package/dist/compiler/toolchain.js +1 -0
  18. package/dist/idl-coder.d.ts +21 -2
  19. package/dist/idl-coder.js +42 -4
  20. package/dist/testing.d.ts +14 -3
  21. package/dist/testing.js +87 -17
  22. package/docker/deps/0.48.0.lock.json +1206 -0
  23. package/docker/deps/0.49.0.lock.json +1206 -0
  24. package/docs/architecture.md +2 -2
  25. package/docs/audit.md +31 -15
  26. package/docs/case-study-escrow.md +7 -5
  27. package/docs/case-study-marginfi.md +15 -2
  28. package/docs/case-study-multisig.md +2 -1
  29. package/docs/case-study-raydium-amm.md +2 -1
  30. package/docs/case-study-spl-stake-pool.md +4 -3
  31. package/docs/language-accounts.md +5 -6
  32. package/docs/language-basics.md +2 -1
  33. package/docs/language-builtins.md +5 -1
  34. package/docs/language-chain.md +13 -1
  35. package/docs/language-cpi.md +26 -0
  36. package/docs/language-errors-events.md +16 -1
  37. package/docs/language-native.md +23 -3
  38. package/docs/language-statements.md +4 -2
  39. package/docs/language.md +2 -2
  40. package/docs/mainnet.md +1 -1
  41. package/docs/runtime.md +7 -0
  42. package/docs/security-model.md +11 -4
  43. package/docs/stability.md +9 -4
  44. package/docs/test-your-program.md +43 -4
  45. package/docs/testing.md +16 -4
  46. package/docs/troubleshooting.md +1 -1
  47. package/lib/typesol.d.ts +46 -1
  48. package/llms-full.txt +164 -34
  49. package/llms.txt +2 -1
  50. package/package.json +3 -3
  51. package/releases/0.47.0.json +837 -0
  52. package/releases/0.48.0.json +847 -0
  53. package/runtime/typesol_rt.h +276 -1
package/SECURITY.md CHANGED
@@ -8,6 +8,11 @@ TypeSOL generates programs that hold funds. Treat it accordingly.
8
8
  0.44.0 on 2026-11-11, found defects in the compiler (wrong token-wrapper instruction data, and a reference that could
9
9
  outlive a resize and reach another record) and a latent one in the runtime; they are fixed in 0.44.1. The one
10
10
  before it, of 0.43.0, found defects fixed in 0.44.0 (one of them could break an authorization check in a helper).
11
+ 0.45.0 to 0.49.0 have had no security review. They add, among others,
12
+ `runtime/typesol_builtins.c` (the compiler builtins as TypeSOL's own C, 0.45.0), `transferCheckedWithHook`,
13
+ `EVENT_AUTHORITY_CHECK` and the reads of processed sibling instructions (0.48.0), and `zeroData`, `log64`,
14
+ `PANIC_STYLE = "solana-1.18"`, `executable` on remaining accounts and lamport writes on remaining accounts under
15
+ `NATIVE_ACCOUNT_WRITES` (0.49.0).
11
16
  **Rebuild and redeploy programs built before 0.44.1**;
12
17
  [docs/security-model.md](docs/security-model.md#status) gives the status, its sections on each review say how to
13
18
  tell whether a program was exposed, and [docs/audit.md](docs/audit.md#earlier-reviews) what each review did and did
@@ -10,6 +10,12 @@ import { type Value, type Ref, type Local, type Closure, type FunctionChoice, ty
10
10
  export declare abstract class EmitterBase {
11
11
  protected readonly reporter: Reporter;
12
12
  protected readonly model: ProgramModel;
13
+ /**
14
+ * `const EVENT_AUTHORITY_CHECK = "address"`: Anchor 1.x's #[event_cpi] accounts. The event authority is checked by
15
+ * address among the constraints (ConstraintAddress, 2012) instead of by seeds when the accounts load (2006), and the
16
+ * program account is not checked: the event's self-CPI names this program's id, as Anchor's emit_cpi! does.
17
+ */
18
+ protected get eventAuthorityByAddress(): boolean;
13
19
  protected readonly imports: Map<string, string>;
14
20
  protected readonly accounts: Map<string, AccountParam>;
15
21
  protected readonly args: Map<string, Local>;
@@ -128,11 +134,13 @@ export declare abstract class EmitterBase {
128
134
  */
129
135
  protected nativeAccountWrites(): boolean;
130
136
  /**
131
- * `const PANIC_STYLE = "solana-1.14"`: a Rust panic logs what solana_program 1.14's panic handler logs (rustc before
132
- * 1.73 formats it as `panicked at '<message>', <file>:<line>:<col>`) and then aborts, so the runtime reports "SBF
133
- * program panicked"; by default it logs the message and calls sol_panic_ with the location.
137
+ * `const PANIC_STYLE = "solana-1.14"` / `"solana-1.18"`: a Rust panic logs what that solana-program's panic handler
138
+ * logs and then aborts, so the runtime reports "SBF program panicked". rustc before 1.73 (solana-program 1.14 to
139
+ * 1.17) formats a panic as `panicked at '<message>', <file>:<line>:<col>`; from 1.73 (solana-program 1.18's toolchain)
140
+ * as `panicked at <file>:<line>:<col>:\n<message>`, one log line holding the newline. By default it logs the message
141
+ * and calls sol_panic_ with the location.
134
142
  */
135
- protected panicStyle(): "solana-1.14" | undefined;
143
+ protected panicStyle(): "solana-1.14" | "solana-1.18" | undefined;
136
144
  /** The C statements of a Rust panic with `message` (undefined: nothing logged) at `location` ("file:line:col"). */
137
145
  protected panicC(message: string | undefined, location: string): string[];
138
146
  /** `file.ts:line:column` of a node (1-based, as Rust reports a location). */
@@ -9,6 +9,14 @@ import { isStable, cString, valueC, fixedVecC, passedByPointer, } from "./shared
9
9
  export class EmitterBase {
10
10
  reporter;
11
11
  model;
12
+ /**
13
+ * `const EVENT_AUTHORITY_CHECK = "address"`: Anchor 1.x's #[event_cpi] accounts. The event authority is checked by
14
+ * address among the constraints (ConstraintAddress, 2012) instead of by seeds when the accounts load (2006), and the
15
+ * program account is not checked: the event's self-CPI names this program's id, as Anchor's emit_cpi! does.
16
+ */
17
+ get eventAuthorityByAddress() {
18
+ return this.model.constants.get("EVENT_AUTHORITY_CHECK")?.value === "address";
19
+ }
12
20
  imports;
13
21
  accounts = new Map();
14
22
  args = new Map();
@@ -411,17 +419,23 @@ export class EmitterBase {
411
419
  return this.model.constants.get("NATIVE_ACCOUNT_WRITES")?.value === true;
412
420
  }
413
421
  /**
414
- * `const PANIC_STYLE = "solana-1.14"`: a Rust panic logs what solana_program 1.14's panic handler logs (rustc before
415
- * 1.73 formats it as `panicked at '<message>', <file>:<line>:<col>`) and then aborts, so the runtime reports "SBF
416
- * program panicked"; by default it logs the message and calls sol_panic_ with the location.
422
+ * `const PANIC_STYLE = "solana-1.14"` / `"solana-1.18"`: a Rust panic logs what that solana-program's panic handler
423
+ * logs and then aborts, so the runtime reports "SBF program panicked". rustc before 1.73 (solana-program 1.14 to
424
+ * 1.17) formats a panic as `panicked at '<message>', <file>:<line>:<col>`; from 1.73 (solana-program 1.18's toolchain)
425
+ * as `panicked at <file>:<line>:<col>:\n<message>`, one log line holding the newline. By default it logs the message
426
+ * and calls sol_panic_ with the location.
417
427
  */
418
428
  panicStyle() {
419
- return this.model.constants.get("PANIC_STYLE")?.value === "solana-1.14" ? "solana-1.14" : undefined;
429
+ const v = this.model.constants.get("PANIC_STYLE")?.value;
430
+ return v === "solana-1.14" || v === "solana-1.18" ? v : undefined;
420
431
  }
421
432
  /** The C statements of a Rust panic with `message` (undefined: nothing logged) at `location` ("file:line:col"). */
422
433
  panicC(message, location) {
423
- if (this.panicStyle())
434
+ const style = this.panicStyle();
435
+ if (style === "solana-1.14")
424
436
  return [`sol_log(${cString(`panicked at '${message}', ${location}`)});`, `abort();`, `__builtin_unreachable();`];
437
+ if (style === "solana-1.18")
438
+ return [`sol_log(${cString(`panicked at ${location}:\n${message}`)});`, `abort();`, `__builtin_unreachable();`];
425
439
  const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(location);
426
440
  const [file, line, col] = m ? [m[1], m[2], m[3] ?? "0"] : [location, "0", "0"];
427
441
  return [
@@ -57,6 +57,22 @@ export class CallEmitter extends ExpressionEmitter {
57
57
  this.fail(node, "stackHeight() takes no arguments");
58
58
  return { c: "sol_get_stack_height()", type: U64 };
59
59
  }
60
+ case "processedSiblingInstructionCount": {
61
+ if (args.length)
62
+ this.fail(node, "processedSiblingInstructionCount() takes no arguments");
63
+ const t = this.tmp("sibn");
64
+ this.line(`uint64_t ${t} = ts_sibling_count();`);
65
+ return { c: t, type: U64 };
66
+ }
67
+ case "processedSiblingInstruction": {
68
+ if (args.length !== 1)
69
+ this.fail(node, "processedSiblingInstruction(index) takes the sibling's index");
70
+ const i = this.expect(this.expr(args[0], U64), U64, args[0]);
71
+ const t = this.tmp("sib");
72
+ this.line(`TsIx ${t};`);
73
+ this.line(`TS_TRY(ts_sibling_load(${i.c}, &${t}));`);
74
+ return { c: t, type: { kind: "txIx" } };
75
+ }
60
76
  case "constraint":
61
77
  this.fail(node, "constraint(account, condition, error?) goes at the start of an instruction's body, before any other statement");
62
78
  case "require": {
@@ -107,7 +123,7 @@ export class CallEmitter extends ExpressionEmitter {
107
123
  this.fail(node, 'panic() takes an optional message (or null to log nothing) and an optional "file:line:column" location: string literals or string constants');
108
124
  const msg = silent ? undefined : args.length ? text(args[0]) : "explicit panic";
109
125
  if (silent && this.panicStyle())
110
- this.fail(args[0], 'under PANIC_STYLE "solana-1.14" a panic logs its message, as solana_program 1.14\'s panic handler always does: pass the message');
126
+ this.fail(args[0], "under PANIC_STYLE a panic logs its message, as solana_program's panic handler always does: pass the message");
111
127
  // The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"), or the panic line
112
128
  // logs: the given one, as a ported program's panic reports it, else this source line (with its column under
113
129
  // PANIC_STYLE, as Rust always gives one).
@@ -847,6 +863,46 @@ export class CallEmitter extends ExpressionEmitter {
847
863
  this.line(`sol_set_return_data((const uint8_t *)${s.items}, ${s.count});`);
848
864
  return undefined;
849
865
  }
866
+ case "zeroData": {
867
+ // Rust's `for b in data[offset..offset + length].iter_mut() { *b = 0; }` (a memset): the memset syscall, about
868
+ // constant compute units whatever the length, as the original's compiled loop.
869
+ if (args.length !== 3)
870
+ this.fail(node, "zeroData(account, offset, length) takes an account, a byte offset and a length");
871
+ // The length does not change: views of the account made before stay valid (they read the zeros).
872
+ let a = this.handle(args[0]);
873
+ if (a) {
874
+ if (!this.nativeAccountWrites())
875
+ this.line(`TS_TRY(ts_check_writable(${a}));`);
876
+ }
877
+ else {
878
+ const acct = this.accountParam(args[0], "zeroData's account");
879
+ if (acct.kind.kind !== "info" || (!isWritable(acct.kind) && !this.nativeAccountWrites()))
880
+ this.fail(args[0], "zeroData needs a Mut<AccountInfo> parameter or a remaining account");
881
+ a = `a_${acct.name}`;
882
+ }
883
+ const off = this.expect(this.expr(args[1], U64), U64, args[1]);
884
+ const o = this.tmp("off");
885
+ this.line(`uint64_t ${o} = ${off.c};`);
886
+ const len = this.expect(this.expr(args[2], U64), U64, args[2]);
887
+ const n = this.tmp("len");
888
+ this.line(`uint64_t ${n} = ${len.c};`);
889
+ this.line(`if (${o} > ${a}->data_len || ${a}->data_len - ${o} < ${n}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: write past the end of the account data");`);
890
+ this.line(`ts_memzero_bulk(${a}->data + ${o}, ${n});`);
891
+ return undefined;
892
+ }
893
+ case "log64": {
894
+ // Rust's `sol_log_64(a, b, c, d, e)`: the runtime writes "Program log: 0x<a>, 0x<b>, 0x<c>, 0x<d>, 0x<e>" (hex).
895
+ if (args.length !== 5)
896
+ this.fail(node, "log64(a, b, c, d, e) takes five u64 values");
897
+ const vs = args.map((a) => this.expect(this.expr(a, U64), U64, a).c);
898
+ const ts_ = vs.map((v) => {
899
+ const t = this.tmp("l64");
900
+ this.line(`uint64_t ${t} = ${v};`);
901
+ return t;
902
+ });
903
+ this.line(`sol_log_64(${ts_.join(", ")});`);
904
+ return undefined;
905
+ }
850
906
  case "logComputeUnits": {
851
907
  if (args.length)
852
908
  this.fail(node, "logComputeUnits() takes no arguments");
@@ -1598,6 +1654,8 @@ export class CallEmitter extends ExpressionEmitter {
1598
1654
  return this.isTxIx(node.expression);
1599
1655
  if (ts.isIdentifier(node))
1600
1656
  return this.lookup(node.text)?.type.kind === "txIx";
1657
+ if (ts.isCallExpression(node) && this.exportName(node.expression) === "processedSiblingInstruction")
1658
+ return true;
1601
1659
  return (ts.isCallExpression(node) &&
1602
1660
  ts.isPropertyAccessExpression(node.expression) &&
1603
1661
  node.expression.name.text === "get" &&
@@ -466,7 +466,9 @@ export class CpiEmitter extends MetaplexEmitter {
466
466
  const signer = this.tmp("signer");
467
467
  this.line(`SolAccountMeta ${m}[1] = {{&a_${cpi.authority}->key, false, true}};`);
468
468
  this.line(`SolSignerSeed ${sd}[2] = {{(const uint8_t *)"__event_authority", 17}, {&eb_${cpi.authority}, 1}};`);
469
- this.line(`SolInstruction ${ix} = {&a_${cpi.program}->key, ${m}, 1, ${buf}, ${len}};`);
469
+ // EVENT_AUTHORITY_CHECK = "address": the program account is unchecked, so the CPI names this program's id.
470
+ const target = this.eventAuthorityByAddress ? `(SolPubkey *)params->program_id` : `&a_${cpi.program}->key`;
471
+ this.line(`SolInstruction ${ix} = {${target}, ${m}, 1, ${buf}, ${len}};`);
470
472
  this.line(`SolSignerSeeds ${signer} = {${sd}, 2};`);
471
473
  this.line(`TS_TRY(ts_invoke(params, &${ix}, &${signer}, 1));`);
472
474
  return;
@@ -493,8 +493,10 @@ export class ExpressionEmitter extends StorageEmitter {
493
493
  return { c: `${h}->is_signer`, type: BOOL };
494
494
  case "isWritable":
495
495
  return { c: `${h}->is_writable`, type: BOOL };
496
+ case "executable":
497
+ return { c: `${h}->executable`, type: BOOL };
496
498
  }
497
- this.fail(node.name, `remaining accounts expose key, owner, lamports, dataLen, isSigner and isWritable, not ${field}`);
499
+ this.fail(node.name, `remaining accounts expose key, owner, lamports, dataLen, isSigner, isWritable and executable, not ${field}`);
498
500
  }
499
501
  // A struct loaded with loadAccount / loadAccountMut is also its account: key, lamports, dataLen, isSigner, isWritable.
500
502
  if (ts.isIdentifier(node.expression)) {
@@ -84,9 +84,12 @@ export class FunctionEmitter extends StatementEmitter {
84
84
  // constraint order), as Anchor's `#[account(address = sysvar::instructions::ID)]` on an UncheckedAccount.
85
85
  if (k.kind === "instructionsSysvar" && !a.constraints.address)
86
86
  head.push(` TS_TRY(ts_check_address(${v}, &TS_INSTRUCTIONS_SYSVAR_ID));`);
87
- if (k.kind === "eventAuthority")
87
+ if (k.kind === "eventAuthority" && this.eventAuthorityByAddress)
88
+ // Anchor 1.x: the address is checked among the constraints (constraintChecks); here only the PDA and its bump.
89
+ head.push(` uint8_t eb_${a.name};`, ` SolPubkey ek_${a.name};`, ` { SolSignerSeed s = {(const uint8_t *)"__event_authority", 17}; if (ts_find_pda(&s, 1, params->program_id, &ek_${a.name}, &eb_${a.name}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no event authority"); }`);
90
+ else if (k.kind === "eventAuthority")
88
91
  head.push(` uint8_t eb_${a.name};`, ` TS_TRY(ts_check_event_authority(${v}, params->program_id, &eb_${a.name}));`);
89
- if (k.kind === "selfProgram")
92
+ if (k.kind === "selfProgram" && !this.eventAuthorityByAddress)
90
93
  head.push(` if (!ts_key_eq(&${v}->key, params->program_id)) TS_FAIL(TS_ERR_WRONG_PROGRAM, "TypeSOL: expected this program");`);
91
94
  if (k.kind === "programData")
92
95
  head.push(` TS_TRY(ts_check_program_data(${v}, params->program_id));`);
@@ -667,6 +670,8 @@ export class FunctionEmitter extends StatementEmitter {
667
670
  }
668
671
  if (c.executable)
669
672
  out.push(` if (!a_${a.name}->executable) TS_FAIL(TS_ERR_CONSTRAINT_EXECUTABLE, "TypeSOL: ${a.name} must be an executable program");`);
673
+ if (k === "eventAuthority" && this.eventAuthorityByAddress)
674
+ out.push(` if (!ts_key_eq(&a_${a.name}->key, &ek_${a.name})) TS_FAIL(TS_ERR_ADDRESS, "TypeSOL: ${a.name} is not this program's event authority");`);
670
675
  if (c.address) {
671
676
  out.push(` static const SolPubkey ca_${a.name} = {${cBytes(c.address.bytes)}};`);
672
677
  out.push(` if (!ts_key_eq(&a_${a.name}->key, &ca_${a.name})) ${this.checkFail(a, "address", "TS_ERR_ADDRESS", `${a.name} is not the expected address`)};`);
@@ -59,15 +59,20 @@ export function emitProgram(analysis, opts = {}) {
59
59
  else if (panicFlag.value)
60
60
  out.push(`#define TS_PANIC_ON_OVERFLOW 1`);
61
61
  }
62
- // `const PANIC_STYLE = "solana-1.14"`: panics log as solana_program 1.14's panic handler does and abort (read by the
63
- // emitter); PANIC_ON_OVERFLOW's panics abort too instead of calling sol_panic_.
62
+ // `const PANIC_STYLE = "solana-1.14"` / `"solana-1.18"`: panics log as that solana_program's panic handler does and
63
+ // abort (read by the emitter); PANIC_ON_OVERFLOW's panics abort too instead of calling sol_panic_.
64
64
  const panicStyle = model.constants.get("PANIC_STYLE");
65
65
  if (panicStyle) {
66
- if (panicStyle.value !== "solana-1.14")
67
- reporter.error(analysis.sourceFile, "PANIC_STYLE must be \"solana-1.14\" (panics log `panicked at '<message>', <file>:<line>:<col>` and abort, as programs built with solana-program 1.14 to 1.17 do); leave it out for the default");
66
+ if (panicStyle.value !== "solana-1.14" && panicStyle.value !== "solana-1.18")
67
+ reporter.error(analysis.sourceFile, 'PANIC_STYLE must be "solana-1.14" (panics log `panicked at \'<message>\', <file>:<line>:<col>` and abort, as programs built with solana-program 1.14 to 1.17 do) or "solana-1.18" (`panicked at <file>:<line>:<col>:` and the message on the next line, then abort, as solana-program 1.18\'s); leave it out for the default');
68
68
  else if (panicFlag?.value === true)
69
69
  out.push(`#define TS_PANIC_ABORT 1`);
70
70
  }
71
+ // `const EVENT_AUTHORITY_CHECK = "address"`: the emitCpi accounts are checked as Anchor 1.x's #[event_cpi] checks
72
+ // them (read by the emitter; nothing to define in C).
73
+ const eventCheck = model.constants.get("EVENT_AUTHORITY_CHECK");
74
+ if (eventCheck && eventCheck.value !== "address")
75
+ reporter.error(analysis.sourceFile, 'EVENT_AUTHORITY_CHECK must be "address" (the event authority checked as Anchor 1.x\'s `address = EVENT_AUTHORITY` constraint, 2012 among the constraints, and the program account left unchecked); leave it out for the default');
71
76
  // `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut / storeBorsh / BigVec writes leave writability and aliasing to the
72
77
  // runtime, as a native program does (read by the emitter; nothing to define in C).
73
78
  const nativeWrites = model.constants.get("NATIVE_ACCOUNT_WRITES");
@@ -3,6 +3,11 @@ 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
+ /** A call whose result is a proof or signature check: a built-in, or a helper (`name`) returning the result of one (`wraps`). */
7
+ interface CheckCall {
8
+ name: string;
9
+ wraps?: string;
10
+ }
6
11
  export declare abstract class StatementEmitter extends CpiEmitter {
7
12
  protected statement(stmt: ts.Statement, topLevel?: boolean): void;
8
13
  protected statementInner(stmt: ts.Statement, topLevel: boolean): void;
@@ -169,8 +174,29 @@ export declare abstract class StatementEmitter extends CpiEmitter {
169
174
  * a field path (no calls), so reading it once per name reads the same thing JS reads once.
170
175
  */
171
176
  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;
177
+ /**
178
+ * The check `e` (in parentheses, or under `!` if `negated`) calls: merkleVerify, verifyEd25519 or verifySecp256k1,
179
+ * or a helper that returns the result of one (see returnedCheck).
180
+ */
181
+ protected verifierCall(e: ts.Expression, negated?: boolean): CheckCall | undefined;
182
+ /** The built-in whose result a function declared where it is called (a closure) returns, if it does. */
183
+ private localFunctionCheck;
184
+ /** Helpers whose returnedCheck is known (null: none), and the ones being looked at (recursion). */
185
+ private readonly checkMemo;
186
+ private readonly checkActive;
187
+ private checkMetActive;
188
+ /** The built-in whose result the helper or generic helper `name` returns, if it does. */
189
+ private helperCheck;
190
+ /**
191
+ * The built-in check (merkleVerify, verifyEd25519 or verifySecp256k1) a helper's result comes from: a `return` that
192
+ * yields its result, or a helper's that returns one, directly, in parentheses or under `as`, combined with `&&`,
193
+ * `||`, `!` or `?:`, or through a local of the helper that was given such a value and is read only in returns. A
194
+ * helper that acts on the result itself (requires it, branches on it) and returns something else returns no check.
195
+ * A helper still being looked at (recursion) counts as returning none.
196
+ */
197
+ private returnedCheck;
198
+ /** The built-in check whose result the value `e`, returned by `fn`, carries (see returnedCheck). */
199
+ private checkIn;
174
200
  /**
175
201
  * `const ok = merkleVerify(…)` (or `ok = …`, the call in parentheses or under `as`) where the function that
176
202
  * declares `ok` never reads it: nothing is checked. A read anywhere in that function counts, in a closure inside it
@@ -180,3 +206,4 @@ export declare abstract class StatementEmitter extends CpiEmitter {
180
206
  protected expressionStatement(e: ts.Expression, topLevel: boolean): void;
181
207
  protected assign(target: ts.Expression, valueNode: ts.Expression, op?: ts.BinaryOperator, topLevel?: boolean): void;
182
208
  }
209
+ export {};
@@ -1,14 +1,16 @@
1
1
  import ts from "typescript";
2
2
  import { MAX_RETURN_DATA, calleeName, resolveScalarType, resolveValueType, structNameOf, typesolName } from "../analyze.js";
3
- import { INT_INFO, isScalar, optionKey, sameType, scalarSize, typeName } from "../model.js";
3
+ import { INT_INFO, isScalar, optionKey, sameType, scalarSize, typeName, } from "../model.js";
4
4
  import { U64, BOOL, PUBKEY, cString, fixedVecC, helperSignature, optC, scalarC, scalarStorageC, storageDecl, valueC, } from "./shared.js";
5
5
  import { CpiEmitter } from "./cpi.js";
6
6
  import { cTokens, declaredNames, isGlobalName, parameterDecls, usedNames } from "./outline.js";
7
7
  /**
8
8
  * Statements: variables, assignment, control flow and return.
9
9
  */
10
+ /** The built-ins that return whether a proof or signature holds, and fail nothing by themselves. */
11
+ const VERIFIERS = new Set(["merkleVerify", "verifyEd25519", "verifySecp256k1"]);
10
12
  /** A proof or signature check whose result decides nothing: `how` says why (discarded, never read, an empty if). */
11
- const VERIFIER_UNUSED = (checker, how) => `the result of ${checker} ${how}, so nothing is checked: it returns whether the ${checker === "merkleVerify" ? "proof" : "signature"} holds; write require(${checker}(…), error)`;
13
+ const VERIFIER_UNUSED = (call, how) => `the result of ${call.name} ${how}, so nothing is checked: ${call.wraps ? `it returns the result of ${call.wraps}` : `it returns whether the ${call.name === "merkleVerify" ? "proof" : "signature"} holds`}; write require(${call.name}(…), error)`;
12
14
  export class StatementEmitter extends CpiEmitter {
13
15
  statement(stmt, topLevel = false) {
14
16
  const outer = this.where;
@@ -1902,14 +1904,155 @@ export class StatementEmitter extends CpiEmitter {
1902
1904
  this.variable({ ...list, declarations: [decl] }, topLevel);
1903
1905
  }
1904
1906
  }
1905
- /** merkleVerify, verifyEd25519 or verifySecp256k1 when `e` (in parentheses, or under `!` if `negated`) calls one. */
1907
+ /**
1908
+ * The check `e` (in parentheses, or under `!` if `negated`) calls: merkleVerify, verifyEd25519 or verifySecp256k1,
1909
+ * or a helper that returns the result of one (see returnedCheck).
1910
+ */
1906
1911
  verifierCall(e, negated = false) {
1907
1912
  while (ts.isParenthesizedExpression(e) || (negated && ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.ExclamationToken))
1908
1913
  e = ts.isParenthesizedExpression(e) ? e.expression : e.operand;
1909
- if (!ts.isCallExpression(e))
1914
+ if (!ts.isCallExpression(e) || !ts.isIdentifier(e.expression))
1915
+ return undefined;
1916
+ const builtin = this.exportName(e.expression);
1917
+ if (builtin)
1918
+ return VERIFIERS.has(builtin) ? { name: builtin } : undefined;
1919
+ // The helper the call runs, found as helperOf finds it but without instantiating a generic one.
1920
+ const callee = e.expression;
1921
+ const name = this.helper?.fnArgs?.get(callee.text) ?? calleeName(callee, this.model.helperDecls, this.checker) ?? (this.lookup(callee.text) ? undefined : callee.text);
1922
+ const wraps = name !== undefined ? this.helperCheck(name) : this.localFunctionCheck(callee, this.imports);
1923
+ return wraps ? { name: callee.text, wraps } : undefined;
1924
+ }
1925
+ /** The built-in whose result a function declared where it is called (a closure) returns, if it does. */
1926
+ localFunctionCheck(callee, imports) {
1927
+ const decl = this.checker.getSymbolAtLocation(callee)?.valueDeclaration;
1928
+ const init = decl && ts.isVariableDeclaration(decl) ? decl.initializer : undefined;
1929
+ const fn = init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) ? init : decl && ts.isFunctionDeclaration(decl) ? decl : undefined;
1930
+ return fn ? this.returnedCheck(fn, imports) : undefined;
1931
+ }
1932
+ /** Helpers whose returnedCheck is known (null: none), and the ones being looked at (recursion). */
1933
+ checkMemo = new Map();
1934
+ checkActive = new Set();
1935
+ checkMetActive = false;
1936
+ /** The built-in whose result the helper or generic helper `name` returns, if it does. */
1937
+ helperCheck(name) {
1938
+ const h = this.model.helpers.get(name) ?? this.model.generics.get(name);
1939
+ return h ? this.returnedCheck(h.node, h.imports) : undefined;
1940
+ }
1941
+ /**
1942
+ * The built-in check (merkleVerify, verifyEd25519 or verifySecp256k1) a helper's result comes from: a `return` that
1943
+ * yields its result, or a helper's that returns one, directly, in parentheses or under `as`, combined with `&&`,
1944
+ * `||`, `!` or `?:`, or through a local of the helper that was given such a value and is read only in returns. A
1945
+ * helper that acts on the result itself (requires it, branches on it) and returns something else returns no check.
1946
+ * A helper still being looked at (recursion) counts as returning none.
1947
+ */
1948
+ returnedCheck(fn, imports) {
1949
+ const known = this.checkMemo.get(fn);
1950
+ if (known !== undefined)
1951
+ return known ?? undefined;
1952
+ if (this.checkActive.has(fn)) {
1953
+ this.checkMetActive = true;
1910
1954
  return undefined;
1911
- const name = this.exportName(e.expression);
1912
- return name === "merkleVerify" || name === "verifyEd25519" || name === "verifySecp256k1" ? name : undefined;
1955
+ }
1956
+ const outer = this.checkMetActive;
1957
+ this.checkMetActive = false;
1958
+ this.checkActive.add(fn);
1959
+ let found;
1960
+ try {
1961
+ const returns = [];
1962
+ if (fn.body && !ts.isBlock(fn.body))
1963
+ returns.push(fn.body);
1964
+ else if (fn.body) {
1965
+ const visit = (n) => {
1966
+ if (ts.isFunctionLike(n))
1967
+ return;
1968
+ if (ts.isReturnStatement(n) && n.expression)
1969
+ returns.push(n.expression);
1970
+ ts.forEachChild(n, visit);
1971
+ };
1972
+ visit(fn.body);
1973
+ }
1974
+ for (const r of returns)
1975
+ if ((found = this.checkIn(r, fn, imports, new Set())))
1976
+ break;
1977
+ }
1978
+ finally {
1979
+ this.checkActive.delete(fn);
1980
+ }
1981
+ // "None" found while a helper further up was still open may change once it is known: not kept.
1982
+ if (found || !this.checkMetActive)
1983
+ this.checkMemo.set(fn, found ?? null);
1984
+ this.checkMetActive ||= outer;
1985
+ return found;
1986
+ }
1987
+ /** The built-in check whose result the value `e`, returned by `fn`, carries (see returnedCheck). */
1988
+ checkIn(e, fn, imports, seen) {
1989
+ while (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isNonNullExpression(e) || ts.isSatisfiesExpression(e))
1990
+ e = e.expression;
1991
+ if (ts.isCallExpression(e)) {
1992
+ if (!ts.isIdentifier(e.expression))
1993
+ return undefined;
1994
+ const builtin = imports.get(e.expression.text);
1995
+ if (builtin)
1996
+ return VERIFIERS.has(builtin) ? builtin : undefined;
1997
+ const name = calleeName(e.expression, this.model.helperDecls, this.checker);
1998
+ return name !== undefined ? this.helperCheck(name) : this.localFunctionCheck(e.expression, imports);
1999
+ }
2000
+ if (ts.isPrefixUnaryExpression(e))
2001
+ return e.operator === ts.SyntaxKind.ExclamationToken ? this.checkIn(e.operand, fn, imports, seen) : undefined;
2002
+ if (ts.isBinaryExpression(e)) {
2003
+ const op = e.operatorToken.kind;
2004
+ if (op !== ts.SyntaxKind.AmpersandAmpersandToken && op !== ts.SyntaxKind.BarBarToken)
2005
+ return undefined;
2006
+ return this.checkIn(e.left, fn, imports, seen) ?? this.checkIn(e.right, fn, imports, seen);
2007
+ }
2008
+ if (ts.isConditionalExpression(e))
2009
+ return this.checkIn(e.condition, fn, imports, seen) ?? this.checkIn(e.whenTrue, fn, imports, seen) ?? this.checkIn(e.whenFalse, fn, imports, seen);
2010
+ if (!ts.isIdentifier(e))
2011
+ return undefined;
2012
+ // A local of `fn` (not of a closure in it), every value it is given, when nothing but a return reads it.
2013
+ const symbol = this.checker.getSymbolAtLocation(e);
2014
+ const decl = symbol?.valueDeclaration;
2015
+ if (!symbol || !decl || !ts.isVariableDeclaration(decl) || seen.has(symbol))
2016
+ return undefined;
2017
+ let owner = decl.parent;
2018
+ while (owner && !ts.isFunctionLike(owner))
2019
+ owner = owner.parent;
2020
+ if (owner !== fn)
2021
+ return undefined;
2022
+ seen.add(symbol);
2023
+ const values = decl.initializer ? [decl.initializer] : [];
2024
+ const inReturn = (n) => {
2025
+ for (let p = n.parent; p && p !== fn; p = p.parent) {
2026
+ if (ts.isReturnStatement(p))
2027
+ return true;
2028
+ if (ts.isFunctionLike(p))
2029
+ return false; // read in a closure: it may act on it
2030
+ }
2031
+ return !!fn.body && !ts.isBlock(fn.body);
2032
+ };
2033
+ let actedOn = false;
2034
+ const visit = (n) => {
2035
+ if (actedOn)
2036
+ return;
2037
+ if (ts.isIdentifier(n) && n !== decl.name && this.checker.getSymbolAtLocation(n) === symbol) {
2038
+ const p = n.parent;
2039
+ if (ts.isBinaryExpression(p) && p.left === n && p.operatorToken.kind === ts.SyntaxKind.EqualsToken)
2040
+ values.push(p.right);
2041
+ else if (!inReturn(n))
2042
+ actedOn = true;
2043
+ }
2044
+ ts.forEachChild(n, visit);
2045
+ };
2046
+ if (fn.body)
2047
+ visit(fn.body);
2048
+ if (actedOn)
2049
+ return undefined;
2050
+ for (const v of values) {
2051
+ const found = this.checkIn(v, fn, imports, seen);
2052
+ if (found)
2053
+ return found;
2054
+ }
2055
+ return undefined;
1913
2056
  }
1914
2057
  /**
1915
2058
  * `const ok = merkleVerify(…)` (or `ok = …`, the call in parentheses or under `as`) where the function that
@@ -901,9 +901,14 @@ export class StorageEmitter extends AliasEmitter {
901
901
  const h = this.handle(node.expression);
902
902
  if (h) {
903
903
  // Remaining accounts carry no static guarantees: check writability where it is written, and that it is not
904
- // also another (declared or remaining) account, which would let one balance be counted twice.
905
- this.line(`TS_TRY(ts_check_writable(${h}));`);
906
- this.line(`TS_TRY(ts_check_unaliased(params, ${h}));`);
904
+ // also another (declared or remaining) account, which would let one balance be counted twice. Under
905
+ // NATIVE_ACCOUNT_WRITES the write is a native program's `**a.lamports.borrow_mut() = v`: an account passed twice
906
+ // shares one record (as Rust's duplicate AccountInfos share one RefCell), and the runtime judges writability
907
+ // when the instruction ends (ReadonlyLamportChange / UnbalancedInstruction).
908
+ if (!this.nativeAccountWrites()) {
909
+ this.line(`TS_TRY(ts_check_writable(${h}));`);
910
+ this.line(`TS_TRY(ts_check_unaliased(params, ${h}));`);
911
+ }
907
912
  return { type: U64, read: `${h}->lamports`, write: (c) => `${h}->lamports = ${c}` };
908
913
  }
909
914
  }
@@ -54,6 +54,23 @@ export class TokenEmitter extends CreateEmitter {
54
54
  this.line(`TS_TRY(ts_token_transfer_checked(params, ${p}, ${from.c}, ${mint.c}, ${to.c}, ${auth.c}, ${amt}, ${s.name}, ${s.count}));`);
55
55
  return undefined;
56
56
  }
57
+ case "transferCheckedWithHook": {
58
+ // transferChecked with a transfer hook's extra accounts, resolved among `hookAccounts` (a remaining-accounts
59
+ // range) as spl-transfer-hook-interface's add_extra_accounts_for_execute_cpi resolves them on chain.
60
+ if (a.length !== 6 && a.length !== 7)
61
+ this.fail(node, "transferCheckedWithHook(from, mint, to, authority, amount, hookAccounts, signerSeeds?)");
62
+ const from = want(a[0], "token", true, "the source");
63
+ const mint = want(a[1], "mint", false, "the mint");
64
+ const to = want(a[2], "token", true, "the destination");
65
+ const auth = this.cpiAccount(a[3], "the authority");
66
+ const amt = this.expect(this.expr(a[4], U64), U64, a[4]);
67
+ const held = this.tmp("amt");
68
+ this.line(`uint64_t ${held} = ${amt.c};`);
69
+ const range = this.remainingRange(a[5]) ?? this.fail(a[5], "pass the hook's accounts as remainingAccounts() or rest.slice(a, b)");
70
+ const s = this.signerSeeds(a[6], auth, a[3]);
71
+ this.line(`TS_TRY(ts_token_transfer_checked_hook(params, ${p}, ${from.c}, ${mint.c}, ${to.c}, ${auth.c}, ${held}, ${range.base} + ${range.from}, ${range.base} + ${range.to}, ${s.name}, ${s.count}));`);
72
+ return undefined;
73
+ }
57
74
  case "mintTo": {
58
75
  arity(4);
59
76
  // A Mut<Mint>, or a mint created and initialized earlier in this instruction (Mut<Signer> / Mut<AccountInfo>).
@@ -608,7 +625,7 @@ export class TokenEmitter extends CreateEmitter {
608
625
  return undefined;
609
626
  }
610
627
  }
611
- this.fail(node.expression, `token programs support transfer, transferChecked, mintTo, burn, closeAccount, approve, revoke, setAuthority, freezeAccount, thawAccount, syncNative, initializeMint2, initializeAccount3, initializeMetadata, updateMetadataField, removeMetadataKey, updateMetadataAuthority, emitMetadata, the Token-2022 extension instructions (updateDefaultAccountState, updateTransferHook, enableRequiredMemoTransfers, disableRequiredMemoTransfers, updateInterestRate, transferCheckedWithFee, harvestWithheldTokensToMint, withdrawWithheldTokensFromMint, setTransferFee) and initializers (initializeTransferFeeConfig, initializeMintCloseAuthority, initializeNonTransferableMint, initializePermanentDelegate, initializeDefaultAccountState, initializeMetadataPointer, initializeGroupPointer, initializeGroupMemberPointer, initializeTransferHook, initializeInterestBearingMint, initializeImmutableOwner), not ${method}`);
628
+ this.fail(node.expression, `token programs support transfer, transferChecked, transferCheckedWithHook, mintTo, burn, closeAccount, approve, revoke, setAuthority, freezeAccount, thawAccount, syncNative, initializeMint2, initializeAccount3, initializeMetadata, updateMetadataField, removeMetadataKey, updateMetadataAuthority, emitMetadata, the Token-2022 extension instructions (updateDefaultAccountState, updateTransferHook, enableRequiredMemoTransfers, disableRequiredMemoTransfers, updateInterestRate, transferCheckedWithFee, harvestWithheldTokensToMint, withdrawWithheldTokensFromMint, setTransferFee) and initializers (initializeTransferFeeConfig, initializeMintCloseAuthority, initializeNonTransferableMint, initializePermanentDelegate, initializeDefaultAccountState, initializeMetadataPointer, initializeGroupPointer, initializeGroupMemberPointer, initializeTransferHook, initializeInterestBearingMint, initializeImmutableOwner), not ${method}`);
612
629
  }
613
630
  ataOp(node, program, method) {
614
631
  if (method !== "create" && method !== "createIdempotent")
@@ -91,6 +91,9 @@ export function hintForTypeScript(d, message, libPath) {
91
91
  case 2365: // Operator '+=' cannot be applied to types 'bigint' and 'number'.
92
92
  case 2322: // Type 'number' is not assignable to type 'bigint'.
93
93
  case 2345: // Argument of type 'bigint' is not assignable to parameter of type 'number'.
94
+ // Argument of type 'TokenAccount' is not assignable to parameter of type 'RemainingAccount | AccountInfo'.
95
+ if (/parameter of type '(?:RemainingAccount \| AccountInfo|AccountInfo \| RemainingAccount)'/.test(message))
96
+ return "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter; a declared parameter of a program or sysvar type is used as it is";
94
97
  if (/\bDate\.now\(|\bnew Date\b/.test(line))
95
98
  return CLOCK_HINT;
96
99
  if (/\bMath\.\w+\(/.test(line))
@@ -199,6 +199,7 @@ export const SYSCALLS = [
199
199
  "sol_get_epoch_rewards_sysvar",
200
200
  "sol_get_epoch_schedule_sysvar",
201
201
  "sol_get_last_restart_slot",
202
+ "sol_get_processed_sibling_instruction",
202
203
  "sol_get_rent_sysvar",
203
204
  "sol_get_return_data",
204
205
  "sol_get_stack_height",
@@ -65,15 +65,25 @@ export interface CoderIdl {
65
65
  name: string;
66
66
  discriminator: readonly number[];
67
67
  }[];
68
+ events?: readonly {
69
+ name: string;
70
+ discriminator: readonly number[];
71
+ }[];
68
72
  types?: readonly unknown[];
69
73
  }
74
+ export interface IdlCoderOptions {
75
+ /** A missing field or argument that is not an Option, or a key that names none, is an error (default false). */
76
+ strict?: boolean;
77
+ }
70
78
  export declare class IdlCoder {
71
79
  private readonly types;
72
80
  private readonly instructions;
73
81
  private readonly accountDefs;
82
+ private readonly eventDefs;
83
+ private readonly strict;
74
84
  private readonly enc;
75
85
  private readonly dec;
76
- constructor(idl: CoderIdl);
86
+ constructor(idl: CoderIdl, options?: IdlCoderOptions);
77
87
  private resolve;
78
88
  private arrayLen;
79
89
  /** A defined type and the environment its fields are read in. */
@@ -88,7 +98,8 @@ export declare class IdlCoder {
88
98
  private items;
89
99
  /**
90
100
  * A struct's fields in order. A field left undefined is written as zeros when its size is fixed (what Anchor's coder
91
- * does); a variable-size one cannot be, and throws.
101
+ * does); a variable-size one cannot be, and throws. Strict: a missing field that is not an Option, and a key that
102
+ * names no field, throw.
92
103
  */
93
104
  private fields;
94
105
  /** Instruction data: the IDL's discriminator, then the arguments. */
@@ -105,6 +116,14 @@ export declare class IdlCoder {
105
116
  decodeAccount(name: string, data: Uint8Array): Record<string, unknown>;
106
117
  /** A defined type read from the start of `data`. Bytes after it are ignored. */
107
118
  decodeType(name: string, data: Uint8Array): unknown;
119
+ /**
120
+ * An event's name and fields from its bytes (the discriminator, then the fields), as Anchor's `coder.events.decode`
121
+ * gives them from the same bytes in base64; null when the bytes start with none of the IDL's event discriminators.
122
+ */
123
+ decodeEvent(data: Uint8Array): {
124
+ name: string;
125
+ data: Record<string, unknown>;
126
+ } | null;
108
127
  /** An instruction's arguments read back from its data (after checking the discriminator). */
109
128
  decodeInstruction(name: string, data: Uint8Array): Record<string, unknown>;
110
129
  }