@typesol/cli 0.42.0 → 0.44.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 (78) hide show
  1. package/CHANGELOG.md +350 -0
  2. package/NOTICE +71 -0
  3. package/README.md +35 -18
  4. package/SECURITY.md +32 -5
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.js +5 -5
  7. package/dist/cli.js +196 -72
  8. package/dist/compiler/analyze.js +447 -12
  9. package/dist/compiler/diagnostics.d.ts +1 -0
  10. package/dist/compiler/diagnostics.js +13 -0
  11. package/dist/compiler/emit/alias.d.ts +45 -1
  12. package/dist/compiler/emit/alias.js +143 -6
  13. package/dist/compiler/emit/base.d.ts +28 -1
  14. package/dist/compiler/emit/base.js +77 -9
  15. package/dist/compiler/emit/borsh.js +11 -5
  16. package/dist/compiler/emit/calls.d.ts +80 -0
  17. package/dist/compiler/emit/calls.js +612 -54
  18. package/dist/compiler/emit/cpi-core.d.ts +23 -4
  19. package/dist/compiler/emit/cpi-core.js +261 -12
  20. package/dist/compiler/emit/cpi.js +8 -2
  21. package/dist/compiler/emit/create.js +3 -0
  22. package/dist/compiler/emit/expressions.js +44 -8
  23. package/dist/compiler/emit/function.js +10 -0
  24. package/dist/compiler/emit/program.js +30 -1
  25. package/dist/compiler/emit/rbtree.d.ts +7 -0
  26. package/dist/compiler/emit/rbtree.js +142 -0
  27. package/dist/compiler/emit/shared.d.ts +25 -0
  28. package/dist/compiler/emit/shared.js +45 -4
  29. package/dist/compiler/emit/statements.d.ts +27 -1
  30. package/dist/compiler/emit/statements.js +305 -23
  31. package/dist/compiler/emit/storage.d.ts +25 -2
  32. package/dist/compiler/emit/storage.js +116 -64
  33. package/dist/compiler/emit/token.js +2 -2
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/idl.js +2 -1
  37. package/dist/compiler/index.d.ts +15 -1
  38. package/dist/compiler/index.js +40 -3
  39. package/dist/compiler/model.d.ts +65 -4
  40. package/dist/compiler/model.js +14 -0
  41. package/dist/compiler/toolchain.d.ts +56 -1
  42. package/dist/compiler/toolchain.js +246 -12
  43. package/dist/testing-stake.d.ts +2 -1
  44. package/dist/testing-stake.js +2 -1
  45. package/dist/testing.js +6 -4
  46. package/dist/tools/clientgen.d.ts +15 -0
  47. package/dist/tools/clientgen.js +173 -7
  48. package/dist/tools/cpigen.d.ts +0 -15
  49. package/dist/tools/cpigen.js +19 -8
  50. package/dist/tools/doctor.d.ts +17 -2
  51. package/dist/tools/doctor.js +64 -4
  52. package/dist/tools/portgen.js +43 -18
  53. package/dist/workspace.d.ts +20 -0
  54. package/dist/workspace.js +173 -6
  55. package/docs/ai.md +10 -5
  56. package/docs/architecture.md +10 -3
  57. package/docs/audit.md +63 -17
  58. package/docs/case-study-escrow.md +1 -1
  59. package/docs/case-study-phoenix.md +226 -0
  60. package/docs/case-study-raydium-amm.md +3 -3
  61. package/docs/case-study-spl-stake-pool.md +5 -5
  62. package/docs/cli.md +17 -8
  63. package/docs/client.md +11 -3
  64. package/docs/errors.md +1 -1
  65. package/docs/language.md +148 -12
  66. package/docs/mainnet.md +21 -10
  67. package/docs/migrate-from-anchor.md +3 -1
  68. package/docs/runtime.md +12 -2
  69. package/docs/security-model.md +38 -6
  70. package/docs/stability.md +42 -4
  71. package/docs/testing.md +25 -0
  72. package/docs/troubleshooting.md +17 -2
  73. package/lib/typesol.d.ts +221 -4
  74. package/llms-full.txt +336 -65
  75. package/llms.txt +2 -2
  76. package/package.json +4 -2
  77. package/runtime/typesol_rt.h +429 -13
  78. package/test/programs/LICENSE-Apache-2.0.txt +201 -0
@@ -4,7 +4,7 @@ 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";
7
- import { U64, U32, U8, I64, I32, BOOL, PUBKEY, STRING, HASH, cBytes, cString, scalarC, scalarStorageC, optC, valueC, fieldC, storageDecl, accountMismatch, vecCount, emptySizeC, vecLenCheck, } from "./shared.js";
7
+ import { U64, U32, U8, I64, I32, BOOL, PUBKEY, STRING, HASH, cBytes, cString, scalarC, scalarStorageC, optC, valueC, fieldC, storageDecl, accountMismatch, vecCount, emptySizeC, vecLenCheck, passedByPointer, unreachableArg, } from "./shared.js";
8
8
  import { ExpressionEmitter } from "./expressions.js";
