@typesol/cli 0.40.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 (57) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/README.md +9 -5
  3. package/dist/ai.d.ts +10 -0
  4. package/dist/ai.js +43 -0
  5. package/dist/cli.js +15 -1
  6. package/dist/compiler/analyze.js +44 -3
  7. package/dist/compiler/diagnostics.d.ts +2 -0
  8. package/dist/compiler/emit/base.d.ts +40 -7
  9. package/dist/compiler/emit/base.js +33 -0
  10. package/dist/compiler/emit/borsh.d.ts +7 -0
  11. package/dist/compiler/emit/borsh.js +86 -1
  12. package/dist/compiler/emit/calls.d.ts +102 -2
  13. package/dist/compiler/emit/calls.js +671 -50
  14. package/dist/compiler/emit/cpi-core.d.ts +9 -3
  15. package/dist/compiler/emit/cpi-core.js +12 -7
  16. package/dist/compiler/emit/cpi.js +8 -14
  17. package/dist/compiler/emit/create.d.ts +3 -3
  18. package/dist/compiler/emit/create.js +33 -25
  19. package/dist/compiler/emit/expressions.js +51 -2
  20. package/dist/compiler/emit/function.js +2 -2
  21. package/dist/compiler/emit/outline.d.ts +24 -0
  22. package/dist/compiler/emit/outline.js +100 -0
  23. package/dist/compiler/emit/program.js +7 -2
  24. package/dist/compiler/emit/shared.d.ts +35 -1
  25. package/dist/compiler/emit/shared.js +9 -1
  26. package/dist/compiler/emit/statements.d.ts +31 -0
  27. package/dist/compiler/emit/statements.js +272 -14
  28. package/dist/compiler/emit/storage.d.ts +27 -1
  29. package/dist/compiler/emit/storage.js +124 -11
  30. package/dist/compiler/emit/token.d.ts +11 -8
  31. package/dist/compiler/emit/token.js +233 -104
  32. package/dist/compiler/hints.js +6 -0
  33. package/dist/compiler/model.d.ts +20 -1
  34. package/dist/compiler/model.js +5 -0
  35. package/dist/testing-stake.d.ts +216 -0
  36. package/dist/testing-stake.js +526 -0
  37. package/dist/testing.d.ts +1 -0
  38. package/dist/testing.js +1 -0
  39. package/dist/tools/mcp.d.ts +11 -0
  40. package/dist/tools/mcp.js +208 -0
  41. package/dist/workspace.js +8 -0
  42. package/docs/ai.md +52 -0
  43. package/docs/architecture.md +1 -1
  44. package/docs/audit.md +16 -14
  45. package/docs/case-study-raydium-cp-swap.md +77 -41
  46. package/docs/case-study-spl-stake-pool.md +122 -0
  47. package/docs/errors.md +1 -1
  48. package/docs/language.md +107 -14
  49. package/docs/security-model.md +4 -0
  50. package/docs/stability.md +69 -0
  51. package/docs/test-your-program.md +47 -0
  52. package/docs/testing.md +19 -0
  53. package/lib/typesol.d.ts +241 -40
  54. package/llms-full.txt +1352 -0
  55. package/llms.txt +30 -0
  56. package/package.json +4 -2
  57. 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");
@@ -121,7 +127,14 @@ export class CallEmitter extends ExpressionEmitter {
121
127
  this.line(`sol_log_((const char *)${t}.ptr, ${t}.len);`);
122
128
  }
123
129
  else {
124
- const value = v.literal !== undefined ? this.expect(v, U64, args[0]) : v;
130
+ let value = v.literal !== undefined ? this.expect(v, U64, args[0]) : v;
131
+ // An Option TypeScript has narrowed to its value (after `x === null` was ruled out): log the value.
132
+ if (value.type.kind === "option") {
133
+ const t = this.checker.getTypeAtLocation(args[0]);
134
+ if (t.isUnion() && t.types.some((m) => m.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)))
135
+ this.fail(args[0], "log() takes a value, not an Option that may be null: check `x !== null` first, or log `${x}` (null prints as null)");
136
+ value = this.unwrap(value, args[0]);
137
+ }
125
138
  if (value.type.kind === "pubkey")
126
139
  this.line(`sol_log_pubkey(${value.c});`);
