@typesol/cli 0.38.0 → 0.40.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 (61) hide show
  1. package/CHANGELOG.md +373 -2
  2. package/README.md +43 -26
  3. package/SECURITY.md +1 -1
  4. package/dist/cli.js +37 -3
  5. package/dist/compiler/analyze.d.ts +6 -11
  6. package/dist/compiler/analyze.js +331 -34
  7. package/dist/compiler/emit/alias.js +3 -2
  8. package/dist/compiler/emit/base.d.ts +7 -1
  9. package/dist/compiler/emit/base.js +2 -0
  10. package/dist/compiler/emit/borsh.js +63 -2
  11. package/dist/compiler/emit/calls.d.ts +14 -1
  12. package/dist/compiler/emit/calls.js +311 -21
  13. package/dist/compiler/emit/cpi-core.js +17 -5
  14. package/dist/compiler/emit/cpi.js +81 -27
  15. package/dist/compiler/emit/create.d.ts +7 -0
  16. package/dist/compiler/emit/create.js +27 -0
  17. package/dist/compiler/emit/expressions.d.ts +6 -0
  18. package/dist/compiler/emit/expressions.js +102 -6
  19. package/dist/compiler/emit/function.d.ts +7 -0
  20. package/dist/compiler/emit/function.js +164 -29
  21. package/dist/compiler/emit/program.js +27 -2
  22. package/dist/compiler/emit/shared.d.ts +15 -5
  23. package/dist/compiler/emit/shared.js +5 -0
  24. package/dist/compiler/emit/statements.d.ts +28 -1
  25. package/dist/compiler/emit/statements.js +270 -13
  26. package/dist/compiler/emit/storage.d.ts +10 -1
  27. package/dist/compiler/emit/storage.js +50 -11
  28. package/dist/compiler/hints.d.ts +5 -0
  29. package/dist/compiler/hints.js +88 -0
  30. package/dist/compiler/idl.d.ts +1 -1
  31. package/dist/compiler/idl.js +42 -11
  32. package/dist/compiler/index.d.ts +3 -0
  33. package/dist/compiler/index.js +6 -1
  34. package/dist/compiler/model.d.ts +47 -10
  35. package/dist/compiler/model.js +14 -4
  36. package/dist/testing.js +8 -0
  37. package/dist/tools/clientgen.js +10 -1
  38. package/dist/tools/portgen.d.ts +6 -0
  39. package/dist/tools/portgen.js +68 -17
  40. package/docs/architecture.md +5 -4
  41. package/docs/audit.md +31 -19
  42. package/docs/case-study-escrow.md +5 -5
  43. package/docs/case-study-jito-mev.md +9 -5
  44. package/docs/case-study-marginfi.md +797 -0
  45. package/docs/case-study-multisig.md +3 -3
  46. package/docs/case-study-raydium-amm.md +80 -0
  47. package/docs/case-study-raydium-clmm.md +44 -33
  48. package/docs/case-study-raydium-cp-swap.md +3 -3
  49. package/docs/cli.md +5 -5
  50. package/docs/client.md +1 -1
  51. package/docs/errors.md +13 -5
  52. package/docs/language.md +65 -32
  53. package/docs/migrate-from-anchor.md +4 -1
  54. package/docs/runtime.md +1 -1
  55. package/docs/security-model.md +2 -1
  56. package/docs/testing.md +34 -1
  57. package/docs/troubleshooting.md +6 -0
  58. package/lib/typesol.d.ts +118 -10
  59. package/package.json +9 -7
  60. package/runtime/typesol_rt.h +158 -17
  61. package/ts-plugin/index.js +24 -1
@@ -4,12 +4,40 @@ import { borshIdentical } from "./borsh.js";
4
4
  import { ANCHOR_ERRORS } from "../anchor-errors.js";
5
5
  import { decodeAddress } from "../../keys.js";
6
6
  import { INT_INFO, INT_NAMES, isScalar, isWritable, sameType, scalarSize, typeName, } from "../model.js";
7
- import { U64, U8, I64, I32, BOOL, PUBKEY, STRING, HASH, cBytes, cString, scalarC, scalarStorageC, optC, valueC, fieldC, storageDecl, accountMismatch, vecCount, emptySizeC, vecLenCheck, } from "./shared.js";
7
+ import { U64, U32, U8, I64, I32, BOOL, PUBKEY, STRING, HASH, cBytes, cString, scalarC, scalarStorageC, optC, valueC, fieldC, storageDecl, accountMismatch, vecCount, emptySizeC, vecLenCheck, } from "./shared.js";
8
8
  import { ExpressionEmitter } from "./expressions.js";
9
9
  /**
10
10
  * Calls: built-in functions, Vec methods, helpers, remaining accounts, foreign account reads and return data.
11
11
  */
12
12
  /** List methods taking a callback (or a value) that expand into a loop. */
