@typesol/cli 0.41.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +2 -1
  3. package/dist/compiler/analyze.js +41 -1
  4. package/dist/compiler/emit/base.d.ts +40 -7
  5. package/dist/compiler/emit/base.js +33 -0
  6. package/dist/compiler/emit/borsh.d.ts +7 -0
  7. package/dist/compiler/emit/borsh.js +86 -1
  8. package/dist/compiler/emit/calls.d.ts +102 -2
  9. package/dist/compiler/emit/calls.js +663 -49
  10. package/dist/compiler/emit/cpi-core.d.ts +9 -3
  11. package/dist/compiler/emit/cpi-core.js +12 -7
  12. package/dist/compiler/emit/cpi.js +8 -14
  13. package/dist/compiler/emit/create.d.ts +3 -3
  14. package/dist/compiler/emit/create.js +33 -25
  15. package/dist/compiler/emit/expressions.js +51 -2
  16. package/dist/compiler/emit/function.js +2 -2
  17. package/dist/compiler/emit/outline.d.ts +24 -0
  18. package/dist/compiler/emit/outline.js +100 -0
  19. package/dist/compiler/emit/program.js +7 -2
  20. package/dist/compiler/emit/shared.d.ts +35 -1
  21. package/dist/compiler/emit/shared.js +9 -1
  22. package/dist/compiler/emit/statements.d.ts +31 -0
  23. package/dist/compiler/emit/statements.js +272 -14
  24. package/dist/compiler/emit/storage.d.ts +27 -1
  25. package/dist/compiler/emit/storage.js +124 -11
  26. package/dist/compiler/emit/token.d.ts +11 -8
  27. package/dist/compiler/emit/token.js +233 -104
  28. package/dist/compiler/hints.js +6 -0
  29. package/dist/compiler/model.d.ts +20 -1
  30. package/dist/compiler/model.js +5 -0
  31. package/dist/testing-stake.d.ts +216 -0
  32. package/dist/testing-stake.js +526 -0
  33. package/dist/testing.d.ts +1 -0
  34. package/dist/testing.js +1 -0
  35. package/docs/architecture.md +1 -1
  36. package/docs/case-study-spl-stake-pool.md +122 -0
  37. package/docs/errors.md +1 -1
  38. package/docs/language.md +107 -14
  39. package/docs/security-model.md +4 -0
  40. package/docs/stability.md +13 -0
  41. package/docs/test-your-program.md +47 -0
  42. package/docs/testing.md +19 -0
  43. package/lib/typesol.d.ts +241 -40
  44. package/llms-full.txt +172 -15
  45. package/llms.txt +1 -1
  46. package/package.json +1 -1
  47. package/runtime/typesol_rt.h +69 -0
@@ -1,20 +1,24 @@
1
1
  import ts from "typescript";
2
2
  import { isWritable } from "../model.js";
3
- import { U64, U8, BOOL, PUBKEY, STRING, cBytes, optC } from "./shared.js";
3
+ import { U64, U8, I64, BOOL, PUBKEY, STRING, cBytes, cString, optC } from "./shared.js";
4
4
  import { CreateEmitter } from "./create.js";
5
5
  /** SPL Token and Token-2022 instructions (`tokenProgram.transfer(…)` and the rest) and the ATA program's. */
