@typesol/cli 0.41.0 → 0.42.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 (47) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +2 -1
  3. package/dist/compiler/analyze.js +41 -1
  4. package/dist/compiler/emit/base.d.ts +40 -7
  5. package/dist/compiler/emit/base.js +33 -0
  6. package/dist/compiler/emit/borsh.d.ts +7 -0
  7. package/dist/compiler/emit/borsh.js +86 -1
  8. package/dist/compiler/emit/calls.d.ts +102 -2
  9. package/dist/compiler/emit/calls.js +663 -49
  10. package/dist/compiler/emit/cpi-core.d.ts +9 -3
  11. package/dist/compiler/emit/cpi-core.js +12 -7
  12. package/dist/compiler/emit/cpi.js +8 -14
  13. package/dist/compiler/emit/create.d.ts +3 -3
  14. package/dist/compiler/emit/create.js +33 -25
  15. package/dist/compiler/emit/expressions.js +51 -2
  16. package/dist/compiler/emit/function.js +2 -2
  17. package/dist/compiler/emit/outline.d.ts +24 -0
  18. package/dist/compiler/emit/outline.js +100 -0
  19. package/dist/compiler/emit/program.js +7 -2
  20. package/dist/compiler/emit/shared.d.ts +35 -1
  21. package/dist/compiler/emit/shared.js +9 -1
  22. package/dist/compiler/emit/statements.d.ts +31 -0
  23. package/dist/compiler/emit/statements.js +272 -14
  24. package/dist/compiler/emit/storage.d.ts +27 -1
  25. package/dist/compiler/emit/storage.js +124 -11
  26. package/dist/compiler/emit/token.d.ts +11 -8
  27. package/dist/compiler/emit/token.js +233 -104
  28. package/dist/compiler/hints.js +6 -0
  29. package/dist/compiler/model.d.ts +20 -1
  30. package/dist/compiler/model.js +5 -0
  31. package/dist/testing-stake.d.ts +216 -0
  32. package/dist/testing-stake.js +526 -0
  33. package/dist/testing.d.ts +1 -0
  34. package/dist/testing.js +1 -0
  35. package/docs/architecture.md +1 -1
  36. package/docs/case-study-spl-stake-pool.md +122 -0
  37. package/docs/errors.md +1 -1
  38. package/docs/language.md +107 -14
  39. package/docs/security-model.md +4 -0
  40. package/docs/stability.md +13 -0
  41. package/docs/test-your-program.md +47 -0
  42. package/docs/testing.md +19 -0
  43. package/lib/typesol.d.ts +241 -40
  44. package/llms-full.txt +172 -15
  45. package/llms.txt +1 -1
  46. package/package.json +1 -1
  47. package/runtime/typesol_rt.h +69 -0
@@ -1,6 +1,6 @@
1
1
  import ts from "typescript";
2
- import { calleeName, discriminator, resolveScalarType, resolveValueType, snakeCase, structNameOf } from "../analyze.js";
3
- import { borshIdentical } from "./borsh.js";
2
+ import { calleeName, discriminator, resolveScalarType, resolveValueType, snakeCase, structNameOf, typesolName } from "../analyze.js";
3
+ import { borshIdentical, borshNativeStructUnsupported } from "./borsh.js";
4
4
  import { ANCHOR_ERRORS } from "../anchor-errors.js";
5
5
  import { decodeAddress } from "../../keys.js";
6
6
  import { INT_INFO, INT_NAMES, isScalar, isWritable, sameType, scalarSize, typeName, } from "../model.js";
@@ -72,13 +72,9 @@ export class CallEmitter extends ExpressionEmitter {
72
72
  }
73
73
  // A built-in ProgramError: its u64 form (the index shifted into the high 32 bits), as solana_program returns it.