13
+ /** solana_program's ProgramError variants with no data, in order from InvalidArgument (2) on. */
14
+ const PROGRAM_ERRORS = [
15
+ "InvalidArgument",
16
+ "InvalidInstructionData",
17
+ "InvalidAccountData",
18
+ "AccountDataTooSmall",
19
+ "InsufficientFunds",
20
+ "IncorrectProgramId",
21
+ "MissingRequiredSignature",
22
+ "AccountAlreadyInitialized",
23
+ "UninitializedAccount",
24
+ "NotEnoughAccountKeys",
25
+ "AccountBorrowFailed",
26
+ "MaxSeedLengthExceeded",
27
+ "InvalidSeeds",
28
+ "BorshIoError",
29
+ "AccountNotRentExempt",
30
+ "UnsupportedSysvar",
31
+ "IllegalOwner",
32
+ "MaxAccountsDataAllocationsExceeded",
33
+ "InvalidRealloc",
34
+ "MaxInstructionTraceLengthExceeded",
35
+ "BuiltinProgramsMustConsumeComputeUnits",
36
+ "InvalidAccountOwner",
37
+ "ArithmeticOverflow",
38
+ "Immutable",
39
+ "IncorrectAuthority",
40
+ ];
13
41
  const LIST_METHODS = new Set(["forEach", "some", "every", "find", "findIndex", "reduce", "includes", "indexOf"]);