9
9
  /**
10
10
  * Calls: built-in functions, Vec methods, helpers, remaining accounts, foreign account reads and return data.
@@ -39,6 +39,8 @@ const PROGRAM_ERRORS = [
39
39
  "IncorrectAuthority",
40
40
  ];
41
41
  const LIST_METHODS = new Set(["forEach", "some", "every", "find", "findIndex", "reduce", "includes", "indexOf"]);
42
+ /** The byte builders of a FixedVec<u8, N> (byteListMethod). */
43
+ const BYTE_METHODS = new Set(["pushLE", "pushKey", "pushBorsh", "setLE", "truncate"]);
42
44
  export class CallEmitter extends ExpressionEmitter {
43
45
  call(node, topLevel) {
44
46
  const callee = node.expression;
@@ -67,7 +69,10 @@ export class CallEmitter extends ExpressionEmitter {
67
69
  if (v.type.kind === "string")
68
70
  this.fail(args[1], "require's error is a string literal, a member of an error enum (CounterError.X) or a u32 code; a template string or string variable is not: give the message to an error enum member");
69
71
  const code = v.literal !== undefined ? this.literal(v.literal, U32, args[1]) : this.expect(v, U32, args[1]);
70
- this.line(`if (!${cond.c}) return ts_fail_code(${code.c}, ${cString(`Error: the code returned (${this.location(node)})`)});`);
72
+ if (this.quietErrors())
73
+ this.line(`if (!${cond.c}) return ts_fail_code_quiet(${code.c});`);
74
+ else
75
+ this.line(`if (!${cond.c}) return ts_fail_code(${code.c}, ${cString(`Error: the code returned (${this.location(node)})`)});`);
71
76
  return undefined;
72
77
  }
73
78
  // A built-in ProgramError: its u64 form (the index shifted into the high 32 bits), as solana_program returns it.
@@ -79,9 +84,13 @@ export class CallEmitter extends ExpressionEmitter {
79
84
  }
80
85
  const err = this.errorRef(args[1]);
81
86
  // `const ERROR_LOG_PREFIX = "AMM error: "`: the program's errors log as its native entrypoint logs them.
87
+ // `const ERROR_LOG_PREFIX = null`: nothing logged, only the code returned.
82
88
  const prefix = this.model.constants.get("ERROR_LOG_PREFIX")?.value;
83
89
  const text = typeof prefix === "string" ? `${prefix}${err.msg}` : `Error ${err.code} ${err.name}: ${err.msg} (${this.location(node)})`;
84
- this.line(`if (!${cond.c}) TS_FAIL(${err.code}, ${cString(text)});`);
90
+ if (prefix === null)
91
+ this.line(`if (!${cond.c}) return ts_fail_quiet(${err.code});`);
92
+ else
93
+ this.line(`if (!${cond.c}) TS_FAIL(${err.code}, ${cString(text)});`);
85
94
  return undefined;
86
95
  }
87
96
  case "panic": {
@@ -97,17 +106,47 @@ export class CallEmitter extends ExpressionEmitter {
97
106
  if (args.length > 2 || args.some((a, i) => !(i === 0 && silent) && text(a) === undefined))
98
107
  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
108
  const msg = silent ? undefined : args.length ? text(args[0]) : "explicit panic";
100
- // The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"): the given one, as a
101
- // ported program's panic reports it, else this source line.
102
- const at = args.length > 1 ? text(args[1]) : this.location(node);
103
- const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(at);
104
- const [file, line, col] = m ? [m[1], m[2], m[3] ?? "0"] : [at, "0", "0"];
105
- if (msg !== undefined)
106
- this.line(`sol_log(${cString(msg)});`);
107
- this.line(`sol_panic_(${cString(file)}, ${Buffer.byteLength(file)}, ${line}, ${col});`);
108
- this.line(`__builtin_unreachable();`);
109
+ if (silent && this.panicStyle())
110
+ this.fail(args[0], 'under PANIC_STYLE "solana-1.14" a panic logs its message, as solana_program 1.14\'s panic handler always does: pass the message');
111
+ // The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"), or the panic line
112
+ // logs: the given one, as a ported program's panic reports it, else this source line (with its column under
113
+ // PANIC_STYLE, as Rust always gives one).
114
+ const at = args.length > 1 ? text(args[1]) : this.panicStyle() ? this.locationWithColumn(node) : this.location(node);
115
+ for (const l of this.panicC(msg, at))
116
+ this.line(l);
109
117
  return undefined;
110
118
  }
119
+ case "panicsAt": {
120
+ // The checked arithmetic of `expression` panics as Rust's does at `location`, with Rust's messages.
121
+ const first = args[0];
122
+ const loc = first && (ts.isStringLiteralLike(first) ? first.text : ts.isIdentifier(first) ? this.model.constants.get(first.text)?.value : undefined);
123
+ if (args.length !== 2 || typeof loc !== "string" || !/^.+:\d+:\d+$/.test(loc))
124
+ this.fail(node, 'panicsAt(location, expression) takes a "file:line:column" string literal (or string constant) and the expression whose arithmetic panics there');
125
+ // Prettier writes an assignment argument in parentheses: `panicsAt(loc, (total += fee))`.
126
+ let inner = args[1];
127
+ while (ts.isParenthesizedExpression(inner))
128
+ inner = inner.expression;
129
+ const outer = this.panicAt;
130
+ this.panicAt = loc;
131
+ try {
132
+ // A statement: an assignment, a compound assignment (`total += fee`) or ++ / --.
133
+ const assigns = (ts.isBinaryExpression(inner) &&
134
+ inner.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
135
+ inner.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
136
+ ((ts.isPrefixUnaryExpression(inner) || ts.isPostfixUnaryExpression(inner)) &&
137
+ (inner.operator === ts.SyntaxKind.PlusPlusToken || inner.operator === ts.SyntaxKind.MinusMinusToken));
138
+ if (assigns) {
139
+ if (!ts.isExpressionStatement(node.parent))
140
+ this.fail(inner, "an assignment inside panicsAt is a statement of its own: panicsAt(location, total += fee);");
141
+ this.expressionStatement(inner, topLevel);
142
+ return undefined;
143
+ }
144
+ return this.expr(inner);
145
+ }
146
+ finally {
147
+ this.panicAt = outer;
148
+ }
149
+ }
111
150
  case "abort": {
112
151
  // Rust's abort on SBF: the runtime's `abort` syscall ("SBF program panicked", no location, nothing logged).
113
152
  if (args.length)
@@ -180,7 +219,14 @@ export class CallEmitter extends ExpressionEmitter {
180
219
  const d = this.accountParam(args[1], "close's destination");
181
220
  if (!isWritable(d.kind))
182
221
  this.fail(args[1], "the destination must be writable (Mut<...>)");
222
+ // In a helper both may be one account the caller passed twice (Dup<…>): closing into itself is refused.
223
+ if (a.index === -1 || d.index === -1)
224
+ this.line(`if (a_${a.name} == a_${d.name}) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: close's destination is the account itself");`);
225
+ else if (a === d)
226
+ this.fail(args[1], "the destination is the account being closed; name another writable account");
227
+ this.assertNotUsedAfterClose(a, node);
183
228
  this.line(`TS_TRY(ts_close(a_${a.name}, a_${d.name}));`);
229
+ this.forgetOwners();
184
230
  return undefined;
185
231
  }
186
232
  case "minimumBalance": {
@@ -332,7 +378,9 @@ export class CallEmitter extends ExpressionEmitter {
332
378
  if (a.type.kind !== "int" || !sameType(a.type, b.type))
333
379
  this.fail(node, `${builtin}(a, b) takes two integers of the same type`);
334
380
  const t = this.tmp("mm");
335
- this.line(`${INT_INFO[a.type.name].c} ${t} = (${a.c} ${builtin === "min" ? "<" : ">"} ${b.c}) ? ${a.c} : ${b.c};`);
381
+ // A u256 is four limbs, compared by the runtime.
382
+ const less = a.type.name === "u256" ? `ts_u256_cmp(${a.c}, ${b.c}) ${builtin === "min" ? "<" : ">"} 0` : `${a.c} ${builtin === "min" ? "<" : ">"} ${b.c}`;
383
+ this.line(`${INT_INFO[a.type.name].c} ${t} = (${less}) ? ${a.c} : ${b.c};`);
336
384
  return { c: t, type: a.type };
337
385
  }
338
386
  case "realloc": {
@@ -630,6 +678,8 @@ export class CallEmitter extends ExpressionEmitter {
630
678
  this.line(`ts_log_base64(${cString(prefix)}, ${Buffer.byteLength(prefix)}, (const uint8_t *)${place.ptr}, sizeof(TSS_${sd.name}));`);
631
679
  return undefined;
632
680
  }
681
+ case "findProgramAddressWithBump":
682
+ this.fail(node, "bind both results where it is called: const [address, bump] = findProgramAddressWithBump(seeds, program)");
633
683
  case "findProgramAddress": {
634
684
  // Pubkey::find_program_address(seeds, program).0: the canonical PDA of any program.
635
685
  if (args.length !== 2)
@@ -682,15 +732,59 @@ export class CallEmitter extends ExpressionEmitter {
682
732
  case "resizeAccount": {
683
733
  if (args.length !== 2)
684
734
  this.fail(node, "resizeAccount(account, newSize) takes the account and its new size");
735
+ this.assertNoViewAfter(this.viewAccountKey(args[0]), node, "resizeAccount()");
736
+ // A remaining account (or a helper's RemainingAccount): its size when the instruction started is the one the
737
+ // entrypoint recorded in the record's padding, as solana_program 1.14's entrypoint records it for realloc.
738
+ const h = this.handle(args[0]);
739
+ if (h) {
740
+ if (!this.nativeAccountWrites())
741
+ this.line(`TS_TRY(ts_check_writable(${h}));`);
742
+ const size = this.expect(this.expr(args[1], U64), U64, args[1]);
743
+ this.line(`TS_TRY(ts_resize_raw(${h}, ${size.c}, ts_entry_len(${h})));`);
744
+ return undefined;
745
+ }
685
746
  if (!this.ix)
686
- this.fail(node, "resizeAccount() is only available in instructions");
747
+ this.fail(node, "resizeAccount() is only available in instructions (or on a remaining account a helper was given)");
687
748
  const acct = this.accountParam(args[0], "resizeAccount's account");
688
- if (acct.kind.kind !== "info" || !isWritable(acct.kind))
689
- this.fail(args[0], "resizeAccount needs a Mut<AccountInfo> parameter");
749
+ if (acct.kind.kind !== "info" || (!isWritable(acct.kind) && !this.nativeAccountWrites()))
750
+ this.fail(args[0], "resizeAccount needs a Mut<AccountInfo> parameter or a remaining account");
690
751
  const size = this.expect(this.expr(args[1], U64), U64, args[1]);
691
752
  this.line(`TS_TRY(ts_resize_raw(a_${acct.name}, ${size.c}, entry_${acct.name}));`);
692
753
  return undefined;
693
754
  }
755
+ case "closeRaw": {
756
+ // Phoenix's Tombstone, in its order: receiver.lamports = receiver.lamports + account.lamports;
757
+ // account.lamports = 0; account.assign(&system_program::id()); account.realloc(0, false). The data is not
758
+ // zeroed (realloc's zero_init is false): the runtime drops it with the length, and then accepts the new owner.
759
+ if (args.length !== 2)
760
+ this.fail(node, "closeRaw(account, receiver) takes the account to close and the account that gets its lamports");
761
+ this.assertNoViewAfter(this.viewAccountKey(args[0]), node, "closeRaw()");
762
+ const a = this.inPlaceAccount(args[0], "closeRaw's account", true);
763
+ const r = this.inPlaceAccount(args[1], "closeRaw's receiver", false);
764
+ // Closing an account into itself would burn its lamports (the runtime then refuses the instruction).
765
+ if (!this.nativeAccountWrites())
766
+ this.line(`if (${a} == ${r}) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: closeRaw's receiver is the account itself");`);
767
+ const sum = this.tmp("sum");
768
+ this.line(`uint64_t ${sum};`);
769
+ this.line(`if (ts_add_overflow_u64(${r}->lamports, ${a}->lamports, &${sum})) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow");`);
770
+ this.line(`${r}->lamports = ${sum};`);
771
+ this.line(`${a}->lamports = 0;`);
772
+ this.line(`ts_memcpy(&${a}->owner, &TS_SYSTEM_PROGRAM_ID, 32);`);
773
+ this.forgetOwners();
774
+ this.line(`${a}->data_len = 0;`);
775
+ return undefined;
776
+ }
777
+ case "assignOwner": {
778
+ // AccountInfo::assign: the owner field written in place; the runtime accepts it at the end of the instruction
779
+ // (or at a CPI) only for an account of this program that is writable and whose data is empty or zeroed.
780
+ if (args.length !== 2)
781
+ this.fail(node, "assignOwner(account, owner) takes the account and its new owner's address");
782
+ const a = this.inPlaceAccount(args[0], "assignOwner's account", true);
783
+ const owner = this.expect(this.expr(args[1], PUBKEY), PUBKEY, args[1]);
784
+ this.line(`ts_memcpy(&${a}->owner, ${owner.c}, 32);`);
785
+ this.forgetOwners();
786
+ return undefined;
787
+ }
694
788
  case "bigEndian":
695
789
  this.fail(node, "bigEndian(value) is a PDA seed: use it inside a seeds list");
696
790
  case "loadAccount":
@@ -700,6 +794,13 @@ export class CallEmitter extends ExpressionEmitter {
700
794
  case "loadForeign":
701
795
  case "loadBorsh":
702
796
  this.fail(node, `bind ${builtin}<T>(...) to a const first: const p = ${builtin}<T>(account)`);
797
+ case "loadRawAt":
798
+ case "loadRawMutAt":
799
+ case "rawArrayAt":
800
+ case "rawArrayMutAt":
801
+ case "rbTreeAt":
802
+ case "rbTreeMutAt":
803
+ this.fail(node, `bind ${builtin}(…) to a const first: const v = ${builtin}<…>(account, offset${builtin.startsWith("load") ? "" : ", capacity"})`);
703
804
  case "storeBorsh":
704
805
  return this.storeBorsh(node);
705
806
  case "emit":
@@ -720,6 +821,26 @@ export class CallEmitter extends ExpressionEmitter {
720
821
  }
721
822
  case "returnData":
722
823
  return this.returnData(node);
824
+ case "setReturnData": {
825
+ // Rust's set_return_data(&bytes): the bytes as they are. More than 1024 is left to the syscall, which refuses
826
+ // it exactly as it refuses the original's call.
827
+ if (args.length !== 1)
828
+ this.fail(node, "setReturnData(bytes) takes one list of u8");
829
+ if (this.ix?.returns)
830
+ this.fail(node, `${this.ix.name} returns a value, which is its return data: return it instead of calling setReturnData (or declare the instruction void)`);
831
+ const what = "setReturnData takes a list of u8: a local FixedVec<u8, N>, a Vec or FixedVec in account data, or the instruction data or a slice of it";
832
+ const s = this.listSpan(args[0]) ?? this.fail(args[0], what);
833
+ if (s.elem.kind !== "int" || s.elem.name !== "u8")
834
+ this.fail(args[0], what);
835
+ this.line(`sol_set_return_data((const uint8_t *)${s.items}, ${s.count});`);
836
+ return undefined;
837
+ }
838
+ case "logComputeUnits": {
839
+ if (args.length)
840
+ this.fail(node, "logComputeUnits() takes no arguments");
841
+ this.line(`sol_log_compute_units();`);
842
+ return undefined;
843
+ }
723
844
  case "programAt":
724
845
  case "sysvarAt":
725
846
  return this.programAt(node, builtin);
@@ -766,6 +887,10 @@ export class CallEmitter extends ExpressionEmitter {
766
887
  return this.callHelper(node, helper);
767
888
  if (ts.isPropertyAccessExpression(callee)) {
768
889
  const method = callee.name.text;
890
+ // A RedBlackTree's methods (rbTreeAt / rbTreeMutAt).
891
+ const onTree = this.treeCall(node);
892
+ if (onTree)
893
+ return onTree.value;
769
894
  const introspected = this.instructionsCall(node, callee, method);
770
895
  if (introspected)
771
896
  return introspected;
@@ -1006,6 +1131,8 @@ export class CallEmitter extends ExpressionEmitter {
1006
1131
  this.fail(node, "only Vecs of Mut<...> / Init<...> accounts can grow or shrink");
1007
1132
  this.line(`TS_TRY(ts_resize(params, ${payer}, a_${v.account.name}, 8 + ${info.fixed} + (${newLen}) * ${info.elemSize}, entry_${v.account.name}));`);
1008
1133
  };
1134
+ if (BYTE_METHODS.has(method))
1135
+ return this.byteListMethod(node, method, v);
1009
1136
  if (info.big !== undefined) {
1010
1137
  const done = this.bigVecMethod(node, method, v, { stageElem, needWritable, elemPaths });
1011
1138
  if (done)
@@ -1159,6 +1286,8 @@ export class CallEmitter extends ExpressionEmitter {
1159
1286
  const vt = v.type;
1160
1287
  if (method === "set")
1161
1288
  return undefined;
1289
+ if (info.raw)
1290
+ this.fail(node, `a RawArray has get, set, .length, for … of and the list methods (its length is the capacity it was made with), not ${method}()`);
1162
1291
  if (method === "slice")
1163
1292
  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
1293
  if (info.slice)
@@ -1754,7 +1883,7 @@ export class CallEmitter extends ExpressionEmitter {
1754
1883
  const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
1755
1884
  const text = typeof pre === "string" ? `${pre}${PROGRAM_ERRORS[err]}` : `TypeSOL: not ${what}`;
1756
1885
  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)});`);
1886
+ this.line(`if (${bad}) ${this.programFail(`((uint64_t)${err + 2}) << 32`, text)};`);
1758
1887
  if (kind.kind === "stakeHistory")
1759
1888
  this.line(`if (${h}->data_len < 8) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: not the StakeHistory sysvar's data");`);
1760
1889
  return { c: h, type: { kind: "account", program: kind } };
@@ -1909,20 +2038,8 @@ export class CallEmitter extends ExpressionEmitter {
1909
2038
  this.fail(node, `${s.name} is @layout borsh: ${fn} reads fixed layouts only`);
1910
2039
  if (node.arguments.length !== 1)
1911
2040
  this.fail(node, `${fn}<T>(account) takes one remaining account or AccountInfo parameter`);
1912
- let h = this.handle(node.arguments[0]);
1913
- let param;
1914
- if (!h) {
1915
- const acct = this.accountParam(node.arguments[0], "the account");
1916
- if (acct.kind.kind !== "info")
1917
- this.fail(node.arguments[0], "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter");
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)`);
1920
- if (!this.ix)
1921
- this.fail(node, `load ${acct.name} in the instruction and pass the struct on`);
1922
- h = `a_${acct.name}`;
1923
- param = this.ix.accounts.indexOf(acct);
1924
- }
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");`);
2041
+ const { h, param } = this.rawAccount(node, fn, mut);
2042
+ this.line(this.viewOwnerCheck(h));
1926
2043
  this.line(`if (${h}->data_len < sizeof(TSS_${s.name})) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account data too small");`);
1927
2044
  // A BigVec's stored length must fit in the account. Its capacity is kept in a local: every access is clamped to it
1928
2045
  // (the length may be written again after this), without a division each time.
@@ -1934,21 +2051,56 @@ export class CallEmitter extends ExpressionEmitter {
1934
2051
  // Named in scope, so a loop moved into a function of its own is given it (see outlinedLoop).
1935
2052
  this.scopes.at(-1).set(`__${bigCap}`, { c: bigCap, type: U64, mutable: false });
1936
2053
  }
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()) {
1941
- this.line(`TS_TRY(ts_check_writable(${h}));`);
1942
- const slot = this.claimSlots.get(node);
1943
- if (slot)
1944
- this.line(param === undefined
1945
- ? `TS_TRY(ts_claim_mut_rec(params, ${h}, &${slot}, params->ka_num));`
1946
- : `TS_TRY(ts_claim_mut_at_rec(params, ${param}, &${slot}));`);
1947
- else
1948
- this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
1949
- }
2054
+ if (mut)
2055
+ this.claimRawMut(node, h, param);
1950
2056
  return { c: `((TSS_${s.name} *)(${h}->data))`, type: { kind: "structRef", struct: s.name, writable: mut }, ...(bigCap ? { bigCap } : {}) };
1951
2057
  }
2058
+ /**
2059
+ * A native account view's owner check (3007). In a program that makes such views the check goes through ts_owned: the
2060
+ * last account found this program's passes with a pointer compare until a CPI or an owner write forgets it.
2061
+ */
2062
+ viewOwnerCheck(h) {
2063
+ const fail = `TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program")`;
2064
+ return this.model.ownerCache ? `if (!ts_owned(params, ${h})) ${fail};` : `if (!ts_key_eq(&${h}->owner, params->program_id)) ${fail};`;
2065
+ }
2066
+ /** An owner write or a CPI: the owner checks' cache (viewOwnerCheck) is forgotten. */
2067
+ forgetOwners() {
2068
+ if (this.model.ownerCache)
2069
+ this.line(`TS_OWNER_FORGET(params);`);
2070
+ }
2071
+ /**
2072
+ * The account a loadRaw-style view reads (its first argument): a remaining account, or an AccountInfo parameter of
2073
+ * the instruction (`param`: its position, for the claim). `fn` names the call in messages.
2074
+ */
2075
+ rawAccount(node, fn, mut) {
2076
+ const h = this.handle(node.arguments[0]);
2077
+ if (h)
2078
+ return { h };
2079
+ const acct = this.accountParam(node.arguments[0], "the account");
2080
+ if (acct.kind.kind !== "info")
2081
+ this.fail(node.arguments[0], "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter");
2082
+ if (mut && !isWritable(acct.kind) && !this.nativeAccountWrites())
2083
+ this.fail(node.arguments[0], `${acct.name} must be Mut<AccountInfo> to load it with ${fn} (or declare const NATIVE_ACCOUNT_WRITES = true to leave writability to the runtime, as a native program does)`);
2084
+ if (!this.ix)
2085
+ this.fail(node, `load ${acct.name} in the instruction and pass the struct on`);
2086
+ return { h: `a_${acct.name}`, param: this.ix.accounts.indexOf(acct) };
2087
+ }
2088
+ /**
2089
+ * A writable view's checks: the account is writable and loaded mutably once in the instruction (2040).
2090
+ * NATIVE_ACCOUNT_WRITES: no writability check and no claim. The view writes in place; the runtime refuses the
2091
+ * instruction if a read-only account's data changed, and two views of one account share its bytes (the loader
2092
+ * gives a duplicate the same record), as two AccountInfos of one account share one buffer in Rust.
2093
+ */
2094
+ claimRawMut(node, h, param) {
2095
+ if (this.nativeAccountWrites())
2096
+ return;
2097
+ this.line(`TS_TRY(ts_check_writable(${h}));`);
2098
+ const slot = this.claimSlots.get(node);
2099
+ if (slot)
2100
+ this.line(param === undefined ? `TS_TRY(ts_claim_mut_rec(params, ${h}, &${slot}, params->ka_num));` : `TS_TRY(ts_claim_mut_at_rec(params, ${param}, &${slot}));`);
2101
+ else
2102
+ this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
2103
+ }
1952
2104
  /**
1953
2105
  * `const v = loadBorsh<T>(acct)`: the account's data from byte 0 decoded as Borsh into a local `T` (a copy), as
1954
2106
  * `try_from_slice_unchecked` reads it: no owner check, no discriminator, trailing bytes ignored; bytes that are not
@@ -2042,13 +2194,50 @@ export class CallEmitter extends ExpressionEmitter {
2042
2194
  this.line(`TS_TRY(ts_check_unaliased(params, a_${acct.name}));`);
2043
2195
  return `a_${acct.name}`;
2044
2196
  }
2197
+ /**
2198
+ * An account `closeRaw` / `assignOwner` writes in place: a remaining account (a helper's RemainingAccount, a ternary
2199
+ * between them) or an AccountInfo parameter. Without NATIVE_ACCOUNT_WRITES it is checked as the other writes to
2200
+ * accounts the compiler cannot see are: writable (3006; a parameter must be Mut<AccountInfo>), passed once (2040), and
2201
+ * for `owned` this program's (3007). With the flag nothing is checked: the runtime judges the result, as it judges a
2202
+ * native program's.
2203
+ */
2204
+ inPlaceAccount(node, what, owned) {
2205
+ const native = this.nativeAccountWrites();
2206
+ let h = this.handle(node);
2207
+ if (!h) {
2208
+ const acct = this.accountParam(node, what);
2209
+ if (acct.kind.kind !== "info")
2210
+ this.fail(node, `${what} is a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter`);
2211
+ if (!isWritable(acct.kind) && !native)
2212
+ this.fail(node, `${acct.name} must be Mut<AccountInfo> to change it in place (or declare const NATIVE_ACCOUNT_WRITES = true to leave writability to the runtime, as a native program does)`);
2213
+ h = `a_${acct.name}`;
2214
+ }
2215
+ else if (!native)
2216
+ this.line(`TS_TRY(ts_check_writable(${h}));`);
2217
+ if (native)
2218
+ return h;
2219
+ this.line(`TS_TRY(ts_check_unaliased(params, ${h}));`);
2220
+ if (owned)
2221
+ this.line(`if (!ts_key_eq(&${h}->owner, params->program_id)) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program");`);
2222
+ return h;
2223
+ }
2045
2224
  /** `TS_FAIL` with a built-in ProgramError (no custom code), logged as `require(…, ProgramError.X)` logs it. */
2046
2225
  programErrorFail(name, node) {
2047
2226
  const idx = PROGRAM_ERRORS.indexOf(name);
2048
2227
  // `const PROGRAM_ERROR_LOG_PREFIX = "Program error: "`: the log line a native entrypoint writes for it.
2049
2228
  const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
2050
2229
  const text = typeof pre === "string" ? `${pre}${name}` : `Error: ${name} (${this.location(node)})`;
2051
- return `TS_FAIL(((uint64_t)${idx + 2}) << 32, ${cString(text)})`;
2230
+ return this.programFail(`((uint64_t)${idx + 2}) << 32`, text);
2231
+ }
2232
+ /** A failure with a built-in ProgramError's code: logged with `text`, or nothing under `PROGRAM_ERROR_LOG_PREFIX = null`. */
2233
+ programFail(code, text) {
2234
+ if (this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value === null)
2235
+ return `return ts_fail_quiet(${code})`;
2236
+ return `TS_FAIL(${code}, ${cString(text)})`;
2237
+ }
2238
+ /** `const ERROR_LOG_PREFIX = null`: the program's own errors (and codes returned by its helpers) log nothing. */
2239
+ quietErrors() {
2240
+ return this.model.constants.get("ERROR_LOG_PREFIX")?.value === null;
2052
2241
  }
2053
2242
  /** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
2054
2243
  loadAccount(node, mut) {
@@ -2165,6 +2354,80 @@ export class CallEmitter extends ExpressionEmitter {
2165
2354
  visit(body);
2166
2355
  return found;
2167
2356
  }
2357
+ /**
2358
+ * After close(acct, dest) the account holds no data and belongs to the System Program: reading or writing it later in
2359
+ * the function (or on a later turn of a loop around the close) would read zeros or write bytes that are dropped. The
2360
+ * same holds for a reference into it read later. Refused, like a view used after closeRaw (assertNoViewAfter).
2361
+ */
2362
+ assertNotUsedAfterClose(a, at) {
2363
+ let fn = at.parent;
2364
+ while (fn && !ts.isFunctionLike(fn))
2365
+ fn = fn.parent;
2366
+ const body = fn && fn.body;
2367
+ if (!body)
2368
+ return;
2369
+ const loops = [];
2370
+ for (let n = at.parent; n && n !== fn; n = n.parent)
2371
+ if (ts.isForStatement(n) || ts.isForOfStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n))
2372
+ loops.push(n);
2373
+ const later = (n) => n.pos >= at.end || loops.some((l) => n.pos >= l.pos && n.end <= l.end && !(n.pos >= at.pos && n.end <= at.end));
2374
+ let hit;
2375
+ const visit = (n) => {
2376
+ if (hit)
2377
+ return;
2378
+ // Its address stays what it was: `acct.key` after the close is fine.
2379
+ if (ts.isPropertyAccessExpression(n) && n.name.text === "key" && this.probe(() => this.accountAt(n.expression)) === a)
2380
+ return;
2381
+ // A name or group field naming the account (not a property name: `x.vault`'s `vault` is not `vault`).
2382
+ const named = ts.isPropertyAccessExpression(n) ||
2383
+ (ts.isIdentifier(n) && !(ts.isPropertyAccessExpression(n.parent) && n.parent.name === n) && !ts.isPropertyAssignment(n.parent));
2384
+ if (named && later(n) && this.probe(() => this.accountAt(n)) === a)
2385
+ hit = n;
2386
+ if (!hit)
2387
+ ts.forEachChild(n, visit);
2388
+ };
2389
+ visit(body);
2390
+ if (!hit)
2391
+ for (const scope of this.scopes)
2392
+ for (const l of scope.values())
2393
+ if (l.decl && l.paths?.some((p) => p === a.name || p.startsWith(`${a.name}.`) || p.startsWith(`${a.name}[]`)) && this.usedAfter(l.decl, at))
2394
+ hit = l.decl;
2395
+ if (hit)
2396
+ this.fail(hit, `${a.name} is closed by close(${a.name}, …) and used after it: a closed account has no data (writes to it are dropped, reads see zeros). Do everything with ${a.name} before closing it (its key stays readable)`);
2397
+ }
2398
+ /** Whether a helper's body (or a helper it calls) closes or resizes an account: closeRaw / resizeAccount. */
2399
+ helperResizes(body) {
2400
+ return this.helperCalls(body, ["closeRaw", "resizeAccount"]);
2401
+ }
2402
+ /** Whether a helper's body (or a helper it calls) makes a writable tree view, which may change a tree's structure. */
2403
+ helperMakesMutTree(body) {
2404
+ return this.helperCalls(body, ["rbTreeMutAt"]);
2405
+ }
2406
+ /** Whether a helper's body (or a helper it calls) calls one of these built-ins. */
2407
+ helperCalls(body, builtins, seen = new Set()) {
2408
+ if (seen.has(body))
2409
+ return false;
2410
+ seen.add(body);
2411
+ let found = false;
2412
+ const visit = (n) => {
2413
+ if (found)
2414
+ return;
2415
+ if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) {
2416
+ const fn = this.exportName(n.expression);
2417
+ if (fn && builtins.includes(fn))
2418
+ found = true;
2419
+ else {
2420
+ const name = calleeName(n.expression, this.model.helperDecls, this.checker);
2421
+ const callee = name ? (this.model.generics.get(name)?.node ?? this.model.helpers.get(name)?.node) : undefined;
2422
+ if (callee && this.helperCalls(callee, builtins, seen))
2423
+ found = true;
2424
+ }
2425
+ }
2426
+ ts.forEachChild(n, visit);
2427
+ };
2428
+ visit(body);
2429
+ return found;
2430
+ }
2168
2431
  /**
2169
2432
  * A helper given a closure (a function that reads the caller's variables) for a function parameter: a closure only
2170
2433
  * runs where it is declared, so the helper is expanded here, like a closure, with the closure bound to the
@@ -2174,6 +2437,9 @@ export class CallEmitter extends ExpressionEmitter {
2174
2437
  const g = this.givenClosure(node);
2175
2438
  if (!g)
2176
2439
  return undefined;
2440
+ const tagged = [g.node, ...(ts.isVariableDeclaration(g.node.parent) ? [g.node.parent] : [])];
2441
+ if (tagged.some((n) => ts.getJSDocTags(n).some((t) => t.tagName.text === "noinline")))
2442
+ this.fail(node, `${g.display}() is @noinline, but given a closure it is expanded where it is called: pass a named function`);
2177
2443
  // Type parameters: bound from the call (as an instance would be) while the body is expanded.
2178
2444
  const saved = this.scope;
2179
2445
  if (g.typeParams.length) {
@@ -2286,6 +2552,14 @@ export class CallEmitter extends ExpressionEmitter {
2286
2552
  // A helper that takes accounts may change account data, so account text it gets is copied first.
2287
2553
  // A RemainingAccount(s) parameter counts: the helper may load and write a struct through it.
2288
2554
  const takesAccounts = h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining");
2555
+ // What a helper can write: account data (through its accounts) and the caller's places it takes as Inout<T>.
2556
+ const mayWrite = takesAccounts || h.params.some((p) => p.inout);
2557
+ // A helper that closes or resizes an account it is given ends the caller's views of it (any account it may be).
2558
+ if (takesAccounts && this.helperResizes(h.node))
2559
+ this.assertNoViewAfter("?", node, `${h.display}() (it may close or resize an account it is given)`);
2560
+ // Nor may a helper change a tree of an account a for … of is walking.
2561
+ if (takesAccounts && this.iteratingTrees.size && this.helperMakesMutTree(h.node))
2562
+ this.fail(node, `${h.display}() takes accounts and makes an rbTreeMutAt view, so it may change the tree a for … of is walking (${[...this.iteratingTrees.values()].map((w) => w.name).join(", ")}): collect what it needs in the loop, then call it after`);
2289
2563
  const values = [];
2290
2564
  const pieces = [];
2291
2565
  h.params.forEach((p, i) => {
@@ -2298,14 +2572,21 @@ export class CallEmitter extends ExpressionEmitter {
2298
2572
  pieces.push(raw);
2299
2573
  else {
2300
2574
  pieces.push(values.length);
2301
- values.push(takesAccounts ? this.ownedString(raw) : raw);
2575
+ // Text viewing account data or an Inout place may change under the helper: it gets the bytes as they are now.
2576
+ values.push(mayWrite ? this.ownedString(raw) : raw);
2302
2577
  }
2303
2578
  });
2304
- // A helper that takes a writable struct account may replace anything stored in it (see assertNotAliased).
2579
+ if (h.params.some((p) => p.inout))
2580
+ this.checkInoutCall(node, h, argNodes, pieces.map((x) => (typeof x === "string" ? x : undefined)));
2581
+ // A helper that takes a writable struct account may replace anything stored in it (see assertNotAliased): the
2582
+ // account however it is named here (a parameter, an account group's field, a struct loaded with loadAccountMut).
2305
2583
  for (const [i, p] of h.params.entries())
2306
- if (p.account && p.account.kind === "account" && p.account.mut && ts.isIdentifier(argNodes[i]))
2307
- this.assertNotAliased([argNodes[i].text], node, h.display);
2308
- const args = ["params", ...pieces.map((x) => (typeof x === "number" ? (values[x].type.kind === "pubkey" ? `*(${values[x].c})` : values[x].c) : x))];
2584
+ if (p.account && p.account.kind === "account" && p.account.mut)
2585
+ this.assertNotAliased(this.pathsOf(argNodes[i]), node, h.display, true);
2586
+ const args = [
2587
+ "params",
2588
+ ...pieces.map((x) => (typeof x === "number" ? (passedByPointer(values[x].type) ? this.pointerArg(values[x], mayWrite) : values[x].c) : x)),
2589
+ ];
2309
2590
  if (!h.returns) {
2310
2591
  this.line(`TS_TRY(fn_${h.name}(${args.join(", ")}));`);
2311
2592
  return undefined;
@@ -2327,6 +2608,32 @@ export class CallEmitter extends ExpressionEmitter {
2327
2608
  this.line(`TS_TRY(fn_${h.name}(${[...args, `&${t}`].join(", ")}));`);
2328
2609
  return h.returns.kind === "pubkey" ? { c: `(&${t})`, type: h.returns } : { c: t, type: h.returns };
2329
2610
  }
2611
+ /**
2612
+ * A Pubkey, Option, string or u256 helper argument, passed as a pointer (see passedByPointer). When the helper can
2613
+ * write (it takes accounts or Inout places) and the argument is not a named C object nothing passed can reach (see
2614
+ * unreachableArg), the pointer is to a copy taken here: JS gives the helper the value as it is at the call. A
2615
+ * helper that writes nothing reads the caller's value in place.
2616
+ */
2617
+ pointerArg(v, mayWrite) {
2618
+ if (v.type.kind === "pubkey") {
2619
+ if (!mayWrite || unreachableArg(v.c, true))
2620
+ return v.c;
2621
+ const t = this.tmp("argk");
2622
+ this.line(`SolPubkey ${t} = *(${v.c});`);
2623
+ return `(&${t})`;
2624
+ }
2625
+ const own = /^\(\*(p_\w+)\)$/.exec(v.c);
2626
+ if (own)
2627
+ return own[1];
2628
+ if (/^\w+$/.test(v.c))
2629
+ return `(&${v.c})`;
2630
+ // A field read in place (`d_x->opt`): an Option's C struct is packed, so its address is fine to take.
2631
+ if (!mayWrite && v.type.kind === "option" && /^\w+(?:(?:->|\.)\w+)+$/.test(v.c))
2632
+ return `(&${v.c})`;
2633
+ const t = this.tmp("argv");
2634
+ this.line(`${valueC(v.type)} ${t} = ${v.c};`);
2635
+ return `(&${t})`;
2636
+ }
2330
2637
  /** One helper argument: a C argument list fragment (accounts, seeds, references) or a value to settle. */
2331
2638
  helperArg(h, p, n) {
2332
2639
  if (p.account) {
@@ -2359,6 +2666,8 @@ export class CallEmitter extends ExpressionEmitter {
2359
2666
  return `a_${acct.name}, entry_${acct.name}`;
2360
2667
  return `a_${acct.name}`;
2361
2668
  }
2669
+ if (p.inout)
2670
+ return this.inoutArg(h, p, n);
2362
2671
  switch (p.type.kind) {
2363
2672
  case "signerSeeds": {
2364
2673
  const seeds = this.signerSeedsArg(n);
@@ -2398,14 +2707,189 @@ export class CallEmitter extends ExpressionEmitter {
2398
2707
  const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
2399
2708
  // An Option<Vec<T>> argument passes as its list once checked against null (TypeScript narrows it).
2400
2709
  const t = l?.type.kind === "vecArg" && l.type.optional ? { ...l.type, optional: undefined } : l?.type;
2401
- if (!l || !t || !sameType(t, p.type))
2402
- this.fail(n, `expected a ${typeName(p.type)} instruction argument`);
2403
- return l.c;
2710
+ if (l && t && sameType(t, p.type))
2711
+ return l.c;
2712
+ // A list of the caller's (a local FixedVec or FixedArray, a field of a local struct, or one in account data): a
2713
+ // read-only view of its elements, passed by pointer.
2714
+ const view = this.listViewArg(n, p.type, h);
2715
+ if (view)
2716
+ return view;
2717
+ const what = p.type.elem.kind === "int" && p.type.elem.name === "u8" && p.type.cap === undefined ? "list of u8" : `list of ${typeName(p.type.elem)}`;
2718
+ this.fail(n, `expected a ${what}: an instruction argument, the instruction data or a slice of it, or a FixedVec / FixedArray of ${typeName(p.type.elem)} (a local, a field)`);
2404
2719
  }
2405
2720
  default:
2406
2721
  return this.expect(this.expr(n, p.type), p.type, n);
2407
2722
  }
2408
2723
  }
2724
+ /**
2725
+ * An `Inout<T>` argument: a pointer to the caller's place itself (never a copy), which must be writable. A literal
2726
+ * (`f({ … })`, `fixedArray(…)`) is built in a local of its own, as JS passes a fresh object; a ternary must pick
2727
+ * between two places (a literal branch would be a copy the helper's writes never reach).
2728
+ */
2729
+ inoutArg(h, p, n) {
2730
+ const want = p.inout;
2731
+ const what = `Inout<${typeName(want)}>`;
2732
+ let bare = n;
2733
+ while (ts.isParenthesizedExpression(bare))
2734
+ bare = bare.expression;
2735
+ if (want.kind !== "vec" && (ts.isObjectLiteralExpression(bare) || (ts.isCallExpression(bare) && this.exportName(bare.expression) === "fixedArray")))
2736
+ return this.literalArg(n, want);
2737
+ if (ts.isConditionalExpression(bare)) {
2738
+ if (want.kind !== "struct")
2739
+ this.fail(n, `${h.display}() takes ${p.name} as ${what}: pass the list itself, not a choice between lists`);
2740
+ const place = this.structPlace(bare);
2741
+ if (!place)
2742
+ this.fail(n, `${h.display}() takes ${p.name} as ${what}: both branches must be ${want.name} places (a local, a field, a list element), not values`);
2743
+ if (place.struct !== want.name)
2744
+ this.fail(n, `${h.display}() takes ${p.name} as ${what}; this is a ${place.struct}`);
2745
+ if (!place.writable)
2746
+ this.fail(n, `${h.display}() changes ${p.name} (Inout), and a branch of this choice is read-only`);
2747
+ return place.ptr;
2748
+ }
2749
+ let r = this.ref(n);
2750
+ // A narrowed Option<Struct> / Option<FixedArray> place (`c.opt !== null` before it): the value inside it.
2751
+ if (r && r.type.kind === "option" && sameType(r.type.inner, want))
2752
+ r = this.someValue(r);
2753
+ if (!r || !sameType(r.type, want)) {
2754
+ const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
2755
+ if (l?.type.kind === "vecArg" || l?.type.kind === "optionArg")
2756
+ this.fail(n, `${h.display}() changes ${p.name} (Inout): instruction arguments are read-only; copy the value into a local first`);
2757
+ this.fail(n, `${h.display}() takes ${p.name} as ${what}: pass a ${typeName(want)} place of yours (a local, a field, a list element) for it to change`);
2758
+ }
2759
+ if (!r.writable)
2760
+ this.fail(n, `${h.display}() changes ${p.name} (Inout): ${this.readOnly(r)}`);
2761
+ if (r.vec?.slice)
2762
+ this.fail(n, `${h.display}() takes ${p.name} as ${what}: pass the list, not a slice of it`);
2763
+ return `(&${r.lv})`;
2764
+ }
2765
+ /**
2766
+ * The rules of a call with `Inout<T>` arguments, so the helper's pointer is the only way to the place while it runs
2767
+ * (Rust's one `&mut` at a time) and stays valid: no other argument may share storage with an Inout one (two places,
2768
+ * one inside the other, the same list's elements whatever their indexes, an account and a place in it); a place in
2769
+ * a list whose elements can move is refused when the call may move them; a reference into the place read after the
2770
+ * call is refused (the helper may replace what it points at). Places whose roots differ but may be the same bytes at
2771
+ * run time (two `Dup<…>` accounts, two loadRawMut views under NATIVE_ACCOUNT_WRITES, a helper's account parameters)
2772
+ * are compared at run time (2040).
2773
+ */
2774
+ checkInoutCall(node, h, argNodes, passed) {
2775
+ const show = (e) => {
2776
+ try {
2777
+ return e.getText();
2778
+ }
2779
+ catch {
2780
+ return "this argument";
2781
+ }
2782
+ };
2783
+ const fresh = (e) => {
2784
+ while (ts.isParenthesizedExpression(e))
2785
+ e = e.expression;
2786
+ // A literal, or a struct a helper returns: a value of its own that nothing else reaches.
2787
+ if (ts.isObjectLiteralExpression(e))
2788
+ return true;
2789
+ if (!ts.isCallExpression(e))
2790
+ return false;
2791
+ return this.exportName(e.expression) === "fixedArray" || this.helperOf(e)?.returns?.kind === "struct";
2792
+ };
2793
+ // Each argument passed by reference (Inout, read-only structs and lists, accounts, loaded structs) and its storage.
2794
+ const refs = [];
2795
+ h.params.forEach((p, i) => {
2796
+ const n = argNodes[i];
2797
+ if (p.inout) {
2798
+ const paths = this.pathsOf(n);
2799
+ if (!paths && !fresh(n))
2800
+ this.fail(n, `${h.display}() changes ${p.name} (Inout): pass a local, a field path or a list element (bind anything else to a const first)`);
2801
+ if (paths)
2802
+ refs.push({ i, inout: true, paths });
2803
+ return;
2804
+ }
2805
+ const byRef = p.account || p.type.kind === "structRef" || p.type.kind === "arrayArg" || p.type.kind === "dataEnumArg" || p.type.kind === "vecArg";
2806
+ const paths = byRef ? this.pathsOf(n) : undefined;
2807
+ if (paths)
2808
+ refs.push({ i, inout: false, paths });
2809
+ });
2810
+ for (let a = 0; a < refs.length; a++)
2811
+ for (let b = a + 1; b < refs.length; b++) {
2812
+ const x = refs[a];
2813
+ const y = refs[b];
2814
+ if ((!x.inout && !y.inout) || !this.placesOverlap(x.paths, y.paths))
2815
+ continue;
2816
+ const [w, o] = x.inout ? [x, y] : [y, x];
2817
+ const wn = show(argNodes[w.i]);
2818
+ const on = show(argNodes[o.i]);
2819
+ const op = h.params[o.i];
2820
+ const why = `${wn} and ${on} share storage, and ${h.display}() changes ${h.params[w.i].name} (Inout) in place: while it runs, its parameter must be the only way to that place`;
2821
+ if (op.inout)
2822
+ this.fail(argNodes[Math.max(w.i, o.i)], `${why}. Two elements of one list count as one place whatever their indexes; pass what holds both, or copy one into a local and store it back after the call`);
2823
+ if (op.account)
2824
+ this.fail(argNodes[o.i], `${why}. Pass the account alone and reach ${wn} through it in the helper, or pass only ${wn}`);
2825
+ this.fail(argNodes[o.i], `${why}. Copy ${on} into a local first (const copy: T = ${on}) and pass the copy`);
2826
+ }
2827
+ for (const r of refs) {
2828
+ if (!r.inout)
2829
+ continue;
2830
+ const n = argNodes[r.i];
2831
+ if (this.throughMovableList(n) && this.mayResizeVecs(node))
2832
+ this.fail(n, `${show(n)} is in a list whose elements move when it grows, shrinks or is filtered (a Vec or BigVec), and ${h.display}() may do that (it takes writable or remaining accounts) while it holds ${show(n)}; copy the element into a local (const e: T = …), pass the local and store it back after the call`);
2833
+ this.assertNothingInside(r.paths, node, h.display, show(n));
2834
+ }
2835
+ // Different roots that may still be the same bytes: compared at run time.
2836
+ const root = (p) => p.split(/[.[]/)[0];
2837
+ const local = (c) => {
2838
+ for (const s of [...this.scopes, this.args])
2839
+ for (const l of s.values())
2840
+ if (l.c === c)
2841
+ return l;
2842
+ return undefined;
2843
+ };
2844
+ const mayShare = (a, b) => {
2845
+ if (a === b)
2846
+ return false;
2847
+ const acct = (r) => (r.startsWith("@") ? undefined : this.accounts.get(r));
2848
+ const view = (r) => (r.startsWith("@") && local(r.slice(1))?.view ? r : undefined);
2849
+ const [aa, ba] = [acct(a), acct(b)];
2850
+ if (aa && ba)
2851
+ return aa.index === -1 || ba.index === -1 || !!aa.constraints.dup || !!ba.constraints.dup;
2852
+ if (!this.nativeAccountWrites())
2853
+ return false;
2854
+ return !!((aa || view(a)) && (ba || view(b)));
2855
+ };
2856
+ // A read-only argument beside an Inout one may also be the same bytes: an account the runtime does not keep apart
2857
+ // from a writable one (a read-only parameter is not checked against the writable ones).
2858
+ const readOnlyAccount = (r) => {
2859
+ const a = r.startsWith("@") ? undefined : this.accounts.get(r);
2860
+ return !!a && !isWritable(a.kind);
2861
+ };
2862
+ const mayShareRead = (a, b) => mayShare(a, b) || (a !== b && !!this.accounts.get(a) && !!this.accounts.get(b) && (readOnlyAccount(a) || readOnlyAccount(b)));
2863
+ // The bytes an argument is passed as, when they are the caller's own: a place's pointer, an account's data, a list
2864
+ // view's elements. A copy taken for the call (a helper that takes accounts gets one) shares nothing.
2865
+ const bytes = (r) => {
2866
+ const v = passed[r.i];
2867
+ if (!v)
2868
+ return undefined;
2869
+ const p = h.params[r.i];
2870
+ if (r.inout || (v.startsWith("(&") && (p.type.kind === "structRef" || p.type.kind === "arrayArg" || p.type.kind === "dataEnumArg")))
2871
+ return { lo: `(uint8_t *)${v}`, hi: `(uint8_t *)${v} + sizeof(*${v})` };
2872
+ if (p.account && /^\w+$/.test(v))
2873
+ return { lo: `${v}->data`, hi: `${v}->data + ${v}->data_len` };
2874
+ if (p.type.kind === "vecArg" && /^\w+$/.test(v) && !h.params.some((q) => q.account || q.type.kind === "account" || q.type.kind === "remaining"))
2875
+ return { lo: `${v}.ptr`, hi: `${v}.ptr + (uint64_t)${v}.len * ${this.fieldBytes(p.type.elem)}` };
2876
+ return undefined;
2877
+ };
2878
+ for (let a = 0; a < refs.length; a++)
2879
+ for (let b = a + 1; b < refs.length; b++) {
2880
+ const x = refs[a];
2881
+ const y = refs[b];
2882
+ if (!x.inout && !y.inout)
2883
+ continue;
2884
+ const share = x.inout && y.inout ? mayShare : mayShareRead;
2885
+ if (!x.paths.some((p) => y.paths.some((q) => share(root(p), root(q)))))
2886
+ continue;
2887
+ const [bx, by] = [bytes(x), bytes(y)];
2888
+ if (!bx || !by)
2889
+ continue;
2890
+ this.line(`if (${bx.lo} < ${by.hi} && ${by.lo} < ${bx.hi}) TS_FAIL(TS_ERR_DUPLICATE_MUT, ${cString(`TypeSOL: ${h.display}() was given ${show(argNodes[x.i])} and ${show(argNodes[y.i])}, which share storage`)});`);
2891
+ }
2892
+ }
2409
2893
  /**
2410
2894
  * A struct, array or data-enum helper argument written as a literal (`f({ a: 1n, b: { c } })`, `g([1n, 2n])`, or a
2411
2895
  * ternary with a literal branch): built in a local of its own, as `const x: T = { … }; f(x)` would, and passed by
@@ -2452,6 +2936,79 @@ export class CallEmitter extends ExpressionEmitter {
2452
2936
  this.line(`ts_memcpy(${t}, &${lv}, ${n});`);
2453
2937
  return t;
2454
2938
  }
2939
+ /**
2940
+ * A FixedVec or FixedArray of `elem` given for a read-only list parameter: a `TS_VecArg` view of its elements (the
2941
+ * length as it is at the call). A list this function holds (a local, a field of a struct it owns) is read in place;
2942
+ * one in account data is copied first when the helper takes accounts, as a struct argument is (the helper may write
2943
+ * the account). Undefined when `n` is not such a list.
2944
+ */
2945
+ listViewArg(n, want, h) {
2946
+ const r = this.probe(() => this.ref(n));
2947
+ if (!r)
2948
+ return undefined;
2949
+ const elem = want.elem;
2950
+ // A FixedVec<T, N> parameter holds at most N elements: a list with room for more is refused here, as an
2951
+ // instruction argument with more is refused when decoded.
2952
+ const holds = r.type.kind === "vec" ? r.type.cap : r.type.kind === "array" ? r.type.len : undefined;
2953
+ if (want.cap !== undefined && holds !== undefined && holds > want.cap && (r.type.kind === "vec" || r.type.kind === "array") && sameType(r.type.elem, elem))
2954
+ this.fail(n, `${h.display}() takes at most ${want.cap} elements here (FixedVec<${typeName(elem)}, ${want.cap}>) and this list holds up to ${holds}: declare the parameter FixedVec<${typeName(elem)}, ${holds}> (or InstructionBytes / Vec<${typeName(elem)}>, no limit)`);
2955
+ let items;
2956
+ let count;
2957
+ let room;
2958
+ if (r.type.kind === "vec" && r.type.cap !== undefined && !r.type.heap && !r.type.big && !r.type.raw && r.vec && !r.vec.slice) {
2959
+ if (!sameType(r.type.elem, elem))
2960
+ return undefined;
2961
+ const fresh = this.ref(n);
2962
+ items = fresh.vec.items;
2963
+ count = vecCount(fresh.vec);
2964
+ room = r.type.cap;
2965
+ }
2966
+ else if (r.type.kind === "array") {
2967
+ if (!sameType(r.type.elem, elem))
2968
+ return undefined;
2969
+ items = this.ref(n).lv;
2970
+ count = String(r.type.len);
2971
+ room = r.type.len;
2972
+ }
2973
+ else
2974
+ return undefined;
2975
+ const size = this.fieldBytes(elem);
2976
+ const t = this.tmp("lview");
2977
+ if (h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining") && !this.callerHoldsList(n)) {
2978
+ // One buffer per call site, allocated on first use: a call in a loop must not take new heap every pass.
2979
+ const buf = this.tmp("argl");
2980
+ this.hoistLazy(buf, (v) => `uint8_t *${v}`);
2981
+ this.line(`if (${buf} == NULL) TS_TRY(ts_alloc(${room * size}, &${buf}));`);
2982
+ this.line(`TS_VecArg ${t} = {${buf}, (uint32_t)${count}};`);
2983
+ this.line(`ts_memcpy_bulk(${buf}, (const uint8_t *)${items}, (uint64_t)${t}.len * ${size});`);
2984
+ return t;
2985
+ }
2986
+ this.line(`TS_VecArg ${t} = {(const uint8_t *)${items}, (uint32_t)${count}};`);
2987
+ return t;
2988
+ }
2989
+ /** Whether `node` is a list this function holds on its stack (a local list, a field of a struct it owns), not account data. */
2990
+ callerHoldsList(node) {
2991
+ let n = node;
2992
+ for (;;) {
2993
+ if (ts.isParenthesizedExpression(n))
2994
+ n = n.expression;
2995
+ else if (ts.isPropertyAccessExpression(n))
2996
+ n = n.expression;
2997
+ else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === "get")
2998
+ n = n.expression.expression;
2999
+ else
3000
+ break;
3001
+ }
3002
+ if (!ts.isIdentifier(n))
3003
+ return false;
3004
+ const l = this.lookup(n.text);
3005
+ if (!l)
3006
+ return false;
3007
+ // A declared list local has no storage paths; an Inout parameter's (`@p_x`) may be account data.
3008
+ if ((l.type.kind === "vec" || l.type.kind === "array") && !l.paths && !l.readonly)
3009
+ return true;
3010
+ return !!l.owned;
3011
+ }
2455
3012
  /** Whether `node` is (part of) a struct value this function owns: `h`, `h.inner`, `h.list.get(i)`. */
2456
3013
  ownedRoot(node) {
2457
3014
  let n = node;
@@ -2477,7 +3034,8 @@ export class CallEmitter extends ExpressionEmitter {
2477
3034
  if (ts.isCallExpression(n) && this.exportName(n.expression) === "signer") {
2478
3035
  if (n.arguments.length !== 1)
2479
3036
  this.fail(n, "signer([...seeds]) takes the seeds (with the bump) as an array; signer([]) signs for nothing");
2480
- return this.seeds(n.arguments[0], 0);
3037
+ // Bound to a name or given to a helper: the list outlives this expression, so its seeds are copied now.
3038
+ return this.seeds(n.arguments[0], 0, true);
2481
3039
  }
2482
3040
  this.fail(n, "pass signer([...seeds with the bump]) or a SignerSeeds parameter");
2483
3041
  }