74
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)
75
+ if (!PROGRAM_ERRORS.includes(args[1].name.text))
77
76
  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)});`);
77
+ this.line(`if (!${cond.c}) ${this.programErrorFail(args[1].name.text, node)};`);
82
78
  return undefined;
83
79
  }
84
80
  const err = this.errorRef(args[1]);
@@ -96,19 +92,29 @@ export class CallEmitter extends ExpressionEmitter {
96
92
  const v = ts.isIdentifier(a) ? this.model.constants.get(a.text)?.value : undefined;
97
93
  return typeof v === "string" ? v : undefined;
98
94
  };
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";
95
+ // A null message: nothing logged, only the runtime's line (a native program whose panic handler logs nothing).
96
+ const silent = args.length > 0 && args[0].kind === ts.SyntaxKind.NullKeyword;
97
+ if (args.length > 2 || args.some((a, i) => !(i === 0 && silent) && text(a) === undefined))
98
+ 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');
99
+ const msg = silent ? undefined : args.length ? text(args[0]) : "explicit panic";
102
100
  // The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"): the given one, as a
103
101
  // ported program's panic reports it, else this source line.
104
102
  const at = args.length > 1 ? text(args[1]) : this.location(node);
105
103
  const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(at);
106
104
  const [file, line, col] = m ? [m[1], m[2], m[3] ?? "0"] : [at, "0", "0"];
107
- this.line(`sol_log(${cString(msg)});`);
105
+ if (msg !== undefined)
106
+ this.line(`sol_log(${cString(msg)});`);
108
107
  this.line(`sol_panic_(${cString(file)}, ${Buffer.byteLength(file)}, ${line}, ${col});`);
109
108
  this.line(`__builtin_unreachable();`);
110
109
  return undefined;
111
110
  }
111
+ case "abort": {
112
+ // Rust's abort on SBF: the runtime's `abort` syscall ("SBF program panicked", no location, nothing logged).
113
+ if (args.length)
114
+ this.fail(node, "abort() takes no arguments; log the original's message first with log(…) where it writes one");
115
+ this.line(`abort();`);
116
+ return undefined;
117
+ }
112
118
  case "log": {
113
119
  if (args.length !== 1)
114
120
  this.fail(node, "log() takes one argument");
@@ -201,6 +207,15 @@ export class CallEmitter extends ExpressionEmitter {
201
207
  this.line(`TS_TRY(ts_epoch_schedule(${{ slotsPerEpoch: 0, epochWarmup: 2, firstNormalEpoch: 3, firstNormalSlot: 4 }[builtin]}, &${t}));`);
202
208
  return builtin === "epochWarmup" ? { c: `(${t} != 0)`, type: BOOL } : { c: t, type: U64 };
203
209
  }
210
+ case "epochRewards": {
211
+ if (args.length !== 0)
212
+ this.fail(node, "epochRewards() takes no arguments");
213
+ // Rust's EpochRewards::get() (sol_get_epoch_rewards_sysvar): a copy of the sysvar, read where it is called.
214
+ const t = this.tmp("erw");
215
+ this.line(`TsEpochRewards ${t};`);
216
+ this.line(`TS_TRY(ts_epoch_rewards(&${t}));`);
217
+ return { c: t, type: { kind: "epochRewards" } };
218
+ }
204
219
  case "currentSlot":
205
220
  case "currentEpoch":
206
221
  case "epochStartTimestamp":
@@ -683,7 +698,10 @@ export class CallEmitter extends ExpressionEmitter {
683
698
  case "loadRaw":
684
699
  case "loadRawMut":
685
700
  case "loadForeign":
701
+ case "loadBorsh":
686
702
  this.fail(node, `bind ${builtin}<T>(...) to a const first: const p = ${builtin}<T>(account)`);
703
+ case "storeBorsh":
704
+ return this.storeBorsh(node);
687
705
  case "emit":
688
706
  return this.emitEvent(node);
689
707
  case "emitCpi": {
@@ -702,6 +720,9 @@ export class CallEmitter extends ExpressionEmitter {
702
720
  }
703
721
  case "returnData":
704
722
  return this.returnData(node);
723
+ case "programAt":
724
+ case "sysvarAt":
725
+ return this.programAt(node, builtin);
705
726
  case "instructionData":
706
727
  this.fail(node, "bind the data to a local first: const data = instructionData()");
707
728
  case "fixedArray":
@@ -714,6 +735,8 @@ export class CallEmitter extends ExpressionEmitter {
714
735
  case "sighash":
715
736
  case "hex":
716
737
  this.fail(node, `${builtin}() is only valid inside the data list of invoke()`);
738
+ case "named":
739
+ this.fail(node, "named(account, address) is only valid as a Stake CPI's sysvar or stake config argument");
717
740
  }
718
741
  if (builtin)
719
742
  this.fail(callee, `${builtin} cannot be called here`);
@@ -749,16 +772,23 @@ export class CallEmitter extends ExpressionEmitter {
749
772
  // xs.some(…) and friends on a Vec, FixedArray, FixedVec or Vec argument: a loop with the callback expanded in it.
750
773
  if (LIST_METHODS.has(method)) {
751
774
  const l = ts.isIdentifier(callee.expression) ? this.lookup(callee.expression.text) : undefined;
752
- if (l?.type.kind === "vecArg" || l?.type.kind === "array" || this.isPipeline(callee.expression) || this.peekArray(callee.expression))
775
+ if (l?.type.kind === "vecArg" ||
776
+ l?.type.kind === "array" ||
777
+ this.isPipeline(callee.expression) ||
778
+ this.peekArray(callee.expression) ||
779
+ this.isVecArgView(callee.expression) ||
780
+ this.isInlineArray(callee.expression))
753
781
  return this.listMethod(node, method);
754
782
  }
755
783
  // A map / filter chain is consumed by a list method, `.length` or for…of, or stored: const ys = xs.map(…).
756
784
  if (this.isPipeline(node))
757
785
  this.fail(node, `${method} builds a new list: store it (const ys = xs.${method}(…)), or use it right away with a list method, .length or for…of`);
758
- // Vec<T> instruction arguments are read-only views.
759
- if (ts.isIdentifier(callee.expression)) {
760
- const l = this.lookup(callee.expression.text);
761
- if (l?.type.kind === "vecArg") {
786
+ // Vec<T> instruction arguments (and the instruction data) are read-only views; slice gives another one.
787
+ if (this.isVecArgView(callee.expression)) {
788
+ if (method === "slice")
789
+ return this.vecArgView(node);
790
+ const l = this.vecArgView(callee.expression);
791
+ {
762
792
  // Bytes (instruction data, a Vec<u8> argument): little-endian reads at a byte offset, bounds-checked (5104).
763
793
  const le = {
764
794
  readU8: ["uint8_t", 1, U8],
@@ -788,7 +818,7 @@ export class CallEmitter extends ExpressionEmitter {
788
818
  return { c: `(((const TS_Str *)${l.c}.ptr)[${idx}])`, type: STRING };
789
819
  }
790
820
  if (!isScalar(elem))
791
- this.fail(node, `read a field of the element: ${callee.expression.text}.get(i).field`);
821
+ this.fail(node, `read a field of the element: ${ts.isIdentifier(callee.expression) ? callee.expression.text : "list"}.get(i).field`);
792
822
  const idx = this.index(args[0], `(uint64_t)${l.c}.len`);
793
823
  const t = this.tmp("el");
794
824
  this.line(`${scalarStorageC(elem)} ${t};`);
@@ -853,6 +883,9 @@ export class CallEmitter extends ExpressionEmitter {
853
883
  const right = this.expect(this.expr(args[0], left.type), left.type, args[0]);
854
884
  return { c: `ts_key_eq(${this.settle(left, mark).c}, ${right.c})`, type: BOOL };
855
885
  }
886
+ const at = this.programAtValue(callee.expression);
887
+ if (at)
888
+ return this.programAtMethod(node, at, method);
856
889
  if (this.accountAt(callee.expression)) {
857
890
  const target = this.accountAt(callee.expression);
858
891
  // Program accounts used through their methods (systemProgram.transfer, tokenProgram.*…) may be optional.
@@ -871,30 +904,19 @@ export class CallEmitter extends ExpressionEmitter {
871
904
  if (target?.kind.kind === "system" && method === "transfer")
872
905
  return this.systemTransfer(node);
873
906
  if (target?.kind.kind === "system" && method === "createAccount")
874
- return this.createAccount(node, target);
907
+ return this.createAccount(node, this.programParam(target));
875
908
  if (target?.kind.kind === "system" && method === "createPda")
876
909
  return this.createPda(node);
877
910
  if (target?.kind.kind === "system" && (method === "allocate" || method === "assign"))
878
- return this.allocateOrAssign(node, target, method);
911
+ return this.allocateOrAssign(node, this.programParam(target), method);
879
912
  if (target?.kind.kind === "tokenProgram")
880
- return this.tokenOp(node, target, method);
913
+ return this.tokenOp(node, this.programParam(target), method);
881
914
  if (target?.kind.kind === "ataProgram")
882
- return this.ataOp(node, target, method);
915
+ return this.ataOp(node, this.programParam(target), method);
883
916
  if (target?.kind.kind === "memoProgram")
884
- return this.memoOp(node, target, method);
885
- if (target?.kind.kind === "stakeHistory") {
886
- const fields = { has: 0, effective: 1, activating: 2, deactivating: 3 };
887
- if (!(method in fields))
888
- this.fail(callee.name, "StakeHistorySysvar has has(epoch), effective(epoch), activating(epoch) and deactivating(epoch)");
889
- if (args.length !== 1)
890
- this.fail(node, `${method}(epoch) takes the epoch`);
891
- const epoch = this.expect(this.expr(args[0], U64), U64, args[0]);
892
- const f = this.tmp("shf");
893
- const v = this.tmp("shv");
894
- this.line(`bool ${f};`);
895
- this.line(`uint64_t ${v} = ts_stake_history(a_${target.name}, ${epoch.c}, ${Math.max(1, fields[method])}, &${f});`);
896
- return method === "has" ? { c: f, type: BOOL } : { c: v, type: U64 };
897
- }
917
+ return this.memoOp(node, this.programParam(target), method);
918
+ if (target?.kind.kind === "stakeHistory")
919
+ return this.stakeHistoryRead(node, `a_${target.name}`, method);
898
920
  if (target?.kind.kind === "sbRandomness") {
899
921
  if (method !== "value" && method !== "valueU64")
900
922
  this.fail(callee.name, "SwitchboardRandomness has value() and valueU64()");
@@ -906,7 +928,7 @@ export class CallEmitter extends ExpressionEmitter {
906
928
  return method === "value" ? { c: `((const SolPubkey *)${t})`, type: HASH } : { c: `ts_read_le(${t}, 8)`, type: U64 };
907
929
  }
908
930
  if (target?.kind.kind === "stakeProgram")
909
- return this.stakeOp(node, target, method);
931
+ return this.stakeOp(node, this.programParam(target), method);
910
932
  if (target?.kind.kind === "metadataProgram")
911
933
  return this.metadataOp(node, target, method);
912
934
  // Each Metaplex CPI in its own C block: its data buffer's stack slot is reused by the next one.
@@ -984,6 +1006,11 @@ export class CallEmitter extends ExpressionEmitter {
984
1006
  this.fail(node, "only Vecs of Mut<...> / Init<...> accounts can grow or shrink");
985
1007
  this.line(`TS_TRY(ts_resize(params, ${payer}, a_${v.account.name}, 8 + ${info.fixed} + (${newLen}) * ${info.elemSize}, entry_${v.account.name}));`);
986
1008
  };
1009
+ if (info.big !== undefined) {
1010
+ const done = this.bigVecMethod(node, method, v, { stageElem, needWritable, elemPaths });
1011
+ if (done)
1012
+ return done.value;
1013
+ }
987
1014
  /**
988
1015
  * The growable Vecs stored after this one move by `by` bytes (+ grows, - shrinks): where they start and how many
989
1016
  * bytes they take, read before the resize; references into them cannot outlive this call.
@@ -1000,6 +1027,23 @@ export class CallEmitter extends ExpressionEmitter {
1000
1027
  return { at, n };
1001
1028
  };
1002
1029
  switch (method) {
1030
+ case "pushAll": {
1031
+ // Every element of another list appended in one copy (a memcpy, not a loop of pushes).
1032
+ if (info.cap === undefined || info.heap)
1033
+ this.fail(node, "pushAll(items) appends to a FixedVec; a Vec grows one push(value) at a time (for (const x of items) list.push(x, …))");
1034
+ if (args.length !== 1)
1035
+ this.fail(node, "pushAll(items) takes the list to append");
1036
+ needWritable();
1037
+ const src = this.bulkSource(args[0], vt.elem);
1038
+ const n = this.tmp("n");
1039
+ const k = this.tmp("k");
1040
+ this.line(`uint64_t ${n} = ${count};`);
1041
+ this.line(`uint64_t ${k} = ${src.count};`);
1042
+ this.line(`if (${k} > ${info.cap} - ${n}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: pushAll() past the FixedVec's room");`);
1043
+ this.line(`ts_memcpy_bulk((uint8_t *)${info.items} + ${n} * ${info.elemSize}, (const uint8_t *)${src.items}, ${k} * ${info.elemSize});`);
1044
+ this.line(`${info.len} = (uint32_t)(${n} + ${k});`);
1045
+ return undefined;
1046
+ }
1003
1047
  case "set": {
1004
1048
  if (args.length !== 2)
1005
1049
  this.fail(node, "set(index, value) takes two arguments");
@@ -1105,6 +1149,148 @@ export class CallEmitter extends ExpressionEmitter {
1105
1149
  }
1106
1150
  this.fail(node, `Vecs support get, set, push, pop, clear and .length, not ${method}()`);
1107
1151
  }