14
42
  export class CallEmitter extends ExpressionEmitter {
15
43
  call(node, topLevel) {
@@ -33,8 +61,52 @@ export class CallEmitter extends ExpressionEmitter {
33
61
  if (args.length !== 2)
34
62
  this.fail(node, "require(condition, error) takes two arguments");
35
63
  const cond = this.expect(this.expr(args[0], BOOL), BOOL, args[0]);
64
+ if (!this.namesError(args[1])) {
65
+ // A code computed at run time (a helper that returns its error as a value): u32, the program error it names.
66
+ const v = this.expr(args[1], U32);
67
+ if (v.type.kind === "string")
68
+ this.fail(args[1], "require's error is a string literal, a member of an error enum (CounterError.X) or a u32 code; a template string or string variable is not: give the message to an error enum member");
69
+ const code = v.literal !== undefined ? this.literal(v.literal, U32, args[1]) : this.expect(v, U32, args[1]);
70
+ this.line(`if (!${cond.c}) return ts_fail_code(${code.c}, ${cString(`Error: the code returned (${this.location(node)})`)});`);
71
+ return undefined;
72
+ }
73
+ // A built-in ProgramError: its u64 form (the index shifted into the high 32 bits), as solana_program returns it.
74
+ if (ts.isPropertyAccessExpression(args[1]) && this.exportName(args[1].expression) === "ProgramError") {
75
+ const idx = PROGRAM_ERRORS.indexOf(args[1].name.text);
76
+ if (idx < 0)
77
+ this.fail(args[1].name, `ProgramError has no ${args[1].name.text}`);
78
+ // `const PROGRAM_ERROR_LOG_PREFIX = "Program error: "`: the log line a native entrypoint writes for it.
79
+ const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
80
+ const text = typeof pre === "string" ? `${pre}${args[1].name.text}` : `Error: ${args[1].name.text} (${this.location(node)})`;
81
+ this.line(`if (!${cond.c}) TS_FAIL(((uint64_t)${idx + 2}) << 32, ${cString(text)});`);
82
+ return undefined;
83
+ }
36
84
  const err = this.errorRef(args[1]);
37
- this.line(`if (!${cond.c}) TS_FAIL(${err.code}, ${cString(`Error ${err.code} ${err.name}: ${err.msg} (${this.location(node)})`)});`);
85
+ // `const ERROR_LOG_PREFIX = "AMM error: "`: the program's errors log as its native entrypoint logs them.
86
+ const prefix = this.model.constants.get("ERROR_LOG_PREFIX")?.value;
87
+ const text = typeof prefix === "string" ? `${prefix}${err.msg}` : `Error ${err.code} ${err.name}: ${err.msg} (${this.location(node)})`;
88
+ this.line(`if (!${cond.c}) TS_FAIL(${err.code}, ${cString(text)});`);
89
+ return undefined;
90
+ }
91
+ case "panic": {
92
+ // String literals, or top-level string constants.
93
+ const text = (a) => {
94
+ if (ts.isStringLiteralLike(a))
95
+ return a.text;
96
+ const v = ts.isIdentifier(a) ? this.model.constants.get(a.text)?.value : undefined;
97
+ return typeof v === "string" ? v : undefined;
98
+ };
99
+ if (args.length > 2 || args.some((a) => text(a) === undefined))
100
+ this.fail(node, 'panic() takes an optional message and an optional "file:line:column" location: string literals or string constants');
101
+ const msg = args.length ? text(args[0]) : "explicit panic";
102
+ // The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"): the given one, as a
103
+ // ported program's panic reports it, else this source line.
104
+ const at = args.length > 1 ? text(args[1]) : this.location(node);
105
+ const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(at);
106
+ const [file, line, col] = m ? [m[1], m[2], m[3] ?? "0"] : [at, "0", "0"];
107
+ this.line(`sol_log(${cString(msg)});`);
108
+ this.line(`sol_panic_(${cString(file)}, ${Buffer.byteLength(file)}, ${line}, ${col});`);
109
+ this.line(`__builtin_unreachable();`);
38
110
  return undefined;
39
111
  }
40
112
  case "log": {
@@ -124,11 +196,12 @@ export class CallEmitter extends ExpressionEmitter {
124
196
  }
125
197
  case "currentSlot":
126
198
  case "currentEpoch":
199
+ case "epochStartTimestamp":
127
200
  case "now": {
128
201
  if (args.length !== 0)
129
202
  this.fail(node, `${builtin}() takes no arguments`);
130
203
  // Clock { slot, epoch_start_timestamp, epoch, leader_schedule_epoch, unix_timestamp }
131
- const field = builtin === "currentSlot" ? 0 : builtin === "currentEpoch" ? 2 : 4;
204
+ const field = builtin === "currentSlot" ? 0 : builtin === "currentEpoch" ? 2 : builtin === "epochStartTimestamp" ? 1 : 4;
132
205
  const t = this.tmp();
133
206
  if (this.ix) {
134
207
  // The Clock does not change within a transaction: an instruction reads it once, on first use.
@@ -137,6 +210,8 @@ export class CallEmitter extends ExpressionEmitter {
137
210
  this.line(`if (!ts_clk_ok) { TS_TRY(ts_read_clock(ts_clk)); ts_clk_ok = true; }`);
138
211
  if (builtin === "now")
139
212
  return { c: `((int64_t)ts_clk[4])`, type: I64 };
213
+ if (builtin === "epochStartTimestamp")
214
+ return { c: `((int64_t)ts_clk[1])`, type: I64 };
140
215
  this.line(`uint64_t ${t} = ts_clk[${field}];`);
141
216
  return { c: t, type: U64 };
142
217
  }
@@ -147,6 +222,8 @@ export class CallEmitter extends ExpressionEmitter {
147
222
  }
148
223
  this.line(`uint64_t ${t};`);
149
224
  this.line(`TS_TRY(ts_clock_u64(${field}, &${t}));`);
225
+ if (builtin === "epochStartTimestamp")
226
+ return { c: `((int64_t)${t})`, type: I64 };
150
227
  return { c: t, type: U64 };
151
228
  }
152
229
  case "pubkey": {
@@ -193,13 +270,24 @@ export class CallEmitter extends ExpressionEmitter {
193
270
  this.line(`TS_TRY(ts_mul_div${wide ? "_u128" : ""}(${x.c}, ${y.c}, ${z.c}, ${builtin === "mulDivCeil"}, &${t}));`);
194
271
  return { c: t, type: ty };
195
272
  }
273
+ case "f64FromBits":
274
+ case "f64Bits": {
275
+ // An f64 is its IEEE bits held as a u64: both are the same value, typed for the IDL and for TypeScript.
276
+ if (args.length !== 1)
277
+ this.fail(node, `${builtin}(x) takes one ${builtin === "f64Bits" ? "f64" : "u64"}`);
278
+ const v = this.expr(args[0]);
279
+ const x = v.literal !== undefined ? this.literal(v.literal, U64, args[0]) : this.expect(v, U64, args[0]);
280
+ return { c: x.c, type: builtin === "f64Bits" ? U64 : { kind: "int", name: "u64", f64: true } };
281
+ }
196
282
  case "isqrt": {
197
283
  if (args.length !== 1)
198
284
  this.fail(node, "isqrt(x) takes one unsigned integer");
199
285
  const v = this.expr(args[0]);
200
286
  const x = v.literal !== undefined ? this.literal(v.literal, U64, args[0]) : v;
201
287
  if (x.type.kind !== "int" || INT_INFO[x.type.name].signed)
202
- this.fail(args[0], "isqrt needs an unsigned integer (u8 … u128)");
288
+ this.fail(args[0], "isqrt needs an unsigned integer (u8 … u256)");
289
+ if (x.type.name === "u256")
290
+ return { c: `ts_isqrt_u256(${x.c})`, type: x.type };
203
291
  const wide = INT_INFO[x.type.name].bytes === 16;
204
292
  return { c: wide ? `ts_isqrt_u128(${x.c})` : `((${INT_INFO[x.type.name].c})ts_isqrt_u64((uint64_t)(${x.c})))`, type: x.type };
205
293
  }
@@ -492,6 +580,34 @@ export class CallEmitter extends ExpressionEmitter {
492
580
  this.line(`TS_TRY(ts_init_account(${h}, params->program_id, TS_DISC_${s.name}, sizeof(TSS_${s.name})));`);
493
581
  return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: true } };
494
582
  }
583
+ case "createProgramAddress": {
584
+ // Pubkey::create_program_address(seeds, program): the bump is the last seed; null when the seeds give a point
585
+ // on the curve (Rust's Err(PubkeyError::InvalidSeeds)) or are too many / too long.
586
+ if (args.length !== 2)
587
+ this.fail(node, "createProgramAddress(seeds, program) takes the seeds (bump last) and the program's address");
588
+ const seeds = this.seeds(args[0], 0);
589
+ const program = this.expect(this.expr(args[1], PUBKEY), PUBKEY, args[1]);
590
+ const t = this.tmp("cpa");
591
+ this.model.options.set("pubkey", PUBKEY);
592
+ this.line(`${optC(PUBKEY)} ${t};`);
593
+ this.line(`${t}.some = ts_create_pda_address(${seeds.name}, ${seeds.count}, ${program.c}, &${t}.v) == SUCCESS;`);
594
+ return { c: t, type: { kind: "option", inner: PUBKEY } };
595
+ }
596
+ case "logBase64": {
597
+ // msg!("{prefix}{base64 of the struct's bytes}"): a fixed-layout struct's bytes are its bincode / Borsh form
598
+ // when it holds integers and Pubkeys only (Raydium's ray_log).
599
+ if (args.length !== 2 || !ts.isStringLiteralLike(args[0]))
600
+ this.fail(node, 'logBase64("prefix", value) takes a string literal and a struct value');
601
+ const place = this.structPlace(args[1]);
602
+ if (!place)
603
+ this.fail(args[1], "logBase64 logs a struct value (a local, a literal bound to a const, or account data)");
604
+ const sd = this.model.structs.get(place.struct);
605
+ if (sd.size === undefined || sd.vec || sd.fields.some((f) => !["int", "pubkey", "array"].includes(f.type.kind)))
606
+ this.fail(args[1], `${sd.name} must hold only integers, Pubkeys and fixed arrays of them for its bytes to be its serialized form`);
607
+ const prefix = args[0].text;
608
+ this.line(`ts_log_base64(${cString(prefix)}, ${Buffer.byteLength(prefix)}, (const uint8_t *)${place.ptr}, sizeof(TSS_${sd.name}));`);
609
+ return undefined;
610
+ }
495
611
  case "findProgramAddress": {
496
612
  // Pubkey::find_program_address(seeds, program).0: the canonical PDA of any program.
497
613
  if (args.length !== 2)
@@ -535,14 +651,30 @@ export class CallEmitter extends ExpressionEmitter {
535
651
  }
536
652
  case "remainingAccounts":
537
653
  if (!this.ix)
538
- this.fail(node, "remainingAccounts() is only available in instructions");
539
- return { c: "", type: { kind: "remaining" } };
654
+ this.fail(node, "remainingAccounts() is only available in instructions; pass it to a helper that takes RemainingAccounts");
655
+ return { c: String(this.ix.accounts.length), type: { kind: "remaining" } };
540
656
  case "readData":
541
657
  return this.readData(node);
658
+ case "writeData":
659
+ return this.writeData(node);
660
+ case "resizeAccount": {
661
+ if (args.length !== 2)
662
+ this.fail(node, "resizeAccount(account, newSize) takes the account and its new size");
663
+ if (!this.ix)
664
+ this.fail(node, "resizeAccount() is only available in instructions");
665
+ const acct = this.accountParam(args[0], "resizeAccount's account");
666
+ if (acct.kind.kind !== "info" || !isWritable(acct.kind))
667
+ this.fail(args[0], "resizeAccount needs a Mut<AccountInfo> parameter");
668
+ const size = this.expect(this.expr(args[1], U64), U64, args[1]);
669
+ this.line(`TS_TRY(ts_resize_raw(a_${acct.name}, ${size.c}, entry_${acct.name}));`);
670
+ return undefined;
671
+ }
542
672
  case "bigEndian":
543
673
  this.fail(node, "bigEndian(value) is a PDA seed: use it inside a seeds list");
544
674
  case "loadAccount":
545
675
  case "loadAccountMut":
676
+ case "loadRaw":
677
+ case "loadRawMut":
546
678
  case "loadForeign":
547
679
  this.fail(node, `bind ${builtin}<T>(...) to a const first: const p = ${builtin}<T>(account)`);
548
680
  case "emit":
@@ -590,6 +722,8 @@ export class CallEmitter extends ExpressionEmitter {
590
722
  this.fail(node, `${callee.text} returns a function: bind it (const f = ${callee.text}(…)) or call it right away (${callee.text}(…)(…))`);
591
723
  if (local?.closure)
592
724
  return this.expandClosure(local.closure, node.arguments, node);
725
+ if (local?.choice)
726
+ return this.callChoice(local.choice, node.arguments, node);
593
727
  const name = calleeName(callee, this.model.helperDecls, this.checker) ?? callee.text;
594
728
  if (!local && this.model.factories.has(name))
595
729
  this.fail(node, `${callee.text} returns a function: bind it (const f = ${callee.text}(…)) or call it right away (${callee.text}(…)(…))`);
@@ -618,8 +752,29 @@ export class CallEmitter extends ExpressionEmitter {
618
752
  if (ts.isIdentifier(callee.expression)) {
619
753
  const l = this.lookup(callee.expression.text);
620
754
  if (l?.type.kind === "vecArg") {
755
+ // Bytes (instruction data, a Vec<u8> argument): little-endian reads at a byte offset, bounds-checked (5104).
756
+ const le = {
757
+ readU8: ["uint8_t", 1, U8],
758
+ readU16: ["uint16_t", 2, { kind: "int", name: "u16" }],
759
+ readU32: ["uint32_t", 4, { kind: "int", name: "u32" }],
760
+ readU64: ["uint64_t", 8, U64],
761
+ readU128: ["__uint128_t", 16, { kind: "int", name: "u128" }],
762
+ readPubkey: ["SolPubkey", 32, PUBKEY],
763
+ };
764
+ if (le[method] && l.type.elem.kind === "int" && l.type.elem.name === "u8") {
765
+ if (args.length !== 1)
766
+ this.fail(node, `${method}(offset) takes the byte offset`);
767
+ const [c, size, type] = le[method];
768
+ const off = this.tmp("off");
769
+ this.line(`uint64_t ${off} = ${this.expect(this.expr(args[0], U64), U64, args[0]).c};`);
770
+ this.line(`if (${off} > (uint64_t)${l.c}.len || (uint64_t)${l.c}.len - ${off} < ${size}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: read past the end of the bytes");`);
771
+ const t = this.tmp("rd");
772
+ this.line(`${c} ${t};`);
773
+ this.line(`ts_memcpy(&${t}, ${l.c}.ptr + ${off}, ${size});`);
774
+ return type.kind === "pubkey" ? { c: `(&${t})`, type } : { c: t, type };
775
+ }
621
776
  if (method !== "get" || args.length !== 1)
622
- this.fail(node, "Vec arguments are read-only: use .get(i) and .length");
777
+ this.fail(node, "Vec arguments are read-only: use .get(i), .length, and on bytes readU8/U16/U32/U64/U128/readPubkey(offset)");
623
778
  const elem = l.type.elem;
624
779
  if (elem.kind === "string") {
625
780
  const idx = this.index(args[0], `(uint64_t)${l.c}.len`);
@@ -710,6 +865,8 @@ export class CallEmitter extends ExpressionEmitter {
710
865
  return this.systemTransfer(node);
711
866
  if (target?.kind.kind === "system" && method === "createAccount")
712
867
  return this.createAccount(node, target);
868
+ if (target?.kind.kind === "system" && method === "createPda")
869
+ return this.createPda(node);
713
870
  if (target?.kind.kind === "system" && (method === "allocate" || method === "assign"))
714
871
  return this.allocateOrAssign(node, target, method);
715
872
  if (target?.kind.kind === "tokenProgram")
@@ -1069,6 +1226,17 @@ export class CallEmitter extends ExpressionEmitter {
1069
1226
  this.line(`ts_memcpy(${name} + ${f.offset}, ${f.c}, 32);`);
1070
1227
  return { name, count };
1071
1228
  }
1229
+ /** The index of the first remaining account among the instruction's accounts, as C: a constant, or a helper's parameter. */
1230
+ remainingBase(node) {
1231
+ if (ts.isIdentifier(node)) {
1232
+ const l = this.lookup(node.text);
1233
+ if (l?.type.kind === "remaining" && l.c)
1234
+ return l.c;
1235
+ }
1236
+ if (!this.ix)
1237
+ this.fail(node, "remainingAccounts() is only available in instructions; pass it to a helper that takes RemainingAccounts");
1238
+ return String(this.ix.accounts.length);
1239
+ }
1072
1240
  /** `remainingAccounts()` or a const bound to it. */
1073
1241
  isRemaining(node) {
1074
1242
  if (ts.isIdentifier(node))
@@ -1173,11 +1341,9 @@ export class CallEmitter extends ExpressionEmitter {
1173
1341
  ts.isPropertyAccessExpression(node.expression) &&
1174
1342
  node.expression.name.text === "get" &&
1175
1343
  this.isRemaining(node.expression.expression)) {
1176
- if (!this.ix)
1177
- this.fail(node, "remainingAccounts() is only available in instructions");
1178
1344
  if (node.arguments.length !== 1)
1179
1345
  this.fail(node, "get(index) takes one argument");
1180
- const n = this.ix.accounts.length;
1346
+ const n = this.remainingBase(node.expression.expression);
1181
1347
  const idx = this.index(node.arguments[0], `(uint64_t)(params->ka_num - ${n})`);
1182
1348
  const t = this.tmp("acct");
1183
1349
  this.line(`TsAccount *${t} = params->ka[${n} + ${idx}];`);
@@ -1219,12 +1385,41 @@ export class CallEmitter extends ExpressionEmitter {
1219
1385
  this.line(`if (${out} >= ${this.model.enums.get(t.name).variants.length}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: invalid enum value");`);
1220
1386
  return { c: out, type: t };
1221
1387
  }
1388
+ /** `writeData<T>(account, offset, value)`: a little-endian store into a writable AccountInfo's data. */
1389
+ writeData(node) {
1390
+ const targ = node.typeArguments?.[0];
1391
+ const t = targ && resolveScalarType(targ, this.scope);
1392
+ if (!t)
1393
+ this.fail(node, "writeData needs a value type: writeData<u64>(account, offset, value)");
1394
+ if (node.arguments.length !== 3)
1395
+ this.fail(node, "writeData<T>(account, offset, value) takes an account, a byte offset and a value");
1396
+ const acct = this.accountParam(node.arguments[0], "writeData's account");
1397
+ if (acct.kind.kind !== "info" || !isWritable(acct.kind))
1398
+ this.fail(node.arguments[0], "writeData needs a Mut<AccountInfo> parameter");
1399
+ const off = this.expect(this.expr(node.arguments[1], U64), U64, node.arguments[1]);
1400
+ const o = this.tmp("off");
1401
+ this.line(`uint64_t ${o} = ${off.c};`);
1402
+ const v = this.expect(this.expr(node.arguments[2], t), t, node.arguments[2]);
1403
+ const size = scalarSize(t);
1404
+ const a = `a_${acct.name}`;
1405
+ this.line(`if (${o} > ${a}->data_len || ${a}->data_len - ${o} < ${size}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: write past the end of the account data");`);
1406
+ if (t.kind === "pubkey")
1407
+ this.line(`ts_memcpy(${a}->data + ${o}, ${v.c}, 32);`);
1408
+ else {
1409
+ const w = this.tmp("wr");
1410
+ this.line(`${scalarStorageC(t)} ${w} = (${scalarStorageC(t)})(${v.c});`);
1411
+ this.line(`ts_memcpy(${a}->data + ${o}, &${w}, ${size});`);
1412
+ }
1413
+ return undefined;
1414
+ }
1222
1415
  /** `loadForeign<T>(account, owner)`: read-only view of another program's Anchor account. */
1223
1416
  loadForeign(node) {
1224
1417
  const targ = node.typeArguments?.[0];
1225
1418
  const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
1226
1419
  if (!s || s.size === undefined || s.vec)
1227
1420
  this.fail(node, "loadForeign needs a fixed-size struct type: loadForeign<Pool>(account, owner)");
1421
+ if (s.accountDiscriminator.length !== 8)
1422
+ this.fail(node, `${s.name}'s discriminator is shorter than 8 bytes: take it as Owner<Account<${s.name}>, "…">`);
1228
1423
  if (s.layout === "borsh")
1229
1424
  this.fail(node, `${s.name} is @layout borsh: loadForeign reads fixed layouts only`);
1230
1425
  if (node.arguments.length !== 2)
@@ -1242,12 +1437,63 @@ export class CallEmitter extends ExpressionEmitter {
1242
1437
  this.line(l.trim());
1243
1438
  return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: false } };
1244
1439
  }
1440
+ /**
1441
+ * `loadRaw<T>(acct)` / `loadRawMut<T>(acct)`: a native program's account (no discriminator) as a fixed-layout struct
1442
+ * from byte 0, checked as a `#[repr(C)]` type's load_checked does: this program's (3007), large enough (3003).
1443
+ */
1444
+ loadRaw(node, mut) {
1445
+ const fn = mut ? "loadRawMut" : "loadRaw";
1446
+ const targ = node.typeArguments?.[0];
1447
+ const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
1448
+ if (!s || s.size === undefined || s.vec)
1449
+ this.fail(node, `${fn} needs a fixed-size struct type: ${fn}<MyStruct>(account)`);
1450
+ if (s.layout === "borsh")
1451
+ this.fail(node, `${s.name} is @layout borsh: ${fn} reads fixed layouts only`);
1452
+ if (node.arguments.length !== 1)
1453
+ this.fail(node, `${fn}<T>(account) takes one remaining account or AccountInfo parameter`);
1454
+ let h = this.handle(node.arguments[0]);
1455
+ let param;
1456
+ if (!h) {
1457
+ const acct = this.accountParam(node.arguments[0], "the account");
1458
+ if (acct.kind.kind !== "info")
1459
+ this.fail(node.arguments[0], "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter");
1460
+ if (mut && !isWritable(acct.kind))
1461
+ this.fail(node.arguments[0], `${acct.name} must be Mut<AccountInfo> to load it with loadRawMut`);
1462
+ if (!this.ix)
1463
+ this.fail(node, `load ${acct.name} in the instruction and pass the struct on`);
1464
+ h = `a_${acct.name}`;
1465
+ param = this.ix.accounts.indexOf(acct);
1466
+ }
1467
+ this.line(`if (!ts_key_eq(&${h}->owner, params->program_id)) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program");`);
1468
+ this.line(`if (${h}->data_len < sizeof(TSS_${s.name})) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account data too small");`);
1469
+ if (mut) {
1470
+ this.line(`TS_TRY(ts_check_writable(${h}));`);
1471
+ const slot = this.claimSlots.get(node);
1472
+ if (slot)
1473
+ this.line(param === undefined
1474
+ ? `TS_TRY(ts_claim_mut_rec(params, ${h}, &${slot}, params->ka_num));`
1475
+ : `TS_TRY(ts_claim_mut_at_rec(params, ${param}, &${slot}));`);
1476
+ else
1477
+ this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
1478
+ }
1479
+ return { c: `((TSS_${s.name} *)(${h}->data))`, type: { kind: "structRef", struct: s.name, writable: mut } };
1480
+ }
1245
1481
  /** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
1246
1482
  loadAccount(node, mut) {
1247
- const targ = node.typeArguments?.[0];
1483
+ let targ = node.typeArguments?.[0];
1484
+ // loadAccountMut<Dup<T>>: the account may be passed more than once among the remaining accounts (a route back
1485
+ // through one pool), loaded once per loop iteration; two live views of it are still refused.
1486
+ const dup = !!targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) && targ.typeName.text === "Dup" && targ.typeArguments?.length === 1;
1487
+ if (dup) {
1488
+ if (!mut)
1489
+ this.fail(node, "Dup<…> is for loadAccountMut (loadAccount reads, any number of times)");
1490
+ targ = targ.typeArguments[0];
1491
+ }
1248
1492
  const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
1249
1493
  if (!s || s.size === undefined)
1250
1494
  this.fail(node, "loadAccount needs an account struct type: loadAccount<MyStruct>(account)");
1495
+ if (s.accountDiscriminator.length !== 8)
1496
+ this.fail(node, `${s.name}'s discriminator is shorter than 8 bytes: take it as Owner<Account<${s.name}>, "…">`);
1251
1497
  if (s.layout === "borsh")
1252
1498
  this.fail(node, `${s.name} is @layout borsh: declare it as an instruction parameter (remaining accounts are read in place)`);
1253
1499
  if (node.arguments.length !== 1)
@@ -1270,13 +1516,21 @@ export class CallEmitter extends ExpressionEmitter {
1270
1516
  if (this.model.events.has(s.name) && s.fields.some((f) => f.type.kind === "option" || f.type.kind === "dataEnum"))
1271
1517
  this.fail(node, `${s.name} is emitted as an event and has Option or enum fields; declare a separate event struct`);
1272
1518
  this.model.accountStructs.add(s.name);
1273
- this.line(`TS_TRY(ts_check_program_account(${h}, params->program_id, TS_DISC_${s.name}, ${emptySizeC(s)}));`);
1519
+ this.line(`TS_TRY(${s.idlMeta?.serialization?.startsWith("bytemuck") ? "ts_check_loader_account" : "ts_check_program_account"}(${h}, params->program_id, TS_DISC_${s.name}, ${emptySizeC(s)}));`);
1274
1520
  if (s.vec)
1275
1521
  for (const l of vecLenCheck(s, h, `((TSS_${s.name} *)(${h}->data + 8))`, ""))
1276
1522
  this.line(l);
1277
1523
  if (mut) {
1278
1524
  this.line(`TS_TRY(ts_check_writable(${h}));`);
1279
- this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
1525
+ const slot = this.claimSlots.get(node);
1526
+ // Repeats may come only after the instruction's own accounts, and only for Dup<…>: otherwise any repeat is refused.
1527
+ const declared = dup && this.ix ? String(this.ix.accounts.length) : "params->ka_num";
1528
+ if (dup && (param !== undefined || !slot))
1529
+ this.fail(node, "loadAccountMut<Dup<T>> is for remaining accounts loaded in a loop (one view per iteration)");
1530
+ if (slot)
1531
+ this.line(param === undefined ? `TS_TRY(ts_claim_mut_rec(params, ${h}, &${slot}, ${declared}));` : `TS_TRY(ts_claim_mut_at_rec(params, ${param}, &${slot}));`);
1532
+ else
1533
+ this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
1280
1534
  }
1281
1535
  return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: mut } };
1282
1536
  }
@@ -1456,7 +1710,8 @@ export class CallEmitter extends ExpressionEmitter {
1456
1710
  this.fail(node, `${h.display}() takes ${h.params.length} argument(s)`);
1457
1711
  // Arguments are evaluated left to right: settle earlier ones when a later one runs statements.
1458
1712
  // A helper that takes accounts may change account data, so account text it gets is copied first.
1459
- const takesAccounts = h.params.some((p) => p.account);
1713
+ // A RemainingAccount(s) parameter counts: the helper may load and write a struct through it.
1714
+ const takesAccounts = h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining");
1460
1715
  const values = [];
1461
1716
  const pieces = [];
1462
1717
  h.params.forEach((p, i) => {
@@ -1530,20 +1785,25 @@ export class CallEmitter extends ExpressionEmitter {
1530
1785
  case "structRef":
1531
1786
  case "arrayArg": {
1532
1787
  const want = p.type.kind === "structRef" ? { kind: "struct", name: p.type.struct } : p.type.array;
1533
- const r = this.ref(n);
1788
+ let r = this.ref(n);
1789
+ // A narrowed Option<Struct> / Option<FixedArray> place (`c.opt !== null` before it): its value.
1790
+ if (r && r.type.kind === "option" && sameType(r.type.inner, want))
1791
+ r = this.someValue(r);
1534
1792
  if (!r || !sameType(r.type, want))
1535
1793
  this.fail(n, `expected a ${typeName(want)}`);
1536
- return this.snapshotPlace(r.lv, want, h);
1794
+ return this.snapshotPlace(r.lv, want, h, n);
1537
1795
  }
1538
1796
  case "dataEnumArg": {
1539
1797
  const r = this.ref(n);
1540
1798
  if (!r || r.type.kind !== "dataEnum" || r.type.name !== p.type.name)
1541
1799
  this.fail(n, `expected a ${p.type.name}`);
1542
- return this.snapshotPlace(r.lv, { kind: "dataEnum", name: p.type.name }, h);
1800
+ return this.snapshotPlace(r.lv, { kind: "dataEnum", name: p.type.name }, h, n);
1543
1801
  }
1544
1802
  case "vecArg": {
1545
1803
  const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
1546
- if (!l || !sameType(l.type, p.type))
1804
+ // An Option<Vec<T>> argument passes as its list once checked against null (TypeScript narrows it).
1805
+ const t = l?.type.kind === "vecArg" && l.type.optional ? { ...l.type, optional: undefined } : l?.type;
1806
+ if (!l || !t || !sameType(t, p.type))
1547
1807
  this.fail(n, `expected a ${typeName(p.type)} instruction argument`);
1548
1808
  return l.c;
1549
1809
  }
@@ -1555,8 +1815,12 @@ export class CallEmitter extends ExpressionEmitter {
1555
1815
  * A struct/array/data-enum helper argument. Helpers that take accounts may change account data, so they get a
1556
1816
  * copy taken at the call (JS passes the object as it was); other helpers cannot write, so a pointer is enough.
1557
1817
  */
1558
- snapshotPlace(lv, type, h) {
1559
- if (!h.params.some((p) => p.account))
1818
+ snapshotPlace(lv, type, h, node) {
1819
+ if (!h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining"))
1820
+ return `(&${lv})`;
1821
+ // A struct this function owns (a literal, or a helper's result it holds), or part of one, is not account data: what
1822
+ // the helper writes cannot change it, so the helper reads it in place.
1823
+ if (node && this.ownedRoot(node))
1560
1824
  return `(&${lv})`;
1561
1825
  const n = this.fieldBytes(type);
1562
1826
  // One buffer per call site, allocated on first use: a call in a loop must not take new heap every pass.
@@ -1567,6 +1831,21 @@ export class CallEmitter extends ExpressionEmitter {
1567
1831
  this.line(`ts_memcpy(${t}, &${lv}, ${n});`);
1568
1832
  return t;
1569
1833
  }
1834
+ /** Whether `node` is (part of) a struct value this function owns: `h`, `h.inner`, `h.list.get(i)`. */
1835
+ ownedRoot(node) {
1836
+ let n = node;
1837
+ for (;;) {
1838
+ if (ts.isParenthesizedExpression(n))
1839
+ n = n.expression;
1840
+ else if (ts.isPropertyAccessExpression(n))
1841
+ n = n.expression;
1842
+ else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === "get")
1843
+ n = n.expression.expression;
1844
+ else
1845
+ break;
1846
+ }
1847
+ return ts.isIdentifier(n) && !!this.lookup(n.text)?.owned;
1848
+ }
1570
1849
  /** `signer([...seeds])` (one PDA signature), or a SignerSeeds parameter passed on. */
1571
1850
  signerSeedsArg(n) {
1572
1851
  if (ts.isIdentifier(n)) {
@@ -1581,6 +1860,16 @@ export class CallEmitter extends ExpressionEmitter {
1581
1860
  }
1582
1861
  this.fail(n, "pass signer([...seeds with the bump]) or a SignerSeeds parameter");
1583
1862
  }
1863
+ /** Whether `require`'s error is named in the source (an error enum member, AnchorError.X or a message). */
1864
+ namesError(node) {
1865
+ if (ts.isStringLiteral(node))
1866
+ return true;
1867
+ if (!ts.isPropertyAccessExpression(node))
1868
+ return false;
1869
+ if (this.exportName(node.expression) === "AnchorError" || this.exportName(node.expression) === "ProgramError")
1870
+ return true;
1871
+ return ts.isIdentifier(node.expression) && this.model.errorEnums.has(node.expression.text);
1872
+ }
1584
1873
  errorRef(node) {
1585
1874
  // `AnchorError.X`: one of Anchor's own codes (not one of this program's errors, so not in the IDL).
1586
1875
  if (ts.isPropertyAccessExpression(node) && this.exportName(node.expression) === "AnchorError") {
@@ -1598,7 +1887,8 @@ export class CallEmitter extends ExpressionEmitter {
1598
1887
  const existing = this.model.errors.find((e) => e.msg === node.text && e.name.startsWith("RequireFailed"));
1599
1888
  if (existing)
1600
1889
  return existing;
1601
- const def = { code: 6000 + this.model.errors.length, name: `RequireFailed${this.model.errors.length}`, msg: node.text };
1890
+ const code = Math.max(5999, ...this.model.errors.map((e) => e.code)) + 1;
1891
+ const def = { code, name: `RequireFailed${code - 6000}`, msg: node.text };
1602
1892
  this.model.errors.push(def);
1603
1893
  return def;
1604
1894
  }
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { argIdlName, snakeCase } from "../analyze.js";
2
+ import { argIdlName, fieldIdlName, snakeCase } from "../analyze.js";
3
3
  import { INT_INFO, isScalar, scalarSize, typeName } from "../model.js";
4
4
  import { accountLimit, MAX_SEEDS, U64, isStable, cString, scalarStorageC, optC } from "./shared.js";
5
5
  import { CallEmitter } from "./calls.js";
@@ -113,6 +113,15 @@ export class CpiCoreEmitter extends CallEmitter {
113
113
  b.writeBigUInt64LE(value);
114
114
  return { kind: "const", value: [...b] };
115
115
  }
116
+ // `opt ?? 0n` on an Option argument: Anchor's IDL keeps the Rust expression's text, `opt.unwrap_or(0)`.
117
+ if (ts.isBinaryExpression(el) &&
118
+ el.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken &&
119
+ ts.isBigIntLiteral(el.right) &&
120
+ ts.isIdentifier(el.left)) {
121
+ const arg = this.describeSeed(el.left);
122
+ if (arg?.kind === "arg")
123
+ return { kind: "arg", path: `${arg.path}.unwrap_or(${BigInt(el.right.text.slice(0, -1).replace(/_/g, ""))})` };
124
+ }
116
125
  // Only the argument itself, not a local that shadows its name.
117
126
  if (ts.isIdentifier(el) && this.ix?.args.some((a) => a.name === el.text) && this.lookup(el.text) === this.args.get(el.text))
118
127
  return {
@@ -139,7 +148,7 @@ export class CpiCoreEmitter extends CallEmitter {
139
148
  if (a && (a.kind.kind === "account" || a.kind.kind === "init" || a.kind.kind === "zeroed" || a.kind.kind === "initIfNeeded")) {
140
149
  const f = a.kind.struct.fields.find((x) => x.name === el.name.text);
141
150
  if (f && isScalar(f.type))
142
- return { kind: "account", path: `${snakeCase(a.name)}.${snakeCase(f.name)}`, account: a.kind.struct.name };
151
+ return { kind: "account", path: `${snakeCase(a.name)}.${f.idlName ?? fieldIdlName(f.name)}`, account: a.kind.struct.name };
143
152
  }
144
153
  }
145
154
  return undefined;
@@ -230,13 +239,16 @@ export class CpiCoreEmitter extends CallEmitter {
230
239
  * (both checked against the count, 5104). C expressions for the range, relative to the first remaining account.
231
240
  */
232
241
  remainingRange(node) {
242
+ const sliced = ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "slice";
243
+ if (!this.isRemaining(node) && !(sliced && this.isRemaining(node.expression.expression)))
244
+ return undefined;
245
+ if (!this.ix)
246
+ this.fail(node, "pass the remaining accounts to a CPI from the instruction; a helper reads them one at a time with .get(i)");
233
247
  const n = this.ix.accounts.length;
234
248
  const count = `(params->ka_num - ${n})`;
235
249
  if (this.isRemaining(node))
236
250
  return { from: "0", to: count };
237
- if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression) || node.expression.name.text !== "slice")
238
- return undefined;
239
- if (!this.isRemaining(node.expression.expression))
251
+ if (!ts.isCallExpression(node))
240
252
  return undefined;
241
253
  if (node.arguments.length < 1 || node.arguments.length > 2)
242
254
  this.fail(node, "slice(start, end?) takes one or two indexes");