127
140
  else if (value.type.kind === "int") {
@@ -194,6 +207,15 @@ export class CallEmitter extends ExpressionEmitter {
194
207
  this.line(`TS_TRY(ts_epoch_schedule(${{ slotsPerEpoch: 0, epochWarmup: 2, firstNormalEpoch: 3, firstNormalSlot: 4 }[builtin]}, &${t}));`);
195
208
  return builtin === "epochWarmup" ? { c: `(${t} != 0)`, type: BOOL } : { c: t, type: U64 };
196
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
+ }
197
219
  case "currentSlot":
198
220
  case "currentEpoch":
199
221
  case "epochStartTimestamp":
@@ -676,7 +698,10 @@ export class CallEmitter extends ExpressionEmitter {
676
698
  case "loadRaw":
677
699
  case "loadRawMut":
678
700
  case "loadForeign":
701
+ case "loadBorsh":
679
702
  this.fail(node, `bind ${builtin}<T>(...) to a const first: const p = ${builtin}<T>(account)`);
703
+ case "storeBorsh":
704
+ return this.storeBorsh(node);
680
705
  case "emit":
681
706
  return this.emitEvent(node);
682
707
  case "emitCpi": {
@@ -695,6 +720,9 @@ export class CallEmitter extends ExpressionEmitter {
695
720
  }
696
721
  case "returnData":
697
722
  return this.returnData(node);
723
+ case "programAt":
724
+ case "sysvarAt":
725
+ return this.programAt(node, builtin);
698
726
  case "instructionData":
699
727
  this.fail(node, "bind the data to a local first: const data = instructionData()");
700
728
  case "fixedArray":
@@ -707,6 +735,8 @@ export class CallEmitter extends ExpressionEmitter {
707
735
  case "sighash":
708
736
  case "hex":
709
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");
710
740
  }
711
741
  if (builtin)
712
742
  this.fail(callee, `${builtin} cannot be called here`);
@@ -742,16 +772,23 @@ export class CallEmitter extends ExpressionEmitter {
742
772
  // xs.some(…) and friends on a Vec, FixedArray, FixedVec or Vec argument: a loop with the callback expanded in it.
743
773
  if (LIST_METHODS.has(method)) {
744
774
  const l = ts.isIdentifier(callee.expression) ? this.lookup(callee.expression.text) : undefined;
745
- 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))
746
781
  return this.listMethod(node, method);
747
782
  }
748
783
  // A map / filter chain is consumed by a list method, `.length` or for…of, or stored: const ys = xs.map(…).
749
784
  if (this.isPipeline(node))
750
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`);
751
- // Vec<T> instruction arguments are read-only views.
752
- if (ts.isIdentifier(callee.expression)) {
753
- const l = this.lookup(callee.expression.text);
754
- 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
+ {
755
792
  // Bytes (instruction data, a Vec<u8> argument): little-endian reads at a byte offset, bounds-checked (5104).
756
793
  const le = {
757
794
  readU8: ["uint8_t", 1, U8],
@@ -781,7 +818,7 @@ export class CallEmitter extends ExpressionEmitter {
781
818
  return { c: `(((const TS_Str *)${l.c}.ptr)[${idx}])`, type: STRING };
782
819
  }
783
820
  if (!isScalar(elem))
784
- 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`);
785
822
  const idx = this.index(args[0], `(uint64_t)${l.c}.len`);
786
823
  const t = this.tmp("el");
787
824
  this.line(`${scalarStorageC(elem)} ${t};`);
@@ -846,6 +883,9 @@ export class CallEmitter extends ExpressionEmitter {
846
883
  const right = this.expect(this.expr(args[0], left.type), left.type, args[0]);
847
884
  return { c: `ts_key_eq(${this.settle(left, mark).c}, ${right.c})`, type: BOOL };
848
885
  }
886
+ const at = this.programAtValue(callee.expression);
887
+ if (at)
888
+ return this.programAtMethod(node, at, method);
849
889
  if (this.accountAt(callee.expression)) {
850
890
  const target = this.accountAt(callee.expression);
851
891
  // Program accounts used through their methods (systemProgram.transfer, tokenProgram.*…) may be optional.
@@ -864,30 +904,19 @@ export class CallEmitter extends ExpressionEmitter {
864
904
  if (target?.kind.kind === "system" && method === "transfer")
865
905
  return this.systemTransfer(node);
866
906
  if (target?.kind.kind === "system" && method === "createAccount")
867
- return this.createAccount(node, target);
907
+ return this.createAccount(node, this.programParam(target));
868
908
  if (target?.kind.kind === "system" && method === "createPda")
869
909
  return this.createPda(node);
870
910
  if (target?.kind.kind === "system" && (method === "allocate" || method === "assign"))
871
- return this.allocateOrAssign(node, target, method);
911
+ return this.allocateOrAssign(node, this.programParam(target), method);
872
912
  if (target?.kind.kind === "tokenProgram")
873
- return this.tokenOp(node, target, method);
913
+ return this.tokenOp(node, this.programParam(target), method);
874
914
  if (target?.kind.kind === "ataProgram")
875
- return this.ataOp(node, target, method);
915
+ return this.ataOp(node, this.programParam(target), method);
876
916
  if (target?.kind.kind === "memoProgram")
877
- return this.memoOp(node, target, method);
878
- if (target?.kind.kind === "stakeHistory") {
879
- const fields = { has: 0, effective: 1, activating: 2, deactivating: 3 };
880
- if (!(method in fields))
881
- this.fail(callee.name, "StakeHistorySysvar has has(epoch), effective(epoch), activating(epoch) and deactivating(epoch)");
882
- if (args.length !== 1)
883
- this.fail(node, `${method}(epoch) takes the epoch`);
884
- const epoch = this.expect(this.expr(args[0], U64), U64, args[0]);
885
- const f = this.tmp("shf");
886
- const v = this.tmp("shv");
887
- this.line(`bool ${f};`);
888
- this.line(`uint64_t ${v} = ts_stake_history(a_${target.name}, ${epoch.c}, ${Math.max(1, fields[method])}, &${f});`);
889
- return method === "has" ? { c: f, type: BOOL } : { c: v, type: U64 };
890
- }
917
+ return this.memoOp(node, this.programParam(target), method);
918
+ if (target?.kind.kind === "stakeHistory")
919
+ return this.stakeHistoryRead(node, `a_${target.name}`, method);
891
920
  if (target?.kind.kind === "sbRandomness") {
892
921
  if (method !== "value" && method !== "valueU64")
893
922
  this.fail(callee.name, "SwitchboardRandomness has value() and valueU64()");
@@ -899,7 +928,7 @@ export class CallEmitter extends ExpressionEmitter {
899
928
  return method === "value" ? { c: `((const SolPubkey *)${t})`, type: HASH } : { c: `ts_read_le(${t}, 8)`, type: U64 };
900
929
  }
901
930
  if (target?.kind.kind === "stakeProgram")
902
- return this.stakeOp(node, target, method);
931
+ return this.stakeOp(node, this.programParam(target), method);
903
932
  if (target?.kind.kind === "metadataProgram")
904
933
  return this.metadataOp(node, target, method);
905
934
  // Each Metaplex CPI in its own C block: its data buffer's stack slot is reused by the next one.
@@ -977,6 +1006,11 @@ export class CallEmitter extends ExpressionEmitter {
977
1006
  this.fail(node, "only Vecs of Mut<...> / Init<...> accounts can grow or shrink");
978
1007
  this.line(`TS_TRY(ts_resize(params, ${payer}, a_${v.account.name}, 8 + ${info.fixed} + (${newLen}) * ${info.elemSize}, entry_${v.account.name}));`);
979
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
+ }
980
1014
  /**
981
1015
  * The growable Vecs stored after this one move by `by` bytes (+ grows, - shrinks): where they start and how many
982
1016
  * bytes they take, read before the resize; references into them cannot outlive this call.
@@ -993,6 +1027,23 @@ export class CallEmitter extends ExpressionEmitter {
993
1027
  return { at, n };
994
1028
  };
995
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
+ }
996
1047
  case "set": {
997
1048
  if (args.length !== 2)
998
1049
  this.fail(node, "set(index, value) takes two arguments");
@@ -1098,6 +1149,148 @@ export class CallEmitter extends ExpressionEmitter {
1098
1149
  }
1099
1150
  this.fail(node, `Vecs support get, set, push, pop, clear and .length, not ${method}()`);
1100
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
+ }
1101
1294
  /** sha256(...) / keccak256(...) over strings, Pubkeys, Hashes, integers (LE) and booleans. */
1102
1295
  hashCall(node, fn) {
1103
1296
  if (node.arguments.length === 0 || node.arguments.length > 16)
@@ -1330,9 +1523,155 @@ export class CallEmitter extends ExpressionEmitter {
1330
1523
  }
1331
1524
  this.fail(node, "a TransactionInstruction has programId, accountsLength, dataLength, accountKey/accountIsSigner/accountIsWritable(i), readU8/U16/U32/U64/readPubkey(offset) and is(program, name)");
1332
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
+ }
1333
1670
  handle(node) {
1334
1671
  if (ts.isParenthesizedExpression(node))
1335
1672
  return this.handle(node.expression);
1673
+ if (ts.isConditionalExpression(node) && this.looksLikeAccountHandle(node))
1674
+ return this.accountChoice(node).c;
1336
1675
  if (ts.isIdentifier(node)) {
1337
1676
  const l = this.lookup(node.text);
1338
1677
  return l?.type.kind === "account" ? l.c : undefined;
@@ -1358,6 +1697,125 @@ export class CallEmitter extends ExpressionEmitter {
1358
1697
  return h;
1359
1698
  return `a_${this.accountParam(node, what).name}`;
1360
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
+ }
1361
1819
  /** `readData<T>(account, offset)`: a bounds-checked little-endian read of any account's data. */
1362
1820
  readData(node) {
1363
1821
  const targ = node.typeArguments?.[0];
@@ -1445,7 +1903,7 @@ export class CallEmitter extends ExpressionEmitter {
1445
1903
  const fn = mut ? "loadRawMut" : "loadRaw";
1446
1904
  const targ = node.typeArguments?.[0];
1447
1905
  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)
1906
+ if (!s || s.size === undefined || (s.vec && !s.bigVec))
1449
1907
  this.fail(node, `${fn} needs a fixed-size struct type: ${fn}<MyStruct>(account)`);
1450
1908
  if (s.layout === "borsh")
1451
1909
  this.fail(node, `${s.name} is @layout borsh: ${fn} reads fixed layouts only`);
@@ -1457,8 +1915,8 @@ export class CallEmitter extends ExpressionEmitter {
1457
1915
  const acct = this.accountParam(node.arguments[0], "the account");
1458
1916
  if (acct.kind.kind !== "info")
1459
1917
  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`);
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)`);
1462
1920
  if (!this.ix)
1463
1921
  this.fail(node, `load ${acct.name} in the instruction and pass the struct on`);
1464
1922
  h = `a_${acct.name}`;
@@ -1466,7 +1924,20 @@ export class CallEmitter extends ExpressionEmitter {
1466
1924
  }
1467
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");`);
1468
1926
  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) {
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()) {
1470
1941
  this.line(`TS_TRY(ts_check_writable(${h}));`);
1471
1942
  const slot = this.claimSlots.get(node);
1472
1943
  if (slot)
@@ -1476,7 +1947,108 @@ export class CallEmitter extends ExpressionEmitter {
1476
1947
  else
1477
1948
  this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
1478
1949
  }
1479
- 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)})`;
1480
2052
  }
1481
2053
  /** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
1482
2054
  loadAccount(node, mut) {
@@ -1496,6 +2068,8 @@ export class CallEmitter extends ExpressionEmitter {
1496
2068
  this.fail(node, `${s.name}'s discriminator is shorter than 8 bytes: take it as Owner<Account<${s.name}>, "…">`);
1497
2069
  if (s.layout === "borsh")
1498
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`);
1499
2073
  if (node.arguments.length !== 1)
1500
2074
  this.fail(node, "loadAccount<T>(account) takes one remaining account or AccountInfo parameter");
1501
2075
  let h = this.handle(node.arguments[0]);
@@ -1766,6 +2340,14 @@ export class CallEmitter extends ExpressionEmitter {
1766
2340
  this.fail(n, `${h.name}() takes ${p.name} as Mut<${l.loaded.struct}>: load it with loadAccountMut`);
1767
2341
  return l.loaded.handle;
1768
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
+ }
1769
2351
  const acct = this.accountParam(n, `${h.name}()'s ${p.name}`);
1770
2352
  const why = accountMismatch(acct.kind, p.account);
1771
2353
  if (why)
@@ -1785,6 +2367,9 @@ export class CallEmitter extends ExpressionEmitter {
1785
2367
  case "structRef":
1786
2368
  case "arrayArg": {
1787
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;
1788
2373
  let r = this.ref(n);
1789
2374
  // A narrowed Option<Struct> / Option<FixedArray> place (`c.opt !== null` before it): its value.
1790
2375
  if (r && r.type.kind === "option" && sameType(r.type.inner, want))
@@ -1794,12 +2379,22 @@ export class CallEmitter extends ExpressionEmitter {
1794
2379
  return this.snapshotPlace(r.lv, want, h, n);
1795
2380
  }
1796
2381
  case "dataEnumArg": {
2382
+ const built = this.literalArg(n, { kind: "dataEnum", name: p.type.name });
2383
+ if (built)
2384
+ return built;
1797
2385
  const r = this.ref(n);
1798
2386
  if (!r || r.type.kind !== "dataEnum" || r.type.name !== p.type.name)
1799
2387
  this.fail(n, `expected a ${p.type.name}`);
1800
2388
  return this.snapshotPlace(r.lv, { kind: "dataEnum", name: p.type.name }, h, n);
1801
2389
  }
1802
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
+ }
1803
2398
  const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
1804
2399
  // An Option<Vec<T>> argument passes as its list once checked against null (TypeScript narrows it).
1805
2400
  const t = l?.type.kind === "vecArg" && l.type.optional ? { ...l.type, optional: undefined } : l?.type;
@@ -1811,6 +2406,33 @@ export class CallEmitter extends ExpressionEmitter {
1811
2406
  return this.expect(this.expr(n, p.type), p.type, n);
1812
2407
  }
1813
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
+ }
1814
2436
  /**
1815
2437
  * A struct/array/data-enum helper argument. Helpers that take accounts may change account data, so they get a
1816
2438
  * copy taken at the call (JS passes the object as it was); other helpers cannot write, so a pointer is enough.
@@ -1825,8 +2447,7 @@ export class CallEmitter extends ExpressionEmitter {
1825
2447
  const n = this.fieldBytes(type);
1826
2448
  // One buffer per call site, allocated on first use: a call in a loop must not take new heap every pass.
1827
2449
  const t = this.tmp("argc");
1828
- const decl = type.kind === "array" ? storageDecl(type, `(*${t})`) : `${fieldC(type)} *${t}`;
1829
- this.hoisted.push(` ${decl} = NULL;`);
2450
+ this.hoistLazy(t, (n) => (type.kind === "array" ? storageDecl(type, `(*${n})`) : `${fieldC(type)} *${n}`));
1830
2451
  this.line(`if (${t} == NULL) TS_TRY(ts_alloc(${n}, (uint8_t **)&${t}));`);
1831
2452
  this.line(`ts_memcpy(${t}, &${lv}, ${n});`);
1832
2453
  return t;
@@ -1914,27 +2535,27 @@ export class CallEmitter extends ExpressionEmitter {
1914
2535
  this.fail(node, "returnData needs an explicit type: returnData<u64>(program)");
1915
2536
  if (node.arguments.length !== 1)
1916
2537
  this.fail(node, "returnData<T>(program) takes the program that returned it");
1917
- const program = this.accountParam(node.arguments[0], "returnData's program");
2538
+ const program = this.anyAccount(node.arguments[0], "returnData's program");
1918
2539
  const out = this.tmp("rd");
1919
2540
  if (t.kind === "pubkey") {
1920
2541
  this.line(`SolPubkey ${out};`);
1921
- 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));`);
1922
2543
  return { c: `(&${out})`, type: t };
1923
2544
  }
1924
2545
  if (t.kind === "bool") {
1925
2546
  this.line(`uint8_t ${out};`);
1926
- this.line(`TS_TRY(ts_return_data(a_${program.name}, &${out}, 1));`);
2547
+ this.line(`TS_TRY(ts_return_data(${program}, &${out}, 1));`);
1927
2548
  this.line(`if (${out} > 1) TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: invalid bool return data");`);
1928
2549
  return { c: `(${out} == 1)`, type: BOOL };
1929
2550
  }
1930
2551
  if (t.kind === "enum") {
1931
2552
  this.line(`uint8_t ${out};`);
1932
- this.line(`TS_TRY(ts_return_data(a_${program.name}, &${out}, 1));`);
2553
+ this.line(`TS_TRY(ts_return_data(${program}, &${out}, 1));`);
1933
2554
  this.line(`if (${out} >= ${this.model.enums.get(t.name).variants.length}) TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: invalid enum return data");`);
1934
2555
  return { c: out, type: t };
1935
2556
  }
1936
2557
  this.line(`${INT_INFO[t.name].c} ${out};`);
1937
- 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}));`);
1938
2559
  return { c: out, type: t };
1939
2560
  }
1940
2561
  }