1152
+ /**
1153
+ * The methods a BigVec adds or changes (SPL's big_vec): `push` into the account's room, `retain`, and the refusals;
1154
+ * undefined for the methods it shares with other lists (`set`).
1155
+ */
1156
+ bigVecMethod(node, method, v, h) {
1157
+ const args = node.arguments;
1158
+ const info = v.vec;
1159
+ const vt = v.type;
1160
+ if (method === "set")
1161
+ return undefined;
1162
+ if (method === "slice")
1163
+ this.fail(node, "use slice(start, end) right where it is read: for (const x of list.slice(a, b)), list.slice(a, b).forEach(…) or .get(i)");
1164
+ if (info.slice)
1165
+ this.fail(node, `a slice has get, set, .length, for … of and the list methods; call ${method}() on the BigVec itself`);
1166
+ switch (method) {
1167
+ case "push": {
1168
+ // BigVec::push: the element goes after the last one if the account has room for it, else AccountDataTooSmall.
1169
+ if (args.length !== 1)
1170
+ this.fail(node, "push(value) on a BigVec takes the value (its room is the account's, never resized)");
1171
+ h.needWritable();
1172
+ const write = h.stageElem(args[0]);
1173
+ const n = this.tmp("n");
1174
+ this.line(`uint64_t ${n} = (uint64_t)${info.len};`);
1175
+ this.line(`if (${n} >= ${info.big}) ${this.programErrorFail("AccountDataTooSmall", node)};`);
1176
+ this.line(`${info.len} = (uint32_t)(${n} + 1);`);
1177
+ write(this.withFixedVec({ ...v, lv: `${info.items}[${n}]`, type: vt.elem, vec: undefined, path: undefined }));
1178
+ return { value: undefined };
1179
+ }
1180
+ case "retain": {
1181
+ // BigVec::retain: one pass, the predicate reading each element where it was; each run of kept elements moves
1182
+ // down once (sol_memmove), when the next removal (or the end) is found. Bytes past the new end keep what they held.
1183
+ if (args.length !== 1)
1184
+ this.fail(node, "retain(fn) takes one argument: (x) => keep it");
1185
+ const cb = args[0];
1186
+ if (!ts.isArrowFunction(cb) && !ts.isFunctionExpression(cb))
1187
+ this.fail(cb, "pass retain an arrow function written here: xs.retain((x) => …)");
1188
+ if (cb.parameters.length > 1)
1189
+ this.fail(cb.parameters[1], "retain's callback takes the element");
1190
+ h.needWritable();
1191
+ this.assertNotAliased(h.elemPaths(), node);
1192
+ const size = info.elemSize;
1193
+ if (vt.elem.kind === "struct")
1194
+ return this.retainStructs(node, cb, v, vt.elem.name, size);
1195
+ const items = this.tmp("rt_items");
1196
+ const n = this.tmp("rt_n");
1197
+ const removed = this.tmp("rt_removed");
1198
+ const dst = this.tmp("rt_dst");
1199
+ const i = this.tmp("rt_i");
1200
+ const move = (count) => `sol_memmove_(${items} + ${dst} * ${size}, ${items} + (${dst} + ${removed}) * ${size}, (${count}) * ${size});`;
1201
+ this.line(`{`);
1202
+ this.block(() => {
1203
+ this.line(`uint8_t *${items} = (uint8_t *)${info.items};`);
1204
+ this.line(`uint64_t ${n} = ${vecCount(info)}, ${removed} = 0, ${dst} = 0;`);
1205
+ this.line(`for (uint64_t ${i} = 0; ${i} < ${n}; ${i}++) {`);
1206
+ this.block(() => {
1207
+ const f = ts.factory;
1208
+ const place = (x) => {
1209
+ ts.setTextRange(x, node);
1210
+ x.parent = node;
1211
+ return x;
1212
+ };
1213
+ const index = `__rt${this.temp++}`;
1214
+ this.scopes.at(-1).set(index, { c: i, type: U64, mutable: false });
1215
+ const list = node.expression.expression;
1216
+ const element = place(f.createCallExpression(place(f.createPropertyAccessExpression(list, "get")), undefined, [place(f.createIdentifier(index))]));
1217
+ const closure = { node: cb, name: "retain's callback", scopes: [...this.scopes], env: this.envNow(), imports: this.scope.imports };
1218
+ const kept = this.expandClosure(closure, [element].slice(0, cb.parameters.length), cb);
1219
+ if (!kept)
1220
+ this.fail(cb, "retain's callback returns a boolean: true keeps the element");
1221
+ const b = this.expect(kept, BOOL, cb);
1222
+ this.line(`if (!(${b.c})) {`);
1223
+ this.line(` if (${removed} > 0 && ${i} - ${removed} > ${dst}) ${move(`${i} - ${removed} - ${dst}`)}`);
1224
+ this.line(` ${dst} = ${i} - ${removed};`);
1225
+ this.line(` ${removed}++;`);
1226
+ this.line(`}`);
1227
+ });
1228
+ this.line(`}`);
1229
+ this.line(`if (${removed} > 0 && ${n} - ${removed} > ${dst}) ${move(`${n} - ${removed} - ${dst}`)}`);
1230
+ this.line(`${info.len} = (uint32_t)(${n} - ${removed});`);
1231
+ });
1232
+ this.line(`}`);
1233
+ return { value: undefined };
1234
+ }
1235
+ case "pop":
1236
+ case "clear":
1237
+ this.fail(node, `a BigVec has push and retain (as SPL's big_vec), not ${method}(): remove elements with retain((x) => …)`);
1238
+ }
1239
+ this.fail(node, `a BigVec supports get, set, push, retain, slice, find / findIndex and the other list methods, .length and .capacity, not ${method}()`);
1240
+ }
1241
+ /**
1242
+ * BigVec::retain over struct elements, walked with a pointer: the predicate gets each element in place, a kept one
1243
+ * costs its predicate and the step. `run` is the first element not yet moved (the run of kept ones since the last
1244
+ * removal), `dst` where that run goes; each run moves down once, when the next removal (or the end) is found, and
1245
+ * only once something before it was removed. The length is written once, at the end (the moves never reach it).
1246
+ */
1247
+ retainStructs(node, cb, v, struct, size) {
1248
+ const info = v.vec;
1249
+ const items = this.tmp("rt_items");
1250
+ const end = this.tmp("rt_end");
1251
+ const run = this.tmp("rt_run");
1252
+ const dst = this.tmp("rt_dst");
1253
+ const p = this.tmp("rt_p");
1254
+ this.line(`{`);
1255
+ this.block(() => {
1256
+ this.line(`uint8_t *${items} = (uint8_t *)${info.items};`);
1257
+ this.line(`uint8_t *${end} = ${items} + ${vecCount(info)} * ${size}, *${run} = ${items}, *${dst} = ${items};`);
1258
+ this.line(`for (uint8_t *${p} = ${items}; ${p} < ${end}; ${p} += ${size}) {`);
1259
+ this.block(() => {
1260
+ const el = this.tmp("rt_el");
1261
+ this.line(`TSS_${struct} *${el} = (TSS_${struct} *)${p};`);
1262
+ const list = node.expression.expression;
1263
+ const id = ts.factory.createIdentifier(`__rt${this.temp++}`);
1264
+ ts.setTextRange(id, node);
1265
+ id.parent = node;
1266
+ // The element as list.get(i) gives it: a reference into the list, with the list's aliasing paths.
1267
+ this.scopes.at(-1).set(id.text, {
1268
+ c: el,
1269
+ type: { kind: "structRef", struct, writable: !!v.writable },
1270
+ mutable: false,
1271
+ paths: this.pathsOf(list)?.map((x) => `${x}[]`),
1272
+ });
1273
+ const closure = { node: cb, name: "retain's callback", scopes: [...this.scopes], env: this.envNow(), imports: this.scope.imports };
1274
+ const kept = this.expandClosure(closure, [id].slice(0, cb.parameters.length), cb);
1275
+ if (!kept)
1276
+ this.fail(cb, "retain's callback returns a boolean: true keeps the element");
1277
+ const b = this.expect(kept, BOOL, cb);
1278
+ const at = this.tmp("rt_at");
1279
+ this.line(`if (!(${b.c})) {`);
1280
+ // The removal's own copy of the position, so the scan loop keeps a single pointer (see ts_opaque_ptr).
1281
+ this.line(` uint8_t *${at} = ts_opaque_ptr(${p});`);
1282
+ this.line(` if (${dst} != ${run} && ${at} != ${run}) sol_memmove_(${dst}, ${run}, ${at} - ${run});`);
1283
+ this.line(` ${dst} += ${at} - ${run};`);
1284
+ this.line(` ${run} = ${at} + ${size};`);
1285
+ this.line(`}`);
1286
+ });
1287
+ this.line(`}`);
1288
+ this.line(`if (${dst} != ${run} && ${end} != ${run}) sol_memmove_(${dst}, ${run}, ${end} - ${run});`);
1289
+ this.line(`${info.len} = (uint32_t)((uint64_t)(${dst} + (${end} - ${run}) - ${items}) / ${size});`);
1290
+ });
1291
+ this.line(`}`);
1292
+ return { value: undefined };
1293
+ }
1108
1294
  /** sha256(...) / keccak256(...) over strings, Pubkeys, Hashes, integers (LE) and booleans. */