6
6
  export class TokenEmitter extends CreateEmitter {
7
7
  tokenOp(node, program, method) {
8
8
  const a = node.arguments;
9
- const p = `a_${program.name}`;
10
- // `created`: also a Mut<AccountInfo> token account this instruction created (an associated token account).
11
- const want = (n, kind, mut, what, created = false) => {
12
- const acct = this.accountParam(n, what);
13
- if (created && acct.kind.kind === "info" && isWritable(acct.kind))
14
- return acct;
15
- if (acct.kind.kind !== kind || (mut && !acct.kind.mut))
16
- this.fail(n, `${what} must be a ${mut ? "Mut<" : ""}${kind === "token" ? "TokenAccount" : "Mint"}${mut ? ">" : ""}${created ? ", or a Mut<AccountInfo> token account this instruction created" : ""}`);
17
- return acct;
9
+ const p = program.c;
10
+ // A TokenAccount / Mint parameter, or an AccountInfo one (a token account this instruction created, an account a
11
+ // native port takes unchecked) or a remaining account: the token program checks those.
12
+ const want = (n, kind, mut, what) => {
13
+ const x = this.cpiAccount(n, what);
14
+ const acct = x.param;
15
+ if (!acct || (acct.kind.kind === "info" && (!mut || isWritable(acct.kind))))
16
+ return x;
17
+ if (acct.kind.kind !== kind || (mut && !acct.kind.mut)) {
18
+ const type = kind === "token" ? "TokenAccount" : "Mint";
19
+ this.fail(n, `${what} must be a ${mut ? `Mut<${type}> or a Mut<AccountInfo>` : `${type} or an AccountInfo`}`);
20
+ }
21
+ return x;
18
22
  };
19
23
  const arity = (fixed) => {
20
24
  if (a.length !== fixed && a.length !== fixed + 1)
@@ -26,10 +30,10 @@ export class TokenEmitter extends CreateEmitter {
26
30
  arity(4);
27
31
  const from = want(a[0], "token", true, "the source");
28
32
  const to = want(a[1], "token", true, "the destination");
29
- const auth = this.accountParam(a[2], "the authority");
33
+ const auth = this.cpiAccount(a[2], "the authority");
30
34
  const amt = amount(a[3]);
31
35
  const s = this.signerSeeds(a[4], auth, a[2]);
32
- this.line(`TS_TRY(ts_token_transfer(params, ${p}, a_${from.name}, a_${to.name}, a_${auth.name}, ${amt}, ${s.name}, ${s.count}));`);
36
+ this.line(`TS_TRY(ts_token_transfer(params, ${p}, ${from.c}, ${to.c}, ${auth.c}, ${amt}, ${s.name}, ${s.count}));`);
33
37
  return undefined;
34
38
  }
35
39
  case "transferChecked": {
@@ -37,33 +41,34 @@ export class TokenEmitter extends CreateEmitter {
37
41
  const from = want(a[0], "token", true, "the source");
38
42
  const mint = want(a[1], "mint", false, "the mint");
39
43
  const to = want(a[2], "token", true, "the destination");
40
- const auth = this.accountParam(a[3], "the authority");
44
+ const auth = this.cpiAccount(a[3], "the authority");
41
45
  const amt = amount(a[4]);
42
46
  const s = this.signerSeeds(a[5], auth, a[3]);
43
- this.line(`TS_TRY(ts_token_transfer_checked(params, ${p}, a_${from.name}, a_${mint.name}, a_${to.name}, a_${auth.name}, ${amt}, ${s.name}, ${s.count}));`);
47
+ this.line(`TS_TRY(ts_token_transfer_checked(params, ${p}, ${from.c}, ${mint.c}, ${to.c}, ${auth.c}, ${amt}, ${s.name}, ${s.count}));`);
44
48
  return undefined;
45
49
  }
46
50
  case "mintTo": {
47
51
  arity(4);
48
52
  // A Mut<Mint>, or a mint created and initialized earlier in this instruction (Mut<Signer> / Mut<AccountInfo>).
49
- const mint = this.accountParam(a[0], "the mint");
50
- if (!isWritable(mint.kind) || (mint.kind.kind !== "mint" && mint.kind.kind !== "signer" && mint.kind.kind !== "info"))
53
+ const mint = this.cpiAccount(a[0], "the mint");
54
+ const mp = mint.param;
55
+ if (mp && (!isWritable(mp.kind) || (mp.kind.kind !== "mint" && mp.kind.kind !== "signer" && mp.kind.kind !== "info")))
51
56
  this.fail(a[0], "the mint must be a Mut<Mint>, or a Mut<Signer> / Mut<AccountInfo> mint this instruction created");
52
- const to = want(a[1], "token", true, "the destination", true);
53
- const auth = this.accountParam(a[2], "the mint authority");
57
+ const to = want(a[1], "token", true, "the destination");
58
+ const auth = this.cpiAccount(a[2], "the mint authority");
54
59
  const amt = amount(a[3]);
55
60
  const s = this.signerSeeds(a[4], auth, a[2]);
56
- this.line(`TS_TRY(ts_token_mint_to(params, ${p}, a_${mint.name}, a_${to.name}, a_${auth.name}, ${amt}, ${s.name}, ${s.count}));`);
61
+ this.line(`TS_TRY(ts_token_mint_to(params, ${p}, ${mint.c}, ${to.c}, ${auth.c}, ${amt}, ${s.name}, ${s.count}));`);
57
62
  return undefined;
58
63
  }
59
64
  case "burn": {
60
65
  arity(4);
61
66
  const from = want(a[0], "token", true, "the burned account");
62
67
  const mint = want(a[1], "mint", true, "the mint");
63
- const auth = this.accountParam(a[2], "the authority");
68
+ const auth = this.cpiAccount(a[2], "the authority");
64
69
  const amt = amount(a[3]);
65
70
  const s = this.signerSeeds(a[4], auth, a[2]);
66
- this.line(`TS_TRY(ts_token_burn(params, ${p}, a_${from.name}, a_${mint.name}, a_${auth.name}, ${amt}, ${s.name}, ${s.count}));`);
71
+ this.line(`TS_TRY(ts_token_burn(params, ${p}, ${from.c}, ${mint.c}, ${auth.c}, ${amt}, ${s.name}, ${s.count}));`);
67
72
  return undefined;
68
73
  }
69
74
  case "initializeMetadata": {
@@ -72,35 +77,36 @@ export class TokenEmitter extends CreateEmitter {
72
77
  if (a.length !== 6 && a.length !== 7)
73
78
  this.fail(node, "initializeMetadata(mint, updateAuthority, mintAuthority, name, symbol, uri, signerSeeds?)");
74
79
  // The mint may have been created and initialized earlier in this instruction (a Mut<Signer> or Mut<AccountInfo>).
75
- const mint = this.accountParam(a[0], "the mint");
76
- if (!isWritable(mint.kind))
80
+ const mint = this.cpiAccount(a[0], "the mint");
81
+ if (mint.param && !isWritable(mint.param.kind))
77
82
  this.fail(a[0], "the mint must be writable (Mut<...>)");
78
- const ua = this.accountParam(a[1], "the update authority");
79
- const ma = this.accountParam(a[2], "the mint authority");
83
+ const ua = this.cpiAccount(a[1], "the update authority");
84
+ const ma = this.cpiAccount(a[2], "the mint authority");
80
85
  const [nm, sym, uri] = [a[3], a[4], a[5]].map((n) => this.expect(this.expr(n, STRING), STRING, n).c);
81
86
  const s = this.signerSeeds(a[6], ma, a[2]);
82
- this.line(`TS_TRY(ts_t22_init_metadata(params, ${p}, a_${mint.name}, a_${ua.name}, a_${ma.name}, ${nm}, ${sym}, ${uri}, ${s.name}, ${s.count}));`);
87
+ this.line(`TS_TRY(ts_t22_init_metadata(params, ${p}, ${mint.c}, ${ua.c}, ${ma.c}, ${nm}, ${sym}, ${uri}, ${s.name}, ${s.count}));`);
83
88
  return undefined;
84
89
  }
85
90
  case "closeAccount": {
86
91
  arity(3);
87
92
  // A token account, or (Token-2022, with a MintCloseAuthority and no supply left) a mint.
88
- const acct = this.accountParam(a[0], "the closed account");
89
- if (!((acct.kind.kind === "token" || acct.kind.kind === "mint") && acct.kind.mut))
90
- this.fail(a[0], "the closed account must be a Mut<TokenAccount> or a Mut<Mint>");
91
- const dest = this.accountParam(a[1], "the destination");
92
- if (!isWritable(dest.kind))
93
+ const acct = this.cpiAccount(a[0], "the closed account");
94
+ const k = acct.param?.kind;
95
+ if (k && !(((k.kind === "token" || k.kind === "mint") && k.mut) || (k.kind === "info" && k.mut)))
96
+ this.fail(a[0], "the closed account must be a Mut<TokenAccount>, a Mut<Mint> or a Mut<AccountInfo>");
97
+ const dest = this.cpiAccount(a[1], "the destination");
98
+ if (dest.param && !isWritable(dest.param.kind))
93
99
  this.fail(a[1], "the destination must be writable (Mut<...>)");
94
- const auth = this.accountParam(a[2], "the authority");
100
+ const auth = this.cpiAccount(a[2], "the authority");
95
101
  const s = this.signerSeeds(a[3], auth, a[2]);
96
- this.line(`TS_TRY(ts_token_close(params, ${p}, a_${acct.name}, a_${dest.name}, a_${auth.name}, ${s.name}, ${s.count}));`);
102
+ this.line(`TS_TRY(ts_token_close(params, ${p}, ${acct.c}, ${dest.c}, ${auth.c}, ${s.name}, ${s.count}));`);
97
103
  return undefined;
98
104
  }
99
105
  }
100
106
  // The remaining SPL Token instructions share one shape: a tag, a few fixed fields, and fixed account metas.
101
107
  const anyAcct = (n, what, mut) => {
102
- const acct = this.accountParam(n, what);
103
- if (mut && !isWritable(acct.kind))
108
+ const acct = this.cpiAccount(n, what);
109
+ if (mut && acct.param && !isWritable(acct.param.kind))
104
110
  this.fail(n, `${what} must be writable (Mut<...>)`);
105
111
  return acct;
106
112
  };
@@ -112,13 +118,13 @@ export class TokenEmitter extends CreateEmitter {
112
118
  for (const f of fields)
113
119
  f(put);
114
120
  finish(node);
115
- this.cpi(p, metas.map(([acc, w, sg]) => [`a_${acc.name}`, w, sg]), buf, len, seeds);
121
+ this.cpi(p, metas.map(([acc, w, sg]) => [acc.c, w, sg]), buf, len, seeds);
116
122
  };
117
123
  const value = (n, t) => (put) => this.serialize(this.expect(this.expr(n, t), t, n), n, put);
118
124
  const optKey = { kind: "option", inner: PUBKEY };
119
125
  const U16 = { kind: "int", name: "u16" };
120
126
  const I16 = { kind: "int", name: "i16" };
121
- const decimals = (mint) => (put) => put(`&a_${mint.name}->data[44]`, "1", 1);
127
+ const decimals = (mint) => (put) => put(`&${mint.c}->data[44]`, "1", 1);
122
128
  const byte = (k) => (put) => {
123
129
  const t = this.tmp("b");
124
130
  this.line(`uint8_t ${t} = ${k};`);
@@ -153,7 +159,7 @@ export class TokenEmitter extends CreateEmitter {
153
159
  for (const f of fields)
154
160
  f(put);
155
161
  finish(node);
156
- this.cpi(p, metas.map(([acc, w, sg]) => [`a_${acc.name}`, w, sg]), buf, len, seeds);
162
+ this.cpi(p, metas.map(([acc, w, sg]) => [acc.c, w, sg]), buf, len, seeds);
157
163
  };
158
164
  switch (method) {
159
165
  case "initializeTokenGroup": {
@@ -162,7 +168,7 @@ export class TokenEmitter extends CreateEmitter {
162
168
  this.fail(node, "initializeTokenGroup(group, mint, mintAuthority, updateAuthority | null, maxSize, signerSeeds?)");
163
169
  const group = anyAcct(a[0], "the group", true);
164
170
  const mint = anyAcct(a[1], "the mint", false);
165
- const auth = this.accountParam(a[2], "the mint authority");
171
+ const auth = this.cpiAccount(a[2], "the mint authority");
166
172
  grouped([121, 113, 108, 39, 54, 51, 0, 4], [nonZeroKey(a[3]), value(a[4], U64)], [
167
173
  [group, true, false],
168
174
  [mint, false, false],
@@ -176,9 +182,9 @@ export class TokenEmitter extends CreateEmitter {
176
182
  this.fail(node, "initializeGroupMember(member, memberMint, memberMintAuthority, group, groupUpdateAuthority, signerSeeds?)");
177
183
  const member = anyAcct(a[0], "the member", true);
178
184
  const memberMint = anyAcct(a[1], "the member mint", false);
179
- const mintAuth = this.accountParam(a[2], "the member mint's authority");
185
+ const mintAuth = this.cpiAccount(a[2], "the member mint's authority");
180
186
  const group = anyAcct(a[3], "the group", true);
181
- const groupAuth = this.accountParam(a[4], "the group's update authority");
187
+ const groupAuth = this.cpiAccount(a[4], "the group's update authority");
182
188
  grouped([152, 32, 222, 176, 223, 237, 116, 134], [], [
183
189
  [member, true, false],
184
190
  [memberMint, false, false],
@@ -193,7 +199,7 @@ export class TokenEmitter extends CreateEmitter {
193
199
  if (a.length !== 3 && a.length !== 4)
194
200
  this.fail(node, "updateGroupMaxSize(group, updateAuthority, maxSize, signerSeeds?)");
195
201
  const group = anyAcct(a[0], "the group", true);
196
- const auth = this.accountParam(a[1], "the update authority");
202
+ const auth = this.cpiAccount(a[1], "the update authority");
197
203
  grouped([108, 37, 171, 143, 248, 30, 18, 110], [value(a[2], U64)], [
198
204
  [group, true, false],
199
205
  [auth, false, true],
@@ -205,7 +211,7 @@ export class TokenEmitter extends CreateEmitter {
205
211
  if (a.length !== 3 && a.length !== 4)
206
212
  this.fail(node, "updateGroupAuthority(group, updateAuthority, next | null, signerSeeds?)");
207
213
  const group = anyAcct(a[0], "the group", true);
208
- const auth = this.accountParam(a[1], "the update authority");
214
+ const auth = this.cpiAccount(a[1], "the update authority");
209
215
  grouped([161, 105, 88, 1, 237, 221, 216, 203], [nonZeroKey(a[2])], [
210
216
  [group, true, false],
211
217
  [auth, false, true],
@@ -281,7 +287,7 @@ export class TokenEmitter extends CreateEmitter {
281
287
  if (a.length !== 3 && a.length !== 4)
282
288
  this.fail(node, "updateDefaultAccountState(mint, freezeAuthority, frozen, signerSeeds?)");
283
289
  const mint = anyAcct(a[0], "the mint", true);
284
- const auth = this.accountParam(a[1], "the freeze authority");
290
+ const auth = this.cpiAccount(a[1], "the freeze authority");
285
291
  const frozen = this.expect(this.expr(a[2], BOOL), BOOL, a[2]);
286
292
  const st = this.tmp("st");
287
293
  this.line(`uint8_t ${st} = (${frozen.c}) ? 2 : 1;`);
@@ -297,7 +303,7 @@ export class TokenEmitter extends CreateEmitter {
297
303
  if (a.length !== 2 && a.length !== 3)
298
304
  this.fail(node, `${method}(account, owner, signerSeeds?)`);
299
305
  const acct = anyAcct(a[0], "the token account", true);
300
- const owner = this.accountParam(a[1], "the owner");
306
+ const owner = this.cpiAccount(a[1], "the owner");
301
307
  simple(30, [byte(method === "enableRequiredMemoTransfers" ? 0 : 1)], [
302
308
  [acct, true, false],
303
309
  [owner, false, true],
@@ -309,7 +315,7 @@ export class TokenEmitter extends CreateEmitter {
309
315
  if (a.length !== 3 && a.length !== 4)
310
316
  this.fail(node, "updateTransferHook(mint, authority, programId | null, signerSeeds?)");
311
317
  const mint = anyAcct(a[0], "the mint", true);
312
- const auth = this.accountParam(a[1], "the transfer hook authority");
318
+ const auth = this.cpiAccount(a[1], "the transfer hook authority");
313
319
  simple(36, [byte(1), nonZeroKey(a[2])], [
314
320
  [mint, true, false],
315
321
  [auth, false, true],
@@ -321,7 +327,7 @@ export class TokenEmitter extends CreateEmitter {
321
327
  if (a.length !== 3 && a.length !== 4)
322
328
  this.fail(node, "updateInterestRate(mint, rateAuthority, rate, signerSeeds?)");
323
329
  const mint = anyAcct(a[0], "the mint", true);
324
- const auth = this.accountParam(a[1], "the rate authority");
330
+ const auth = this.cpiAccount(a[1], "the rate authority");
325
331
  simple(33, [byte(1), value(a[2], I16)], [
326
332
  [mint, true, false],
327
333
  [auth, false, true],
@@ -335,11 +341,11 @@ export class TokenEmitter extends CreateEmitter {
335
341
  const from = want(a[0], "token", true, "the source");
336
342
  const mint = want(a[1], "mint", false, "the mint");
337
343
  const to = want(a[2], "token", true, "the destination");
338
- const auth = this.accountParam(a[3], "the authority");
344
+ const auth = this.cpiAccount(a[3], "the authority");
339
345
  // The decimals are the mint's own (checked when the mint was), as transferChecked does.
340
346
  const dec = (put) => {
341
347
  const t = this.tmp("dec");
342
- this.line(`uint8_t ${t} = a_${mint.name}->data[44];`);
348
+ this.line(`uint8_t ${t} = ${mint.c}->data[44];`);
343
349
  put(`&${t}`, "1", 1);
344
350
  };
345
351
  simple(26, [byte(1), value(a[4], U64), dec, value(a[5], U64)], [
@@ -363,7 +369,7 @@ export class TokenEmitter extends CreateEmitter {
363
369
  byte(4)(put);
364
370
  finish(node);
365
371
  // The sources go as they were passed (Token-2022 skips any it cannot harvest from).
366
- this.cpi(p, [[`a_${mint.name}`, true, false]], buf, len, none, { ...range, asPassed: true });
372
+ this.cpi(p, [[mint.c, true, false]], buf, len, none, { ...range, asPassed: true });
367
373
  return undefined;
368
374
  }
369
375
  case "withdrawWithheldTokensFromMint": {
@@ -372,7 +378,7 @@ export class TokenEmitter extends CreateEmitter {
372
378
  this.fail(node, "withdrawWithheldTokensFromMint(mint, destination, authority, signerSeeds?)");
373
379
  const mint = anyAcct(a[0], "the mint", true);
374
380
  const dest = want(a[1], "token", true, "the destination");
375
- const auth = this.accountParam(a[2], "the withdraw authority");
381
+ const auth = this.cpiAccount(a[2], "the withdraw authority");
376
382
  simple(26, [byte(2)], [
377
383
  [mint, true, false],
378
384
  [dest, true, false],
@@ -385,7 +391,7 @@ export class TokenEmitter extends CreateEmitter {
385
391
  if (a.length !== 4 && a.length !== 5)
386
392
  this.fail(node, "setTransferFee(mint, configAuthority, basisPoints, maximumFee, signerSeeds?)");
387
393
  const mint = anyAcct(a[0], "the mint", true);
388
- const auth = this.accountParam(a[1], "the config authority");
394
+ const auth = this.cpiAccount(a[1], "the config authority");
389
395
  const bps = (put) => {
390
396
  const v = this.expect(this.expr(a[2], U16), U16, a[2]);
391
397
  this.line(`if (${v.c} > 10000) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: transfer fee above 10000 basis points");`);
@@ -419,7 +425,7 @@ export class TokenEmitter extends CreateEmitter {
419
425
  emitMetadata: "faa6b4fa0d0cb846",
420
426
  }[method];
421
427
  const mint = anyAcct(a[0], "the mint", method !== "emitMetadata");
422
- const auth = method === "emitMetadata" ? undefined : this.accountParam(a[1], "the update authority");
428
+ const auth = method === "emitMetadata" ? undefined : this.cpiAccount(a[1], "the update authority");
423
429
  const { buf, len, put, finish } = this.byteBuffer("tmd", 1232, "TS_ERR_INSTRUCTION_DATA", "token metadata instruction");
424
430
  const d = this.tmp("disc");
425
431
  this.line(`static const uint8_t ${d}[8] = ${cBytes([...Buffer.from(disc, "hex")])};`);
@@ -458,17 +464,17 @@ export class TokenEmitter extends CreateEmitter {
458
464
  const seeds = auth ? this.signerSeeds(a[fixedArgs], auth, a[1]) : none;
459
465
  this.cpi(p, auth
460
466
  ? [
461
- [`a_${mint.name}`, true, false],
462
- [`a_${auth.name}`, false, true],
467
+ [mint.c, true, false],
468
+ [auth.c, false, true],
463
469
  ]
464
- : [[`a_${mint.name}`, false, false]], buf, len, seeds);
470
+ : [[mint.c, false, false]], buf, len, seeds);
465
471
  return undefined;
466
472
  }
467
473
  case "approve": {
468
474
  arity(4);
469
475
  const src = want(a[0], "token", true, "the source");
470
- const delegate = this.accountParam(a[1], "the delegate");
471
- const owner = this.accountParam(a[2], "the owner");
476
+ const delegate = this.cpiAccount(a[1], "the delegate");
477
+ const owner = this.cpiAccount(a[2], "the owner");
472
478
  const s = this.signerSeeds(a[4], owner, a[2]);
473
479
  const amt = value(a[3], U64);
474
480
  simple(4, [amt], [
@@ -483,8 +489,8 @@ export class TokenEmitter extends CreateEmitter {
483
489
  arity(5);
484
490
  const src = want(a[0], "token", true, "the source");
485
491
  const mint = want(a[1], "mint", false, "the mint");
486
- const delegate = this.accountParam(a[2], "the delegate");
487
- const owner = this.accountParam(a[3], "the owner");
492
+ const delegate = this.cpiAccount(a[2], "the delegate");
493
+ const owner = this.cpiAccount(a[3], "the owner");
488
494
  const s = this.signerSeeds(a[5], owner, a[3]);
489
495
  simple(13, [value(a[4], U64), decimals(mint)], [
490
496
  [src, true, false],
@@ -497,8 +503,8 @@ export class TokenEmitter extends CreateEmitter {
497
503
  case "mintToChecked": {
498
504
  arity(4);
499
505
  const mint = want(a[0], "mint", true, "the mint");
500
- const to = want(a[1], "token", true, "the destination", true);
501
- const auth = this.accountParam(a[2], "the mint authority");
506
+ const to = want(a[1], "token", true, "the destination");
507
+ const auth = this.cpiAccount(a[2], "the mint authority");
502
508
  const s = this.signerSeeds(a[4], auth, a[2]);
503
509
  simple(14, [value(a[3], U64), decimals(mint)], [
504
510
  [mint, true, false],
@@ -511,7 +517,7 @@ export class TokenEmitter extends CreateEmitter {
511
517
  arity(4);
512
518
  const from = want(a[0], "token", true, "the burned account");
513
519
  const mint = want(a[1], "mint", true, "the mint");
514
- const auth = this.accountParam(a[2], "the authority");
520
+ const auth = this.cpiAccount(a[2], "the authority");
515
521
  const s = this.signerSeeds(a[4], auth, a[2]);
516
522
  simple(15, [value(a[3], U64), decimals(mint)], [
517
523
  [from, true, false],
@@ -523,7 +529,7 @@ export class TokenEmitter extends CreateEmitter {
523
529
  case "revoke": {
524
530
  arity(2);
525
531
  const src = want(a[0], "token", true, "the source");
526
- const owner = this.accountParam(a[1], "the owner");
532
+ const owner = this.cpiAccount(a[1], "the owner");
527
533
  simple(5, [], [
528
534
  [src, true, false],
529
535
  [owner, false, true],
@@ -533,7 +539,7 @@ export class TokenEmitter extends CreateEmitter {
533
539
  case "setAuthority": {
534
540
  arity(4);
535
541
  const target = anyAcct(a[0], "the mint or token account", true);
536
- const current = this.accountParam(a[1], "the current authority");
542
+ const current = this.cpiAccount(a[1], "the current authority");
537
543
  this.model.options.set("pubkey", PUBKEY);
538
544
  const s = this.signerSeeds(a[4], current, a[1]);
539
545
  simple(6, [value(a[2], U8), value(a[3], optKey)], [
@@ -545,9 +551,9 @@ export class TokenEmitter extends CreateEmitter {
545
551
  case "freezeAccount":
546
552
  case "thawAccount": {
547
553
  arity(3);
548
- const acct = want(a[0], "token", true, "the token account", true);
549
- const mint = this.accountParam(a[1], "the mint");
550
- const auth = this.accountParam(a[2], "the freeze authority");
554
+ const acct = want(a[0], "token", true, "the token account");
555
+ const mint = this.cpiAccount(a[1], "the mint");
556
+ const auth = this.cpiAccount(a[2], "the freeze authority");
551
557
  simple(method === "freezeAccount" ? 10 : 11, [], [
552
558
  [acct, true, false],
553
559
  [mint, false, false],
@@ -574,7 +580,7 @@ export class TokenEmitter extends CreateEmitter {
574
580
  if (a.length !== 3)
575
581
  this.fail(node, "initializeAccount3(account, mint, owner)");
576
582
  const acct = anyAcct(a[0], "the token account", true);
577
- const mint = this.accountParam(a[1], "the mint");
583
+ const mint = this.cpiAccount(a[1], "the mint");
578
584
  simple(18, [value(a[2], PUBKEY)], [
579
585
  [acct, true, false],
580
586
  [mint, false, false],
@@ -590,18 +596,18 @@ export class TokenEmitter extends CreateEmitter {
590
596
  const a = node.arguments;
591
597
  if (a.length !== 6)
592
598
  this.fail(node, `${method}(payer, ata, owner, mint, systemProgram, tokenProgram) takes six accounts`);
593
- const payer = this.accountParam(a[0], "the payer");
594
- if (payer.kind.kind !== "signer" || !payer.kind.mut)
599
+ const payer = this.cpiAccount(a[0], "the payer");
600
+ if (payer.param && (payer.param.kind.kind !== "signer" || !payer.param.kind.mut))
595
601
  this.fail(a[0], "the payer must be a Mut<Signer>");
596
- const ata = this.accountParam(a[1], "the token account");
597
- if (!isWritable(ata.kind))
602
+ const ata = this.cpiAccount(a[1], "the token account");
603
+ if (ata.param && !isWritable(ata.param.kind))
598
604
  this.fail(a[1], "the token account must be Mut<AccountInfo>");
599
- const [owner, mint, sys, tp] = [a[2], a[3], a[4], a[5]].map((n, i) => this.accountParam(n, ["the owner", "the mint", "the system program", "the token program"][i]));
600
- if (sys.kind.kind !== "system")
605
+ const [owner, mint, sys, tp] = [a[2], a[3], a[4], a[5]].map((n, i) => this.cpiAccount(n, ["the owner", "the mint", "the system program", "the token program"][i]));
606
+ if (sys.param && sys.param.kind.kind !== "system")
601
607
  this.fail(a[4], "pass the SystemProgram parameter");
602
- if (tp.kind.kind !== "tokenProgram")
608
+ if (tp.param && tp.param.kind.kind !== "tokenProgram")
603
609
  this.fail(a[5], "pass a token program parameter");
604
- this.line(`TS_TRY(ts_ata_create(params, a_${program.name}, a_${payer.name}, a_${ata.name}, a_${owner.name}, a_${mint.name}, a_${sys.name}, a_${tp.name}, ${method === "createIdempotent"}));`);
610
+ this.line(`TS_TRY(ts_ata_create(params, ${program.c}, ${payer.c}, ${ata.c}, ${owner.c}, ${mint.c}, ${sys.c}, ${tp.c}, ${method === "createIdempotent"}));`);
605
611
  return undefined;
606
612
  }
607
613
  /** memoProgram.memo(text, signers?, signerSeeds?): SPL Memo v2, the UTF-8 text as data, each signer a signing account. */
@@ -615,29 +621,53 @@ export class TokenEmitter extends CreateEmitter {
615
621
  const list = a[1];
616
622
  if (list && !ts.isArrayLiteralExpression(list))
617
623
  this.fail(list, "the signers are a list of accounts: [authority, …]");
618
- const signers = list ? list.elements.map((e) => this.accountParam(e, "a memo signer")) : [];
624
+ const signers = list ? list.elements.map((e) => this.cpiAccount(e, "a memo signer")) : [];
619
625
  const t = this.tmp("memo");
620
626
  this.line(`TS_Str ${t} = ${text.c};`);
621
627
  const seeds = a[2] ? this.signingSeeds(a[2]) : { name: "NULL", count: 0 };
622
628
  if (!signers.length)
623
- this.line(`TS_TRY(ts_cpi(params, a_${program.name}, (uint8_t *)${t}.ptr, ${t}.len, NULL, 0, ${seeds.name}, ${seeds.count}));`);
629
+ this.line(`TS_TRY(ts_cpi(params, ${program.c}, (uint8_t *)${t}.ptr, ${t}.len, NULL, 0, ${seeds.name}, ${seeds.count}));`);
624
630
  else
625
- this.cpi(`a_${program.name}`, signers.map((s) => [`a_${s.name}`, false, true]), `(uint8_t *)${t}.ptr`, `${t}.len`, seeds);
631
+ this.cpi(program.c, signers.map((s) => [s.c, false, true]), `(uint8_t *)${t}.ptr`, `${t}.len`, seeds);
626
632
  return undefined;
627
633
  }
628
634
  /**
629
- * The Stake program (bincode: a u32 instruction tag): initialize, authorize, delegate, deactivate and withdraw, with
630
- * the sysvar and config accounts it reads passed in, as anchor-spl's stake module does. Each authority signs (a PDA of
631
- * this program with `signerSeeds`).
635
+ * The Stake program (bincode: a u32 instruction tag, as solana-stake-interface's StakeInstruction numbers them):
636
+ * initialize, authorize, delegate, split, deactivate, withdraw, merge and getMinimumDelegation, with the account
637
+ * metas of its instruction builders and the sysvar and config accounts it reads passed in. Each authority signs (a
638
+ * PDA of this program with `signerSeeds`).
632
639
  */
633
640
  stakeOp(node, program, method) {
634
641
  const a = node.arguments;
635
642
  const acct = (i, what, mut = false) => {
636
- const x = this.accountParam(a[i], what);
637
- if (mut && !isWritable(x.kind))
643
+ const x = this.cpiAccount(a[i], what);
644
+ if (mut && x.param && !isWritable(x.param.kind))
638
645
  this.fail(a[i], `${what} must be writable (Mut<...>)`);
639
646
  return x;
640
647
  };
648
+ /**
649
+ * A sysvar or config slot: an account, or `named(account, address)`, which names `address` in the instruction's
650
+ * account list as solana_program's stake instruction builders do while handing the runtime `account` (the slot's
651
+ * account, as Rust passes it to invoke_signed): the runtime looks the address up among the CPI's accounts only, so
652
+ * a slot holding another account fails (MissingAccount), as the original does.
653
+ */
654
+ const sysvar = (i, what) => {
655
+ let n = a[i];
656
+ while (ts.isParenthesizedExpression(n))
657
+ n = n.expression;
658
+ if (ts.isCallExpression(n) && this.exportName(n.expression) === "named") {
659
+ if (n.arguments.length !== 2)
660
+ this.fail(n, "named(account, address) takes the slot's account and the address the instruction names");
661
+ const x = this.cpiAccount(n.arguments[0], what);
662
+ const k = this.expect(this.expr(n.arguments[1], PUBKEY), PUBKEY, n.arguments[1]);
663
+ const t = this.tmp("named");
664
+ this.line(`const SolPubkey *${t} = ${k.c};`);
665
+ return { ...x, named: t };
666
+ }
667
+ if (this.checker.typeToString(this.checker.getTypeAtLocation(n)) === "Pubkey")
668
+ this.fail(n, `pass ${what} as an account, or named(account, address) to name its address with the slot's account`);
669
+ return acct(i, what);
670
+ };
641
671
  const send = (tag, fields, metas, seeds) => {
642
672
  const { buf, len, put, finish } = this.byteBuffer("stk", 116, "TS_ERR_INSTRUCTION_DATA", "stake instruction");
643
673
  const t = this.tmp("tag");
@@ -646,7 +676,16 @@ export class TokenEmitter extends CreateEmitter {
646
676
  for (const f of fields)
647
677
  f(put);
648
678
  finish(node);
649
- this.cpi(`a_${program.name}`, metas.map(([x, w, sg]) => [`a_${x.name}`, w, sg]), buf, len, seeds);
679
+ if (metas.some(([x]) => x.named)) {
680
+ // Addresses named with the slot's account: the account infos are the CPI's accounts, as passed (ts_cpi_named).
681
+ const m = this.tmp("metas");
682
+ const infos = this.tmp("accts");
683
+ this.line(`SolAccountMeta ${m}[${metas.length}] = {${metas.map(([x, w, sg]) => `{${x.named ? `(SolPubkey *)${x.named}` : `&${x.c}->key`}, ${w}, ${sg}}`).join(", ")}};`);
684
+ this.line(`const TsAccount *${infos}[${metas.length}] = {${metas.map(([x]) => x.c).join(", ")}};`);
685
+ this.line(`TS_TRY(ts_cpi_named(params, ${program.c}, ${buf}, ${len}, ${m}, ${metas.length}, ${infos}, ${seeds.name}, ${seeds.count}));`);
686
+ return;
687
+ }
688
+ this.cpi(program.c, metas.map(([x, w, sg]) => [x.c, w, sg]), buf, len, seeds);
650
689
  };
651
690
  const value = (n, t) => (put) => this.serialize(this.expect(this.expr(n, t), t, n), n, put);
652
691
  const zeros = (n) => (put) => {
@@ -658,14 +697,28 @@ export class TokenEmitter extends CreateEmitter {
658
697
  if (a.length !== n && a.length !== n + 1)
659
698
  this.fail(node, usage);
660
699
  };
700
+ // signerSeeds, or an account (a lockup custodian) in the optional slot before it.
701
+ const isSeeds = (n) => !!n &&
702
+ (ts.isArrayLiteralExpression(n) ||
703
+ (ts.isIdentifier(n) && this.lookup(n.text)?.type.kind === "signerSeeds") ||
704
+ (ts.isCallExpression(n) && this.exportName(n.expression) === "signer"));
705
+ /** The optional custodian at `i` (then the seeds at i + 1), or the seeds there. */
706
+ const custodianAt = (i) => a[i] && !isSeeds(a[i]) ? { custodian: a[i], seeds: a[i + 1] } : { seeds: a[i] };
707
+ /** The lockup custodian signs too: a Signer, or a PDA of this program covered by the seeds. */
708
+ const custodian = (n, seeds) => {
709
+ const x = this.cpiAccount(n, "the lockup custodian");
710
+ if (!seeds && x.param && x.param.kind.kind !== "signer")
711
+ this.fail(n, "the custodian must be a Signer, or pass signerSeeds for a PDA custodian");
712
+ return [x, false, true];
713
+ };
661
714
  switch (method) {
662
715
  case "initialize": {
663
- // Authorized { staker, withdrawer }, Lockup { unix_timestamp, epoch, custodian }: no lockup.
664
- if (a.length !== 4)
665
- this.fail(node, "initialize(stake, rentSysvar, staker, withdrawer)");
666
- send(0, [value(a[2], PUBKEY), value(a[3], PUBKEY), zeros(48)], [
716
+ // Authorized { staker, withdrawer }, Lockup { unix_timestamp, epoch, custodian }: none, or the one given.
717
+ if (a.length !== 4 && a.length !== 5)
718
+ this.fail(node, "initialize(stake, rentSysvar, staker, withdrawer, lockup?)");
719
+ send(0, [value(a[2], PUBKEY), value(a[3], PUBKEY), a[4] ? (put) => this.stakeLockup(a[4], put) : zeros(48)], [
667
720
  [acct(0, "the stake account", true), true, false],
668
- [acct(1, "the Rent sysvar"), false, false],
721
+ [sysvar(1, "the Rent sysvar"), false, false],
669
722
  ], {
670
723
  name: "NULL",
671
724
  count: 0,
@@ -673,18 +726,24 @@ export class TokenEmitter extends CreateEmitter {
673
726
  return undefined;
674
727
  }
675
728
  case "authorize": {
676
- arity(5, 'authorize(stake, clockSysvar, authority, newAuthority, "staker" | "withdrawer", signerSeeds?)');
729
+ const usage = 'authorize(stake, clockSysvar, authority, newAuthority, "staker" | "withdrawer", custodian?, signerSeeds?)';
730
+ if (a.length < 5 || a.length > 7)
731
+ this.fail(node, usage);
677
732
  const kind = a[4];
678
733
  const i = ts.isStringLiteral(kind) ? ["staker", "withdrawer"].indexOf(kind.text) : -1;
679
734
  if (i < 0)
680
735
  this.fail(kind, 'the authority to change is "staker" or "withdrawer"');
736
+ const opt = custodianAt(5);
737
+ if (a.length === 7 && !opt.custodian)
738
+ this.fail(a[5], usage);
681
739
  const auth = acct(2, "the authority");
682
740
  const k = this.tmp("which");
683
741
  send(1, [value(a[3], PUBKEY), (put) => (this.line(`uint32_t ${k} = ${i};`), put(`&${k}`, "4", 4))], [
684
742
  [acct(0, "the stake account", true), true, false],
685
- [acct(1, "the Clock sysvar"), false, false],
743
+ [sysvar(1, "the Clock sysvar"), false, false],
686
744
  [auth, false, true],
687
- ], this.signerSeeds(a[5], auth, a[2]));
745
+ ...(opt.custodian ? [custodian(opt.custodian, opt.seeds)] : []),
746
+ ], this.signerSeeds(opt.seeds, auth, a[2]));
688
747
  return undefined;
689
748
  }
690
749
  case "delegate": {
@@ -693,36 +752,106 @@ export class TokenEmitter extends CreateEmitter {
693
752
  send(2, [], [
694
753
  [acct(0, "the stake account", true), true, false],
695
754
  [acct(1, "the vote account"), false, false],
696
- [acct(2, "the Clock sysvar"), false, false],
697
- [acct(3, "the StakeHistory sysvar"), false, false],
698
- [acct(4, "the stake config account"), false, false],
755
+ [sysvar(2, "the Clock sysvar"), false, false],
756
+ [sysvar(3, "the StakeHistory sysvar"), false, false],
757
+ [sysvar(4, "the stake config account"), false, false],
699
758
  [staker, false, true],
700
759
  ], this.signerSeeds(a[6], staker, a[5]));
701
760
  return undefined;
702
761
  }
762
+ case "split": {
763
+ arity(4, "split(stake, splitStake, authority, lamports, signerSeeds?)");
764
+ const auth = acct(2, "the staker");
765
+ send(3, [value(a[3], U64)], [
766
+ [acct(0, "the stake account", true), true, false],
767
+ [acct(1, "the split stake account", true), true, false],
768
+ [auth, false, true],
769
+ ], this.signerSeeds(a[4], auth, a[2]));
770
+ return undefined;
771
+ }
703
772
  case "deactivate": {
704
773
  arity(3, "deactivate(stake, clockSysvar, staker, signerSeeds?)");
705
774
  const staker = acct(2, "the staker");
706
775
  send(5, [], [
707
776
  [acct(0, "the stake account", true), true, false],
708
- [acct(1, "the Clock sysvar"), false, false],
777
+ [sysvar(1, "the Clock sysvar"), false, false],
709
778
  [staker, false, true],
710
779
  ], this.signerSeeds(a[3], staker, a[2]));
711
780
  return undefined;
712
781
  }
713
782
  case "withdraw": {
714
- arity(6, "withdraw(stake, to, clockSysvar, stakeHistorySysvar, withdrawer, lamports, signerSeeds?)");
783
+ const usage = "withdraw(stake, to, clockSysvar, stakeHistorySysvar, withdrawer, lamports, custodian?, signerSeeds?)";
784
+ if (a.length < 6 || a.length > 8)
785
+ this.fail(node, usage);
786
+ const opt = custodianAt(6);
787
+ if (a.length === 8 && !opt.custodian)
788
+ this.fail(a[6], usage);
715
789
  const withdrawer = acct(4, "the withdrawer");
716
790
  send(4, [value(a[5], U64)], [
717
791
  [acct(0, "the stake account", true), true, false],
718
792
  [acct(1, "the destination", true), true, false],
719
- [acct(2, "the Clock sysvar"), false, false],
720
- [acct(3, "the StakeHistory sysvar"), false, false],
793
+ [sysvar(2, "the Clock sysvar"), false, false],
794
+ [sysvar(3, "the StakeHistory sysvar"), false, false],
721
795
  [withdrawer, false, true],
722
- ], this.signerSeeds(a[6], withdrawer, a[4]));
723
- return undefined;
796
+ ...(opt.custodian ? [custodian(opt.custodian, opt.seeds)] : []),
797
+ ], this.signerSeeds(opt.seeds, withdrawer, a[4]));
798
+ return undefined;
799
+ }
800
+ case "merge": {
801
+ arity(5, "merge(destination, source, clockSysvar, stakeHistorySysvar, staker, signerSeeds?)");
802
+ const staker = acct(4, "the staker");
803
+ send(7, [], [
804
+ [acct(0, "the destination stake account", true), true, false],
805
+ [acct(1, "the source stake account", true), true, false],
806
+ [sysvar(2, "the Clock sysvar"), false, false],
807
+ [sysvar(3, "the StakeHistory sysvar"), false, false],
808
+ [staker, false, true],
809
+ ], this.signerSeeds(a[5], staker, a[4]));
810
+ return undefined;
811
+ }
812
+ case "getMinimumDelegation": {
813
+ // GetMinimumDelegation (no accounts), then the u64 the Stake program returns, read as
814
+ // solana_program::stake::tools::get_minimum_delegation reads it (and fails as it does).
815
+ if (a.length)
816
+ this.fail(node, "getMinimumDelegation() takes no arguments");
817
+ const t = this.tmp("tag");
818
+ const out = this.tmp("mindel");
819
+ const from = this.tmp("from");
820
+ const n = this.tmp("n");
821
+ const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
822
+ const fail = (code, name, why) => `TS_FAIL(((uint64_t)${code}) << 32, ${cString(typeof pre === "string" ? `${pre}${name}` : `TypeSOL: ${why}`)})`;
823
+ this.line(`uint32_t ${t} = 13;`);
824
+ this.line(`TS_TRY(ts_cpi(params, ${program.c}, (uint8_t *)&${t}, 4, NULL, 0, NULL, 0));`);
825
+ this.line(`uint64_t ${out} = 0;`);
826
+ this.line(`SolPubkey ${from};`);
827
+ this.line(`uint64_t ${n} = sol_get_return_data((uint8_t *)&${out}, 8, &${from});`);
828
+ this.line(`if (${n} == 0) ${fail(3, "InvalidInstructionData", "no minimum delegation returned")};`);
829
+ this.line(`if (!ts_key_eq(&${from}, &${program.c}->key)) ${fail(7, "IncorrectProgramId", "return data not from the Stake program")};`);
830
+ this.line(`if (${n} != 8) ${fail(3, "InvalidInstructionData", "the minimum delegation is not a u64")};`);
831
+ return { c: out, type: U64 };
724
832
  }
725
833
  }
726
- this.fail(node.expression, `the Stake program supports initialize, authorize, delegate, deactivate and withdraw, not ${method}`);
834
+ this.fail(node.expression, `the Stake program supports initialize, authorize, delegate, split, deactivate, withdraw, merge and getMinimumDelegation, not ${method}`);
835
+ }
836
+ /** A stake Lockup { unix_timestamp: i64, epoch: u64, custodian: Pubkey } from `{ unixTimestamp, epoch, custodian }`. */
837
+ stakeLockup(n, put) {
838
+ if (!ts.isObjectLiteralExpression(n))
839
+ this.fail(n, "the lockup is written { unixTimestamp, epoch, custodian }");
840
+ const props = this.literalProps(n, ["unixTimestamp", "epoch", "custodian"], "the lockup");
841
+ for (const f of ["unixTimestamp", "epoch", "custodian"])
842
+ if (!props.has(f))
843
+ this.fail(n, `the lockup needs ${f} (unixTimestamp, epoch, custodian)`);
844
+ // Evaluated in source order (as JS does), laid out in the Lockup's.
845
+ const types = { unixTimestamp: I64, epoch: U64, custodian: PUBKEY };
846
+ const held = new Map();
847
+ for (const [k, e] of props) {
848
+ const v = this.expect(this.expr(e, types[k]), types[k], e);
849
+ const t = this.tmp("lk");
850
+ this.line(k === "custodian" ? `SolPubkey ${t} = *(${v.c});` : `${k === "epoch" ? "uint64_t" : "int64_t"} ${t} = ${v.c};`);
851
+ held.set(k, t);
852
+ }
853
+ put(`&${held.get("unixTimestamp")}`, "8", 8);
854
+ put(`&${held.get("epoch")}`, "8", 8);
855
+ put(`&${held.get("custodian")}`, "32", 32);
727
856
  }
728
857
  }