1109
1295
  hashCall(node, fn) {
1110
1296
  if (node.arguments.length === 0 || node.arguments.length > 16)
@@ -1337,9 +1523,155 @@ export class CallEmitter extends ExpressionEmitter {
1337
1523
  }
1338
1524
  this.fail(node, "a TransactionInstruction has programId, accountsLength, dataLength, accountKey/accountIsSigner/accountIsWritable(i), readU8/U16/U32/U64/readPubkey(offset) and is(program, name)");
1339
1525
  }
1526
+ /** `fixedArray<T, N>(fill)` written inline (a list method, a map / filter chain or `for … of` over it). */
1527
+ isInlineArray(node) {
1528
+ if (ts.isParenthesizedExpression(node))
1529
+ return this.isInlineArray(node.expression);
1530
+ return ts.isCallExpression(node) && this.exportName(node.expression) === "fixedArray";
1531
+ }
1532
+ /**
1533
+ * Whether `node` is a read-only view of a Vec argument or the instruction data, without emitting code: a local or
1534
+ * helper parameter holding one, or `.slice(start, end?)` of such a view.
1535
+ */
1536
+ isVecArgView(node) {
1537
+ if (ts.isParenthesizedExpression(node))
1538
+ return this.isVecArgView(node.expression);
1539
+ if (ts.isIdentifier(node))
1540
+ return this.lookup(node.text)?.type.kind === "vecArg";
1541
+ return (ts.isCallExpression(node) &&
1542
+ ts.isPropertyAccessExpression(node.expression) &&
1543
+ node.expression.name.text === "slice" &&
1544
+ this.isVecArgView(node.expression.expression));
1545
+ }
1546
+ /**
1547
+ * The view `node` names (see isVecArgView) as a `TS_VecArg` C expression. `.slice(start, end)` is elements start..end-1
1548
+ * in place (`end` defaults to the length): unlike JS's slice it does not clamp, an `end` past the length or before
1549
+ * `start` fails with 5104. Undefined when `node` is not such a view.
1550
+ */
1551
+ vecArgView(node) {
1552
+ if (ts.isParenthesizedExpression(node))
1553
+ return this.vecArgView(node.expression);
1554
+ if (ts.isIdentifier(node)) {
1555
+ const l = this.lookup(node.text);
1556
+ return l?.type.kind === "vecArg" ? { c: l.c, type: l.type } : undefined;
1557
+ }
1558
+ if (!this.isVecArgView(node))
1559
+ return undefined;
1560
+ const call = node;
1561
+ const base = this.vecArgView(call.expression.expression);
1562
+ if (base.type.optional)
1563
+ this.fail(call, "check the Option argument is not null before slicing it");
1564
+ const elem = base.type.elem;
1565
+ if (elem.kind === "string")
1566
+ this.fail(call, "slice works on lists of fixed-size elements, not on a Vec<string>");
1567
+ if (call.arguments.length < 1 || call.arguments.length > 2)
1568
+ this.fail(call, "slice(start, end?) takes the first element's index and the index after the last one");
1569
+ const start = this.tmp("sl_start");
1570
+ const end = this.tmp("sl_end");
1571
+ this.line(`uint64_t ${start} = ${this.expect(this.expr(call.arguments[0], U64), U64, call.arguments[0]).c};`);
1572
+ this.line(`uint64_t ${end} = ${call.arguments[1] ? this.expect(this.expr(call.arguments[1], U64), U64, call.arguments[1]).c : `(uint64_t)${base.c}.len`};`);
1573
+ this.line(`if (${end} > (uint64_t)${base.c}.len || ${start} > ${end}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: slice out of range");`);
1574
+ const t = this.tmp("view");
1575
+ this.line(`TS_VecArg ${t} = {${base.c}.ptr + ${start} * ${this.fieldBytes(elem)}, (uint32_t)(${end} - ${start})};`);
1576
+ return { c: t, type: { kind: "vecArg", elem } };
1577
+ }
1578
+ /**
1579
+ * A list's elements as one contiguous run, for a bulk copy or a CPI: a Vec argument, the instruction data or a slice
1580
+ * of them; a Vec, FixedVec, BigVec (slice) or FixedArray in account data or a local. Undefined for anything else.
1581
+ */
1582
+ listSpan(e) {
1583
+ if (this.isVecArgView(e)) {
1584
+ const v = this.vecArgView(e);
1585
+ return { items: `${v.c}.ptr`, count: `((uint64_t)${v.c}.len)`, elem: v.type.elem, view: true };
1586
+ }
1587
+ const r = this.ref(e);
1588
+ if (r?.type.kind === "array")
1589
+ return { items: `${r.lv}`, count: `${r.type.len}ULL`, elem: r.type.elem, view: false };
1590
+ if (r?.vec && r.type.kind === "vec")
1591
+ return { items: r.vec.items, count: vecCount(r.vec), elem: r.type.elem, view: false };
1592
+ return undefined;
1593
+ }
1594
+ /** `pushAll(items)`'s source: a list of exactly `elem` (see listSpan). */
1595
+ bulkSource(e, elem) {
1596
+ const what = `pushAll takes a list of ${typeName(elem)}: a Vec, FixedVec or FixedArray, a Vec argument, or the instruction data or a slice of it`;
1597
+ const s = this.listSpan(e) ?? this.fail(e, what);
1598
+ if (!sameType(s.elem, elem))
1599
+ this.fail(e, what);
1600
+ // A Vec argument's booleans and enums are checked as each is read (get, for … of), not on entry.
1601
+ if (s.view && (elem.kind === "bool" || elem.kind === "enum"))
1602
+ this.fail(e, "a Vec argument's booleans and enums are checked as each is read: push them one by one (for … of)");
1603
+ return s;
1604
+ }
1605
+ /**
1606
+ * Whether `node` names one account a choice may pick, without emitting code: a remaining account (`rest.get(i)`), a
1607
+ * local or `RemainingAccount` helper parameter bound to one, an `AccountInfo` parameter, or a choice between those.
1608
+ */
1609
+ looksLikeAccountHandle(node) {
1610
+ if (ts.isParenthesizedExpression(node))
1611
+ return this.looksLikeAccountHandle(node.expression);
1612
+ if (ts.isConditionalExpression(node))
1613
+ return this.looksLikeAccountHandle(node.whenTrue) && this.looksLikeAccountHandle(node.whenFalse);
1614
+ if (ts.isIdentifier(node)) {
1615
+ const l = this.lookup(node.text);
1616
+ if (l)
1617
+ return l.type.kind === "account";
1618
+ return this.accountAt(node)?.kind.kind === "info";
1619
+ }
1620
+ return (ts.isCallExpression(node) &&
1621
+ ts.isPropertyAccessExpression(node.expression) &&
1622
+ node.expression.name.text === "get" &&
1623
+ this.isRemaining(node.expression.expression));
1624
+ }
1625
+ /**
1626
+ * `c ? rest.get(5n) : reserve`: one of two accounts, chosen at run time (only the chosen side runs), as a `TsAccount *`
1627
+ * usable wherever a remaining account is. Each side is a remaining account, a local or helper parameter bound to one,
1628
+ * an `AccountInfo` parameter or another such choice; a `programAt` check is kept when both sides carry the same one.
1629
+ */
1630
+ accountChoice(node) {
1631
+ const side = (e) => {
1632
+ if (ts.isParenthesizedExpression(e))
1633
+ return side(e.expression);
1634
+ if (ts.isConditionalExpression(e))
1635
+ return this.accountChoice(e);
1636
+ if (ts.isIdentifier(e)) {
1637
+ const l = this.lookup(e.text);
1638
+ if (l?.type.kind === "account")
1639
+ return { c: l.c, type: l.type };
1640
+ const a = this.accountAt(e);
1641
+ if (!l && a?.kind.kind === "info")
1642
+ return { c: `a_${this.accountParam(e, "a choice between accounts").name}`, type: { kind: "account" } };
1643
+ }
1644
+ const h = this.handle(e);
1645
+ if (h)
1646
+ return { c: h, type: { kind: "account" } };
1647
+ this.fail(e, "choose between accounts of the same kind: remaining accounts (rest.get(i), a local or RemainingAccount parameter bound to one) or AccountInfo parameters");
1648
+ };
1649
+ const cond = this.expect(this.expr(node.condition, BOOL), BOOL, node.condition);
1650
+ const t = this.tmp("acct");
1651
+ this.line(`TsAccount *${t};`);
1652
+ this.line(`if (${cond.c}) {`);
1653
+ let a;
1654
+ let b;
1655
+ this.block(() => {
1656
+ a = side(node.whenTrue);
1657
+ this.line(`${t} = ${a.c};`);
1658
+ });
1659
+ this.line(`} else {`);
1660
+ this.block(() => {
1661
+ b = side(node.whenFalse);
1662
+ this.line(`${t} = ${b.c};`);
1663
+ });
1664
+ this.line(`}`);
1665
+ const pa = a.type.kind === "account" ? a.type.program : undefined;
1666
+ const pb = b.type.kind === "account" ? b.type.program : undefined;
1667
+ const program = pa && pb && JSON.stringify(pa) === JSON.stringify(pb) ? pa : undefined;
1668
+ return { c: t, type: { kind: "account", ...(program ? { program } : {}) } };
1669
+ }
1340
1670
  handle(node) {
1341
1671
  if (ts.isParenthesizedExpression(node))
1342
1672
  return this.handle(node.expression);
1673
+ if (ts.isConditionalExpression(node) && this.looksLikeAccountHandle(node))
1674
+ return this.accountChoice(node).c;
1343
1675
  if (ts.isIdentifier(node)) {
1344
1676
  const l = this.lookup(node.text);
1345
1677
  return l?.type.kind === "account" ? l.c : undefined;
@@ -1365,6 +1697,125 @@ export class CallEmitter extends ExpressionEmitter {
1365
1697
  return h;
1366
1698
  return `a_${this.accountParam(node, what).name}`;
1367
1699
  }
1700
+ /**
1701
+ * An account argument of a typed CPI: a declared account parameter (`param`, its kind and writability checked by
1702
+ * the caller), or a remaining account, a local bound to one, a RemainingAccount helper parameter or a loaded struct
1703
+ * (no compile-time checks: the called program and the runtime check them).
1704
+ */
1705
+ cpiAccount(node, what) {
1706
+ const h = this.handle(node);
1707
+ if (h)
1708
+ return { c: h };
1709
+ const loaded = ts.isIdentifier(node) ? this.lookup(node.text)?.loaded : undefined;
1710
+ if (loaded)
1711
+ return { c: loaded.handle };
1712
+ const param = this.accountParam(node, what);
1713
+ return { c: `a_${param.name}`, param };
1714
+ }
1715
+ /** A declared program parameter as the program of a typed CPI. */
1716
+ programParam(a) {
1717
+ return { c: `a_${a.name}`, kind: a.kind };
1718
+ }
1719
+ /**
1720
+ * `programAt<P>(acct)` / `sysvarAt<S>(acct)`: the account (a remaining account or an AccountInfo parameter) checked
1721
+ * to be that program or sysvar by its key, once, then usable with P's typed methods. A wrong program fails with
1722
+ * ProgramError.IncorrectProgramId and a wrong sysvar with ProgramError.InvalidArgument, as solana_program's checks do.
1723
+ */
1724
+ programAt(node, fn) {
1725
+ const programs = {
1726
+ StakeProgram: [{ kind: "stakeProgram" }, "TS_STAKE_PROGRAM_ID", "the Stake program"],
1727
+ SystemProgram: [{ kind: "system" }, "TS_SYSTEM_PROGRAM_ID", "the System Program"],
1728
+ TokenProgram: [{ kind: "tokenProgram", flavor: "token" }, "TS_TOKEN_PROGRAM_ID", "the Token program"],
1729
+ Token2022Program: [{ kind: "tokenProgram", flavor: "token2022" }, "TS_TOKEN_2022_PROGRAM_ID", "the Token-2022 program"],
1730
+ TokenInterface: [{ kind: "tokenProgram", flavor: "tokenInterface" }, undefined, "a token program"],
1731
+ AssociatedTokenProgram: [{ kind: "ataProgram" }, "TS_ATA_PROGRAM_ID", "the Associated Token program"],
1732
+ MemoProgram: [{ kind: "memoProgram" }, "TS_MEMO_PROGRAM_ID", "the Memo program"],
1733
+ };
1734
+ const sysvars = { StakeHistorySysvar: [{ kind: "stakeHistory" }, "TS_STAKE_HISTORY_ID", "the StakeHistory sysvar"] };
1735
+ const table = fn === "programAt" ? programs : sysvars;
1736
+ const targ = node.typeArguments?.[0];
1737
+ const name = targ && typesolName(targ, this.scope.imports);
1738
+ const entry = name ? table[name] : undefined;
1739
+ if (!entry)
1740
+ this.fail(targ ?? node, fn === "programAt" ? `programAt<P>(account): P is one of ${Object.keys(programs).join(", ")}` : "sysvarAt<S>(account): S is StakeHistorySysvar");
1741
+ if (node.arguments.length !== 1)
1742
+ this.fail(node, `${fn}<${name}>(account) takes one remaining account or AccountInfo parameter`);
1743
+ const arg = node.arguments[0];
1744
+ let h = this.handle(arg);
1745
+ if (!h) {
1746
+ const acct = this.accountParam(arg, `${fn}'s account`);
1747
+ if (acct.kind.kind !== "info")
1748
+ this.fail(arg, `pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter; a declared parameter can be typed ${name} itself`);
1749
+ h = `a_${acct.name}`;
1750
+ }
1751
+ const [kind, id, what] = entry;
1752
+ const err = PROGRAM_ERRORS.indexOf(fn === "programAt" ? "IncorrectProgramId" : "InvalidArgument");
1753
+ // `const PROGRAM_ERROR_LOG_PREFIX = "Program error: "`: logged as a native entrypoint logs the error.
1754
+ const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
1755
+ const text = typeof pre === "string" ? `${pre}${PROGRAM_ERRORS[err]}` : `TypeSOL: not ${what}`;
1756
+ const bad = id ? `!ts_key_eq(&${h}->key, &${id})` : `!ts_is_token_program(&${h}->key)`;
1757
+ this.line(`if (${bad}) TS_FAIL(((uint64_t)${err + 2}) << 32, ${cString(text)});`);
1758
+ if (kind.kind === "stakeHistory")
1759
+ this.line(`if (${h}->data_len < 8) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: not the StakeHistory sysvar's data");`);
1760
+ return { c: h, type: { kind: "account", program: kind } };
1761
+ }
1762
+ /** A value `programAt` / `sysvarAt` checked (a local bound to one, or the call itself), as the program it is. */
1763
+ programAtValue(node) {
1764
+ if (ts.isParenthesizedExpression(node))
1765
+ return this.programAtValue(node.expression);
1766
+ if (ts.isIdentifier(node)) {
1767
+ const l = this.lookup(node.text);
1768
+ return l?.type.kind === "account" && l.type.program ? { c: l.c, kind: l.type.program } : undefined;
1769
+ }
1770
+ if (!ts.isCallExpression(node))
1771
+ return undefined;
1772
+ const fn = this.exportName(node.expression);
1773
+ if (fn !== "programAt" && fn !== "sysvarAt")
1774
+ return undefined;
1775
+ const v = this.programAt(node, fn);
1776
+ return { c: v.c, kind: v.type.program };
1777
+ }
1778
+ /** `stake.split(…)` on a programAt value: the same typed methods as on a declared program parameter. */
1779
+ programAtMethod(node, at, method) {
1780
+ switch (at.kind.kind) {
1781
+ case "system":
1782
+ if (method === "transfer")
1783
+ return this.systemTransfer(node);
1784
+ if (method === "createAccount")
1785
+ return this.createAccount(node, at);
1786
+ if (method === "createPda")
1787
+ return this.createPda(node);
1788
+ if (method === "allocate" || method === "assign")
1789
+ return this.allocateOrAssign(node, at, method);
1790
+ this.fail(node.expression, `the System Program has transfer, createAccount, createPda, allocate and assign, not ${method}`);
1791
+ case "tokenProgram":
1792
+ return this.tokenOp(node, at, method);
1793
+ case "ataProgram":
1794
+ return this.ataOp(node, at, method);
1795
+ case "memoProgram":
1796
+ return this.memoOp(node, at, method);
1797
+ case "stakeProgram":
1798
+ return this.stakeOp(node, at, method);
1799
+ case "stakeHistory":
1800
+ return this.stakeHistoryRead(node, at.c, method);
1801
+ }
1802
+ this.fail(node.expression, `unsupported call: ${method}`);
1803
+ }
1804
+ /** StakeHistorySysvar's has / effective / activating / deactivating(epoch), on the sysvar account `h`. */
1805
+ stakeHistoryRead(node, h, method) {
1806
+ const args = node.arguments;
1807
+ const fields = { has: 0, effective: 1, activating: 2, deactivating: 3 };
1808
+ if (!(method in fields))
1809
+ this.fail(node.expression.name, "StakeHistorySysvar has has(epoch), effective(epoch), activating(epoch) and deactivating(epoch)");
1810
+ if (args.length !== 1)
1811
+ this.fail(node, `${method}(epoch) takes the epoch`);
1812
+ const epoch = this.expect(this.expr(args[0], U64), U64, args[0]);
1813
+ const f = this.tmp("shf");
1814
+ const v = this.tmp("shv");
1815
+ this.line(`bool ${f};`);
1816
+ this.line(`uint64_t ${v} = ts_stake_history(${h}, ${epoch.c}, ${Math.max(1, fields[method])}, &${f});`);
1817
+ return method === "has" ? { c: f, type: BOOL } : { c: v, type: U64 };
1818
+ }
1368
1819
  /** `readData<T>(account, offset)`: a bounds-checked little-endian read of any account's data. */
1369
1820
  readData(node) {
1370
1821
  const targ = node.typeArguments?.[0];
@@ -1452,7 +1903,7 @@ export class CallEmitter extends ExpressionEmitter {
1452
1903
  const fn = mut ? "loadRawMut" : "loadRaw";
1453
1904
  const targ = node.typeArguments?.[0];
1454
1905
  const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
1455
- if (!s || s.size === undefined || s.vec)
1906
+ if (!s || s.size === undefined || (s.vec && !s.bigVec))
1456
1907
  this.fail(node, `${fn} needs a fixed-size struct type: ${fn}<MyStruct>(account)`);
1457
1908
  if (s.layout === "borsh")
1458
1909
  this.fail(node, `${s.name} is @layout borsh: ${fn} reads fixed layouts only`);
@@ -1464,8 +1915,8 @@ export class CallEmitter extends ExpressionEmitter {
1464
1915
  const acct = this.accountParam(node.arguments[0], "the account");
1465
1916
  if (acct.kind.kind !== "info")
1466
1917
  this.fail(node.arguments[0], "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter");
1467
- if (mut && !isWritable(acct.kind))
1468
- this.fail(node.arguments[0], `${acct.name} must be Mut<AccountInfo> to load it with loadRawMut`);
1918
+ if (mut && !isWritable(acct.kind) && !this.nativeAccountWrites())
1919
+ this.fail(node.arguments[0], `${acct.name} must be Mut<AccountInfo> to load it with loadRawMut (or declare const NATIVE_ACCOUNT_WRITES = true to leave writability to the runtime, as a native program does)`);
1469
1920
  if (!this.ix)
1470
1921
  this.fail(node, `load ${acct.name} in the instruction and pass the struct on`);
1471
1922
  h = `a_${acct.name}`;
@@ -1473,7 +1924,20 @@ export class CallEmitter extends ExpressionEmitter {
1473
1924
  }
1474
1925
  this.line(`if (!ts_key_eq(&${h}->owner, params->program_id)) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program");`);
1475
1926
  this.line(`if (${h}->data_len < sizeof(TSS_${s.name})) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account data too small");`);
1476
- if (mut) {
1927
+ // A BigVec's stored length must fit in the account. Its capacity is kept in a local: every access is clamped to it
1928
+ // (the length may be written again after this), without a division each time.
1929
+ let bigCap;
1930
+ if (s.bigVec) {
1931
+ bigCap = this.tmp("bv_cap");
1932
+ this.line(`uint64_t ${bigCap} = (${h}->data_len - sizeof(TSS_${s.name})) / ${s.bigVec.elemSize};`);
1933
+ this.line(`if ((uint64_t)((TSS_${s.name} *)(${h}->data))->${s.bigVec.name}__len > ${bigCap}) ${this.programErrorFail("AccountDataTooSmall", node)};`);
1934
+ // Named in scope, so a loop moved into a function of its own is given it (see outlinedLoop).
1935
+ this.scopes.at(-1).set(`__${bigCap}`, { c: bigCap, type: U64, mutable: false });
1936
+ }
1937
+ // NATIVE_ACCOUNT_WRITES: no writability check and no claim. The view writes in place; the runtime refuses the
1938
+ // instruction if a read-only account's data changed, and two views of one account share its bytes (the loader
1939
+ // gives a duplicate the same record), as two AccountInfos of one account share one buffer in Rust.
1940
+ if (mut && !this.nativeAccountWrites()) {
1477
1941
  this.line(`TS_TRY(ts_check_writable(${h}));`);
1478
1942
  const slot = this.claimSlots.get(node);
1479
1943
  if (slot)
@@ -1483,7 +1947,108 @@ export class CallEmitter extends ExpressionEmitter {
1483
1947
  else
1484
1948
  this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
1485
1949
  }
1486
- return { c: `((TSS_${s.name} *)(${h}->data))`, type: { kind: "structRef", struct: s.name, writable: mut } };
1950
+ return { c: `((TSS_${s.name} *)(${h}->data))`, type: { kind: "structRef", struct: s.name, writable: mut }, ...(bigCap ? { bigCap } : {}) };
1951
+ }
1952
+ /**
1953
+ * `const v = loadBorsh<T>(acct)`: the account's data from byte 0 decoded as Borsh into a local `T` (a copy), as
1954
+ * `try_from_slice_unchecked` reads it: no owner check, no discriminator, trailing bytes ignored; bytes that are not
1955
+ * a valid `T` (too short, an Option tag or bool not 0/1, an enum tag out of range) fail with BorshIoError.
1956
+ */
1957
+ loadBorsh(node, c, declared) {
1958
+ const s = this.borshNativeStruct(node, node.typeArguments?.[0], declared, "loadBorsh");
1959
+ if (node.arguments.length !== 1)
1960
+ this.fail(node, "loadBorsh<T>(account) takes one remaining account or AccountInfo parameter");
1961
+ const h = this.borshAccount(node.arguments[0], "loadBorsh", false);
1962
+ this.line(`TSS_${s.name} ${c}__v;`);
1963
+ this.line(`if (ts_bdec_${s.name}(${h}->data, ${h}->data_len, &${c}__v, NULL)) ${this.programErrorFail("BorshIoError", node)};`);
1964
+ this.line(`TSS_${s.name} *${c} = &${c}__v;`);
1965
+ return s;
1966
+ }
1967
+ /**
1968
+ * `storeBorsh(acct, value)`: `value` encoded as Borsh into the account's data from byte 0, as Rust's
1969
+ * `value.serialize(&mut &mut data[..])` writes it: only the encoded bytes (the rest of the account is left as it
1970
+ * was), BorshIoError when they do not fit. The account must be writable.
1971
+ */
1972
+ storeBorsh(node) {
1973
+ if (node.arguments.length !== 2)
1974
+ this.fail(node, "storeBorsh(account, value) takes the account and the struct value to write");
1975
+ const h = this.borshAccount(node.arguments[0], "storeBorsh", true);
1976
+ const valueNode = node.arguments[1];
1977
+ const targ = node.typeArguments?.[0];
1978
+ let ptr;
1979
+ let s;
1980
+ const inner = ts.isParenthesizedExpression(valueNode) ? valueNode.expression : valueNode;
1981
+ if (ts.isObjectLiteralExpression(inner)) {
1982
+ if (!targ)
1983
+ this.fail(valueNode, "storeBorsh needs the struct type for an object literal: storeBorsh<MyStruct>(account, { … })");
1984
+ s = this.borshNativeStruct(node, targ, undefined, "storeBorsh");
1985
+ const t = this.tmp("bval");
1986
+ this.line(`TSS_${s.name} ${t};`);
1987
+ this.writeAggregate({ lv: t, type: { kind: "struct", name: s.name }, writable: true }, inner, true);
1988
+ ptr = `(&${t})`;
1989
+ }
1990
+ else {
1991
+ const place = this.structPlace(valueNode);
1992
+ if (!place)
1993
+ this.fail(valueNode, "storeBorsh writes a struct value: a local (const pool = loadBorsh<Pool>(acct)), a struct field or an object literal");
1994
+ const want = targ ? this.borshNativeStruct(node, targ, undefined, "storeBorsh") : undefined;
1995
+ if (want && want.name !== place.struct)
1996
+ this.fail(valueNode, `expected a ${want.name}, got a ${place.struct}`);
1997
+ s = this.borshNativeStruct(node, undefined, this.model.structs.get(place.struct), "storeBorsh");
1998
+ ptr = place.ptr;
1999
+ }
2000
+ this.line(`if (ts_benc_${s.name}(${ptr}, ${h}->data, ${h}->data_len, NULL)) ${this.programErrorFail("BorshIoError", node)};`);
2001
+ return undefined;
2002
+ }
2003
+ /** The struct loadBorsh / storeBorsh decodes or encodes: from the type argument, else the declared type. */
2004
+ borshNativeStruct(node, targ, declared, fn) {
2005
+ let s = declared;
2006
+ if (targ) {
2007
+ const named = ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
2008
+ if (!named)
2009
+ this.fail(targ, `${fn} needs a struct type: ${fn === "loadBorsh" ? "loadBorsh<MyStruct>(account)" : "storeBorsh<MyStruct>(account, value)"}`);
2010
+ if (declared && declared.name !== named.name)
2011
+ this.fail(node, `loadBorsh<${named.name}> is bound to a ${declared.name}`);
2012
+ s = named;
2013
+ }
2014
+ if (!s)
2015
+ this.fail(node, `${fn} needs a struct type: ${fn === "loadBorsh" ? "const pool = loadBorsh<MyStruct>(account)" : "storeBorsh<MyStruct>(account, value)"}`);
2016
+ const why = borshNativeStructUnsupported(s, this.model);
2017
+ if (why)
2018
+ this.fail(targ ?? node, `${fn} cannot take ${s.name}: ${why}`);
2019
+ this.model.borshNative.add(s.name);
2020
+ return s;
2021
+ }
2022
+ /** The account loadBorsh reads or storeBorsh writes (writable: checked at run time, or Mut<AccountInfo>). */
2023
+ borshAccount(node, fn, write) {
2024
+ const h = this.handle(node);
2025
+ // NATIVE_ACCOUNT_WRITES: written as Rust's serialize writes it, the runtime judging writability afterwards.
2026
+ const native = this.nativeAccountWrites();
2027
+ // Without the flag, a write also needs the account passed once: given again (as another declared account or a
2028
+ // remaining one), what the program reads through the other would not be what it wrote here.
2029
+ if (h) {
2030
+ if (write && !native) {
2031
+ this.line(`TS_TRY(ts_check_writable(${h}));`);
2032
+ this.line(`TS_TRY(ts_check_unaliased(params, ${h}));`);
2033
+ }
2034
+ return h;
2035
+ }
2036
+ const acct = this.accountParam(node, `${fn}'s account`);
2037
+ if (acct.kind.kind !== "info")
2038
+ this.fail(node, `${fn} takes a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter`);
2039
+ if (write && !isWritable(acct.kind) && !native)
2040
+ this.fail(node, `${acct.name} must be Mut<AccountInfo> to write it with storeBorsh (or declare const NATIVE_ACCOUNT_WRITES = true to leave writability to the runtime, as a native program does)`);
2041
+ if (write && !native)
2042
+ this.line(`TS_TRY(ts_check_unaliased(params, a_${acct.name}));`);
2043
+ return `a_${acct.name}`;
2044
+ }
2045
+ /** `TS_FAIL` with a built-in ProgramError (no custom code), logged as `require(…, ProgramError.X)` logs it. */
2046
+ programErrorFail(name, node) {
2047
+ const idx = PROGRAM_ERRORS.indexOf(name);
2048
+ // `const PROGRAM_ERROR_LOG_PREFIX = "Program error: "`: the log line a native entrypoint writes for it.
2049
+ const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
2050
+ const text = typeof pre === "string" ? `${pre}${name}` : `Error: ${name} (${this.location(node)})`;
2051
+ return `TS_FAIL(((uint64_t)${idx + 2}) << 32, ${cString(text)})`;
1487
2052
  }
1488
2053
  /** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
1489
2054
  loadAccount(node, mut) {
@@ -1503,6 +2068,8 @@ export class CallEmitter extends ExpressionEmitter {
1503
2068
  this.fail(node, `${s.name}'s discriminator is shorter than 8 bytes: take it as Owner<Account<${s.name}>, "…">`);
1504
2069
  if (s.layout === "borsh")
1505
2070
  this.fail(node, `${s.name} is @layout borsh: declare it as an instruction parameter (remaining accounts are read in place)`);
2071
+ if (s.bigVec)
2072
+ this.fail(node, `${s.name} ends in a BigVec, a native program's list (no discriminator): read it with loadRaw / loadRawMut`);
1506
2073
  if (node.arguments.length !== 1)
1507
2074
  this.fail(node, "loadAccount<T>(account) takes one remaining account or AccountInfo parameter");
1508
2075
  let h = this.handle(node.arguments[0]);
@@ -1773,6 +2340,14 @@ export class CallEmitter extends ExpressionEmitter {
1773
2340
  this.fail(n, `${h.name}() takes ${p.name} as Mut<${l.loaded.struct}>: load it with loadAccountMut`);
1774
2341
  return l.loaded.handle;
1775
2342
  }
2343
+ // A program or sysvar programAt / sysvarAt checked: as that kind of account.
2344
+ const at = this.programAtValue(n);
2345
+ if (at) {
2346
+ const why = accountMismatch(at.kind, p.account);
2347
+ if (why)
2348
+ this.fail(n, `${h.name}() takes ${p.name} as ${why}`);
2349
+ return at.c;
2350
+ }
1776
2351
  const acct = this.accountParam(n, `${h.name}()'s ${p.name}`);
1777
2352
  const why = accountMismatch(acct.kind, p.account);
1778
2353
  if (why)
@@ -1792,6 +2367,9 @@ export class CallEmitter extends ExpressionEmitter {
1792
2367
  case "structRef":
1793
2368
  case "arrayArg": {
1794
2369
  const want = p.type.kind === "structRef" ? { kind: "struct", name: p.type.struct } : p.type.array;
2370
+ const built = this.literalArg(n, want);
2371
+ if (built)
2372
+ return built;
1795
2373
  let r = this.ref(n);
1796
2374
  // A narrowed Option<Struct> / Option<FixedArray> place (`c.opt !== null` before it): its value.
1797
2375
  if (r && r.type.kind === "option" && sameType(r.type.inner, want))
@@ -1801,12 +2379,22 @@ export class CallEmitter extends ExpressionEmitter {
1801
2379
  return this.snapshotPlace(r.lv, want, h, n);
1802
2380
  }
1803
2381
  case "dataEnumArg": {
2382
+ const built = this.literalArg(n, { kind: "dataEnum", name: p.type.name });
2383
+ if (built)
2384
+ return built;
1804
2385
  const r = this.ref(n);
1805
2386
  if (!r || r.type.kind !== "dataEnum" || r.type.name !== p.type.name)
1806
2387
  this.fail(n, `expected a ${p.type.name}`);
1807
2388
  return this.snapshotPlace(r.lv, { kind: "dataEnum", name: p.type.name }, h, n);
1808
2389
  }
1809
2390
  case "vecArg": {
2391
+ // A slice of a Vec argument or the instruction data: a view of its own, passed like the list.
2392
+ if (!ts.isIdentifier(n) && this.isVecArgView(n)) {
2393
+ const v = this.vecArgView(n);
2394
+ if (!sameType(v.type, p.type))
2395
+ this.fail(n, `expected a ${typeName(p.type)}`);
2396
+ return v.c;
2397
+ }
1810
2398
  const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
1811
2399
  // An Option<Vec<T>> argument passes as its list once checked against null (TypeScript narrows it).
1812
2400
  const t = l?.type.kind === "vecArg" && l.type.optional ? { ...l.type, optional: undefined } : l?.type;
@@ -1818,6 +2406,33 @@ export class CallEmitter extends ExpressionEmitter {
1818
2406
  return this.expect(this.expr(n, p.type), p.type, n);
1819
2407
  }
1820
2408
  }
2409
+ /**
2410
+ * A struct, array or data-enum helper argument written as a literal (`f({ a: 1n, b: { c } })`, `g([1n, 2n])`, or a
2411
+ * ternary with a literal branch): built in a local of its own, as `const x: T = { … }; f(x)` would, and passed by
2412
+ * pointer (the helper cannot change it, and nothing else sees it). Undefined for anything else.
2413
+ */
2414
+ literalArg(n, want) {
2415
+ const literal = (e) => {
2416
+ while (ts.isParenthesizedExpression(e))
2417
+ e = e.expression;
2418
+ if (ts.isConditionalExpression(e))
2419
+ return literal(e.whenTrue) || literal(e.whenFalse);
2420
+ if (want.kind === "array")
2421
+ return ts.isCallExpression(e) && this.exportName(e.expression) === "fixedArray";
2422
+ return ts.isObjectLiteralExpression(e);
2423
+ };
2424
+ if (!literal(n))
2425
+ return undefined;
2426
+ if (want.kind === "struct") {
2427
+ const s = this.model.structs.get(want.name);
2428
+ if (s.size === undefined || s.vec)
2429
+ this.fail(n, `${s.name} has variable-size fields and cannot be built as an argument`);
2430
+ }
2431
+ const t = this.tmp("larg");
2432
+ this.line(`${want.kind === "array" ? storageDecl(want, t) : `${fieldC(want)} ${t}`};`);
2433
+ this.writeAggregate({ lv: t, type: want, writable: true }, n, true);
2434
+ return `(&${t})`;
2435
+ }
1821
2436
  /**
1822
2437
  * A struct/array/data-enum helper argument. Helpers that take accounts may change account data, so they get a
1823
2438
  * copy taken at the call (JS passes the object as it was); other helpers cannot write, so a pointer is enough.
@@ -1832,8 +2447,7 @@ export class CallEmitter extends ExpressionEmitter {
1832
2447
  const n = this.fieldBytes(type);
1833
2448
  // One buffer per call site, allocated on first use: a call in a loop must not take new heap every pass.
1834
2449
  const t = this.tmp("argc");
1835
- const decl = type.kind === "array" ? storageDecl(type, `(*${t})`) : `${fieldC(type)} *${t}`;
1836
- this.hoisted.push(` ${decl} = NULL;`);
2450
+ this.hoistLazy(t, (n) => (type.kind === "array" ? storageDecl(type, `(*${n})`) : `${fieldC(type)} *${n}`));
1837
2451
  this.line(`if (${t} == NULL) TS_TRY(ts_alloc(${n}, (uint8_t **)&${t}));`);
1838
2452
  this.line(`ts_memcpy(${t}, &${lv}, ${n});`);
1839
2453
  return t;
@@ -1921,27 +2535,27 @@ export class CallEmitter extends ExpressionEmitter {
1921
2535
  this.fail(node, "returnData needs an explicit type: returnData<u64>(program)");
1922
2536
  if (node.arguments.length !== 1)
1923
2537
  this.fail(node, "returnData<T>(program) takes the program that returned it");
1924
- const program = this.accountParam(node.arguments[0], "returnData's program");
2538
+ const program = this.anyAccount(node.arguments[0], "returnData's program");
1925
2539
  const out = this.tmp("rd");
1926
2540
  if (t.kind === "pubkey") {
1927
2541
  this.line(`SolPubkey ${out};`);
1928
- this.line(`TS_TRY(ts_return_data(a_${program.name}, (uint8_t *)&${out}, 32));`);
2542
+ this.line(`TS_TRY(ts_return_data(${program}, (uint8_t *)&${out}, 32));`);
1929
2543
  return { c: `(&${out})`, type: t };
1930
2544
  }
1931
2545
  if (t.kind === "bool") {
1932
2546
  this.line(`uint8_t ${out};`);
1933
- this.line(`TS_TRY(ts_return_data(a_${program.name}, &${out}, 1));`);
2547
+ this.line(`TS_TRY(ts_return_data(${program}, &${out}, 1));`);
1934
2548
  this.line(`if (${out} > 1) TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: invalid bool return data");`);
1935
2549
  return { c: `(${out} == 1)`, type: BOOL };
1936
2550
  }
1937
2551
  if (t.kind === "enum") {
1938
2552
  this.line(`uint8_t ${out};`);
1939
- this.line(`TS_TRY(ts_return_data(a_${program.name}, &${out}, 1));`);
2553
+ this.line(`TS_TRY(ts_return_data(${program}, &${out}, 1));`);
1940
2554
  this.line(`if (${out} >= ${this.model.enums.get(t.name).variants.length}) TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: invalid enum return data");`);
1941
2555
  return { c: out, type: t };
1942
2556
  }
1943
2557
  this.line(`${INT_INFO[t.name].c} ${out};`);
1944
- this.line(`TS_TRY(ts_return_data(a_${program.name}, (uint8_t *)&${out}, ${INT_INFO[t.name].bytes}));`);
2558
+ this.line(`TS_TRY(ts_return_data(${program}, (uint8_t *)&${out}, ${INT_INFO[t.name].bytes}));`);
1945
2559
  return { c: out, type: t };
1946
2560
  }
1947
2561
  }