@typesol/cli 0.38.0 → 0.39.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 (52) hide show
  1. package/CHANGELOG.md +327 -2
  2. package/README.md +29 -15
  3. package/SECURITY.md +1 -1
  4. package/dist/compiler/analyze.d.ts +6 -11
  5. package/dist/compiler/analyze.js +323 -31
  6. package/dist/compiler/emit/alias.js +3 -2
  7. package/dist/compiler/emit/base.d.ts +5 -0
  8. package/dist/compiler/emit/base.js +2 -0
  9. package/dist/compiler/emit/borsh.js +63 -2
  10. package/dist/compiler/emit/calls.d.ts +9 -1
  11. package/dist/compiler/emit/calls.js +147 -18
  12. package/dist/compiler/emit/cpi-core.js +17 -5
  13. package/dist/compiler/emit/cpi.js +81 -27
  14. package/dist/compiler/emit/create.d.ts +7 -0
  15. package/dist/compiler/emit/create.js +27 -0
  16. package/dist/compiler/emit/expressions.js +7 -4
  17. package/dist/compiler/emit/function.d.ts +7 -0
  18. package/dist/compiler/emit/function.js +164 -29
  19. package/dist/compiler/emit/program.js +15 -2
  20. package/dist/compiler/emit/shared.d.ts +5 -5
  21. package/dist/compiler/emit/shared.js +5 -0
  22. package/dist/compiler/emit/statements.d.ts +8 -0
  23. package/dist/compiler/emit/statements.js +93 -6
  24. package/dist/compiler/emit/storage.d.ts +10 -1
  25. package/dist/compiler/emit/storage.js +50 -11
  26. package/dist/compiler/idl.d.ts +1 -1
  27. package/dist/compiler/idl.js +42 -11
  28. package/dist/compiler/model.d.ts +47 -10
  29. package/dist/compiler/model.js +14 -4
  30. package/dist/testing.js +8 -0
  31. package/dist/tools/clientgen.js +10 -1
  32. package/dist/tools/portgen.d.ts +6 -0
  33. package/dist/tools/portgen.js +68 -17
  34. package/docs/architecture.md +5 -4
  35. package/docs/audit.md +31 -19
  36. package/docs/case-study-escrow.md +5 -5
  37. package/docs/case-study-jito-mev.md +9 -5
  38. package/docs/case-study-marginfi.md +797 -0
  39. package/docs/case-study-multisig.md +3 -3
  40. package/docs/case-study-raydium-clmm.md +44 -33
  41. package/docs/case-study-raydium-cp-swap.md +3 -3
  42. package/docs/cli.md +5 -5
  43. package/docs/client.md +1 -1
  44. package/docs/errors.md +13 -5
  45. package/docs/language.md +38 -25
  46. package/docs/migrate-from-anchor.md +4 -1
  47. package/docs/runtime.md +1 -1
  48. package/docs/security-model.md +2 -1
  49. package/docs/testing.md +33 -1
  50. package/lib/typesol.d.ts +46 -9
  51. package/package.json +9 -7
  52. package/runtime/typesol_rt.h +111 -17
@@ -18,8 +18,10 @@ export class CpiEmitter extends MetaplexEmitter {
18
18
  }
19
19
  else {
20
20
  const program = this.accountParam(a[0], "invoke's program");
21
- if (program.kind.kind !== "program" && program.kind.kind !== "system" && program.kind.kind !== "tokenProgram")
22
- this.fail(a[0], 'invoke\'s program must be a Program<"address">, UncheckedProgram, SystemProgram, token program or remaining account');
21
+ // Address<A, "base58"> (Anchor's `address = ID` on an UncheckedAccount): the key is that program's; the runtime
22
+ // refuses a CPI into an account that is not executable.
23
+ if (program.kind.kind !== "program" && program.kind.kind !== "system" && program.kind.kind !== "tokenProgram" && !program.constraints.address)
24
+ this.fail(a[0], 'invoke\'s program must be a Program<"address">, UncheckedProgram, Address<A, "address">, SystemProgram, token program or remaining account');
23
25
  programKey = `&a_${program.name}->key`;
24
26
  }
25
27
  const hasSeeds = a.length === 4;
@@ -33,7 +35,7 @@ export class CpiEmitter extends MetaplexEmitter {
33
35
  for (const el of a[1].elements) {
34
36
  if (ts.isSpreadElement(el)) {
35
37
  if (!this.ix)
36
- this.fail(el, "remainingAccounts() is only available in instructions");
38
+ this.fail(el, "pass the remaining accounts to a CPI from the instruction; a helper reads them one at a time with .get(i)");
37
39
  const inner = el.expression;
38
40
  const fnName = ts.isCallExpression(inner) ? this.exportName(inner.expression) : undefined;
39
41
  const wrapped = ts.isCallExpression(inner) && (fnName === "readonly" || fnName === "writable") && inner.arguments.length === 1;
@@ -59,13 +61,17 @@ export class CpiEmitter extends MetaplexEmitter {
59
61
  parts.push({ kind: "meta", c: metas[metas.length - 1] });
60
62
  continue;
61
63
  }
62
- const acct = this.accountParam(el.arguments[0], `${fn}()'s argument`);
64
+ // An optional account as it is (no `!`): left out of the list when it was not passed (Rust's
65
+ // `if let Some(a) = &self.a { accounts.push(…) }`).
66
+ const maybe = this.accountAt(el.arguments[0]);
67
+ const skipped = !!maybe?.optional && !isS && ts.isIdentifier(el.arguments[0]);
68
+ const acct = skipped ? maybe : this.accountParam(el.arguments[0], `${fn}()'s argument`);
63
69
  if (isW && !isWritable(acct.kind))
64
70
  this.fail(el, `"${acct.name}" is not writable here; declare it Mut<...>`);
65
71
  if (isS && acct.kind.kind !== "signer" && !hasSeeds)
66
72
  this.fail(el, `"${acct.name}" did not sign; pass signerSeeds to sign for a PDA, or declare it Signer`);
67
73
  metas.push(`{&a_${acct.name}->key, ${isW}, ${isS}}`);
68
- parts.push({ kind: "meta", c: metas[metas.length - 1] });
74
+ parts.push({ kind: "meta", c: metas[metas.length - 1], when: skipped ? `a_${acct.name} != NULL` : undefined });
69
75
  }
70
76
  // The CPI's account list is built in a buffer with room for one entry per instruction account.
71
77
  if (metas.length > accountLimit(this.model))
@@ -137,9 +143,9 @@ export class CpiEmitter extends MetaplexEmitter {
137
143
  const seeds = hasSeeds && !multi ? this.signingSeeds(a[3]) : { name: "NULL", count: 0 };
138
144
  const metasName = this.tmp("metas");
139
145
  let count = String(metas.length);
140
- if (parts.some((p) => p.kind === "spread")) {
146
+ if (parts.some((p) => p.kind === "spread" || p.when)) {
141
147
  // Room for every account of the instruction (ts_invoke's scratch holds TS_MAX_ACCOUNTS records).
142
- const n = this.ix.accounts.length;
148
+ const n = this.ix ? this.ix.accounts.length : 0;
143
149
  const cnt = this.tmp("nmetas");
144
150
  this.line(`TS_METAS_ROOM(${metasName});`);
145
151
  this.line(`uint64_t ${cnt} = 0;`);
@@ -148,7 +154,7 @@ export class CpiEmitter extends MetaplexEmitter {
148
154
  this.line(`if (${total} > TS_MAX_ACCOUNTS) TS_FAIL(TS_ERR_TOO_MANY_ACCOUNTS, "TypeSOL: the CPI lists more than ${accountLimit(this.model)} accounts");`);
149
155
  for (const p of parts) {
150
156
  if (p.kind === "meta") {
151
- this.line(`${metasName}[${cnt}++] = (SolAccountMeta)${p.c};`);
157
+ this.line(`${p.when ? `if (${p.when}) ` : ""}${metasName}[${cnt}++] = (SolAccountMeta)${p.c};`);
152
158
  continue;
153
159
  }
154
160
  const i = this.tmp("ri");
@@ -287,8 +293,40 @@ export class CpiEmitter extends MetaplexEmitter {
287
293
  for (const f of s.fields)
288
294
  if (!given.has(f.name))
289
295
  this.fail(obj, `missing field "${f.name}" of ${s.name}`);
290
- for (const [name, e] of given) {
291
- const f = s.fields.find((x) => x.name === name);
296
+ // A field's bytes, staged when its value is evaluated: a nested struct written as a literal is Borsh field by field
297
+ // (its Options one byte when empty), as Anchor serializes it.
298
+ const stage = (f, e) => {
299
+ if (f.type.kind === "struct" && ts.isObjectLiteralExpression(e)) {
300
+ const sd = this.model.structs.get(f.type.name);
301
+ // Its Options and enums go out as Borsh, so the IDL describes them so; account data or arguments need it fixed.
302
+ if (sd.fields.some((x) => x.type.kind === "option" || x.type.kind === "dataEnum")) {
303
+ if (this.fixedLayoutStructs().has(sd.name))
304
+ this.fail(e, `${sd.name} has Option or enum fields and is account data or an argument (fixed layout there, Borsh in events); declare a separate struct for the event`);
305
+ sd.wire = "borsh";
306
+ }
307
+ const fields = new Map();
308
+ for (const p of e.properties) {
309
+ if (ts.isPropertyAssignment(p) && ts.isIdentifier(p.name))
310
+ fields.set(p.name.text, p.initializer);
311
+ else if (ts.isShorthandPropertyAssignment(p))
312
+ fields.set(p.name.text, p.name);
313
+ else
314
+ this.fail(p, "use plain `field: value` entries");
315
+ }
316
+ for (const k of fields.keys())
317
+ if (!sd.fields.some((x) => x.name === k))
318
+ this.fail(e, `${sd.name} has no field "${k}"`);
319
+ for (const x of sd.fields)
320
+ if (!fields.has(x.name))
321
+ this.fail(e, `missing field "${x.name}" of ${sd.name}`);
322
+ const parts = new Map();
323
+ for (const [k, v] of fields)
324
+ parts.set(k, stage(sd.fields.find((x) => x.name === k), v));
325
+ return (put) => {
326
+ for (const name of sd.declared ?? sd.fields.map((x) => x.name))
327
+ parts.get(name)(put);
328
+ };
329
+ }
292
330
  if (f.type.kind === "vec" && f.type.cap !== undefined) {
293
331
  // A FixedVec keeps its fixed layout, as in account data: u32 length, then room for N elements.
294
332
  const ft = f.type;
@@ -297,11 +335,21 @@ export class CpiEmitter extends MetaplexEmitter {
297
335
  this.line(`ts_memzero(&${t}, sizeof(${t}));`);
298
336
  this.writeAggregate({ lv: t, type: ft, writable: true }, e);
299
337
  const n = this.fieldBytes(ft);
300
- staged.set(name, (put) => put(`&${t}`, String(n), n));
301
- continue;
338
+ return (put) => put(`&${t}`, String(n), n);
302
339
  }
303
340
  if (f.type.kind === "vec") {
304
- // A Vec is Borsh: u32 length, then the elements, read from a Vec argument or account data when emitted.
341
+ // A Vec is Borsh: u32 length, then the elements, read from a Vec argument or account data when emitted. An
342
+ // Option<Vec<T>> puts a tag byte first: null, an Option<Vec<T>> argument (None or Some) or a list (Some).
343
+ const optional = f.type.optional === true;
344
+ const tag = (put, some) => {
345
+ const t = this.tmp("vt");
346
+ this.line(`uint8_t ${t} = ${some};`);
347
+ put(`&${t}`, "1", 1);
348
+ return t;
349
+ };
350
+ if (optional && e.kind === ts.SyntaxKind.NullKeyword) {
351
+ return (put) => tag(put, "0");
352
+ }
305
353
  const l = ts.isIdentifier(e) ? this.lookup(e.text) : undefined;
306
354
  const r = l?.type.kind === "vecArg" ? undefined : this.ref(e);
307
355
  const elemSize = this.fieldBytes(f.type.elem);
@@ -309,25 +357,28 @@ export class CpiEmitter extends MetaplexEmitter {
309
357
  if (!sameType(l.type.elem, f.type.elem))
310
358
  this.fail(e, `expected a ${typeName(f.type)}`);
311
359
  const c = l.c;
312
- staged.set(name, (put) => {
360
+ const maybe = l.type.optional === true;
361
+ return (put) => {
362
+ const some = optional ? tag(put, maybe ? `${c}.ptr != NULL` : "1") : undefined;
313
363
  const n = this.tmp("vl");
314
364
  this.line(`uint32_t ${n} = (uint32_t)${c}.len;`);
315
- put(`&${n}`, "4");
365
+ put(`&${n}`, some && maybe ? `(${some} ? 4 : 0)` : "4");
316
366
  put(`(const uint8_t *)${c}.ptr`, `(uint64_t)${n} * ${elemSize}`);
317
- });
367
+ };
318
368
  }
319
369
  else if (r?.vec && r.type.kind === "vec" && sameType(r.type.elem, f.type.elem)) {
320
370
  const info = r.vec;
321
- staged.set(name, (put) => {
371
+ return (put) => {
372
+ if (optional)
373
+ tag(put, "1");
322
374
  const n = this.tmp("vl");
323
375
  this.line(`uint32_t ${n} = (uint32_t)${vecCount(info)};`);
324
376
  put(`&${n}`, "4");
325
377
  put(`(const uint8_t *)${info.items}`, `(uint64_t)${n} * ${elemSize}`);
326
- });
378
+ };
327
379
  }
328
380
  else
329
- this.fail(e, `expected a ${typeName(f.type)}: a Vec argument or a list in account data`);
330
- continue;
381
+ this.fail(e, `expected a ${typeName(f.type)}: ${optional ? "null, " : ""}a Vec argument or a list in account data`);
331
382
  }
332
383
  if (f.type.kind === "option" && f.type.inner.kind === "struct")
333
384
  this.fail(obj, "Option<struct> fields are not supported in events yet");
@@ -340,7 +391,7 @@ export class CpiEmitter extends MetaplexEmitter {
340
391
  this.fail(e, `expected a ${enumName}`);
341
392
  this.line(`TSE_${enumName} ${t};`);
342
393
  this.line(`ts_memcpy(&${t}, &${src.lv}, sizeof(${t}));`);
343
- staged.set(name, (put) => this.serializeDataEnumLv(t, enumName, put));
394
+ return (put) => this.serializeDataEnumLv(t, enumName, put);
344
395
  }
345
396
  else if (vt) {
346
397
  const v = this.ownedString(this.expect(this.expr(e, vt), vt, e));
@@ -349,7 +400,7 @@ export class CpiEmitter extends MetaplexEmitter {
349
400
  else
350
401
  this.line(`${valueC(vt)} ${t} = ${v.c};`);
351
402
  const held = { c: vt.kind === "pubkey" ? `(&${t})` : t, type: vt };
352
- staged.set(name, (put) => this.serialize(held, e, put));
403
+ return (put) => this.serialize(held, e, put);
353
404
  }
354
405
  else if (f.type.kind === "fstring") {
355
406
  // Event FixedString keeps its fixed layout: u32 length + capacity bytes.
@@ -357,7 +408,7 @@ export class CpiEmitter extends MetaplexEmitter {
357
408
  const v = this.expect(this.expr(e, STRING), STRING, e);
358
409
  this.line(`TS_FStr${cap} ${t};`);
359
410
  this.line(`TS_TRY(ts_fstr_set((uint8_t *)&${t}, ${cap}, ${v.c}));`);
360
- staged.set(name, (put) => put(`&${t}`, String(4 + cap), 4 + cap));
411
+ return (put) => put(`&${t}`, String(4 + cap), 4 + cap);
361
412
  }
362
413
  else {
363
414
  const src = this.ref(e);
@@ -366,12 +417,15 @@ export class CpiEmitter extends MetaplexEmitter {
366
417
  const n = this.fieldBytes(f.type);
367
418
  this.line(`uint8_t ${t}[${n}];`);
368
419
  this.line(`ts_memcpy(${t}, &${src.lv}, ${n});`);
369
- staged.set(name, (put) => put(t, String(n), n));
420
+ return (put) => put(t, String(n), n);
370
421
  }
371
- }
422
+ };
423
+ for (const [name, e] of given)
424
+ staged.set(name, stage(s.fields.find((x) => x.name === name), e));
372
425
  this.sendEvent(s, obj, cpi, (put) => {
373
- for (const f of s.fields)
374
- staged.get(f.name)(put);
426
+ // Borsh order: as declared (the fixed layout stores growable Vecs last).
427
+ for (const name of s.declared ?? s.fields.map((f) => f.name))
428
+ staged.get(name)(put);
375
429
  });
376
430
  return undefined;
377
431
  }
@@ -36,6 +36,13 @@ export declare abstract class CreateEmitter extends CpiCoreEmitter {
36
36
  protected systemTransfer(node: ts.CallExpression): undefined;
37
37
  /** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
38
38
  protected createAccount(node: ts.CallExpression, system: AccountParam): undefined;
39
+ /**
40
+ * systemProgram.createPda(payer, account, space, owner, seeds): Anchor's `init` with `seeds`, `space` and `owner = …`
41
+ * on an `UncheckedAccount` — the PDA of this program for `seeds` (2006 otherwise), created owned by `owner`, or over
42
+ * an address someone already funded topped up, allocated and assigned. Returns the bump. Leading the body, it runs
43
+ * before the other constraints, as Anchor's `init` does.
44
+ */
45
+ protected createPda(node: ts.CallExpression): Value;
39
46
  /** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
40
47
  protected allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
41
48
  }
@@ -565,6 +565,33 @@ export class CreateEmitter extends CpiCoreEmitter {
565
565
  ], buf, len, seeds);
566
566
  return undefined;
567
567
  }
568
+ /**
569
+ * systemProgram.createPda(payer, account, space, owner, seeds): Anchor's `init` with `seeds`, `space` and `owner = …`
570
+ * on an `UncheckedAccount` — the PDA of this program for `seeds` (2006 otherwise), created owned by `owner`, or over
571
+ * an address someone already funded topped up, allocated and assigned. Returns the bump. Leading the body, it runs
572
+ * before the other constraints, as Anchor's `init` does.
573
+ */
574
+ createPda(node) {
575
+ const a = node.arguments;
576
+ if (a.length !== 5)
577
+ this.fail(node, "createPda(payer, account, space, owner, seeds)");
578
+ const payer = this.accountParam(a[0], "the payer");
579
+ if (payer.kind.kind !== "signer" || !payer.kind.mut)
580
+ this.fail(a[0], "the payer must be a Mut<Signer>");
581
+ const acct = this.accountParam(a[1], "the new account");
582
+ if (acct.kind.kind !== "info" || !isWritable(acct.kind))
583
+ this.fail(a[1], "the new account must be a Mut<AccountInfo>");
584
+ const space = this.tmp("space");
585
+ this.line(`uint64_t ${space} = ${this.expect(this.expr(a[2], U64), U64, a[2]).c};`);
586
+ const owner = this.tmp("owner");
587
+ this.line(`SolPubkey ${owner} = *(${this.expect(this.expr(a[3], PUBKEY), PUBKEY, a[3]).c});`);
588
+ const seeds = this.seeds(a[4], 1);
589
+ this.recordPda(acct, seeds.idl);
590
+ const b = this.tmp("bump");
591
+ this.line(`uint8_t ${b};`);
592
+ this.line(`TS_TRY(ts_create_pda_owned(params, a_${payer.name}, a_${acct.name}, ${seeds.name}, ${seeds.count}, &${owner}, ${space}, &${b}));`);
593
+ return { c: b, type: U8 };
594
+ }
568
595
  /** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
569
596
  allocateOrAssign(node, system, method) {
570
597
  const a = node.arguments;
@@ -179,7 +179,7 @@ export class ExpressionEmitter extends StorageEmitter {
179
179
  if (l.type.kind === "vec")
180
180
  this.fail(node, `"${node.text}" is a list; use .get(i) and .length`);
181
181
  if (l.type.kind === "remaining")
182
- return { c: "", type: l.type };
182
+ return { c: l.c, type: l.type };
183
183
  return l.type.kind === "pubkey" && !l.ptr ? { c: `(&${l.c})`, type: l.type } : { c: l.c, type: l.type };
184
184
  }
185
185
  const k = this.model.constants.get(node.text);
@@ -268,7 +268,7 @@ export class ExpressionEmitter extends StorageEmitter {
268
268
  const field = node.name.text;
269
269
  if (field === "length") {
270
270
  if (this.isRemaining(node.expression))
271
- return { c: `((uint64_t)(params->ka_num - ${this.ix.accounts.length}))`, type: U64 };
271
+ return { c: `((uint64_t)(params->ka_num - ${this.remainingBase(node.expression)}))`, type: U64 };
272
272
  const sysvar = this.instructionsParam(node.expression);
273
273
  if (sysvar) {
274
274
  this.assertUsable(sysvar, node.expression);
@@ -808,9 +808,12 @@ export class ExpressionEmitter extends StorageEmitter {
808
808
  return { c: `(a_${optionalAccount.name} ${neg ? "!=" : "=="} NULL)`, type: BOOL };
809
809
  }
810
810
  const v = this.expr(other);
811
- if (v.type.kind !== "option")
812
- this.fail(other, "only Option values can be compared with null");
813
811
  const neg = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
812
+ // An Option<Vec<T>> argument: None leaves its view's pointer NULL (a Some, empty or not, points into the data).
813
+ if (v.type.kind === "vecArg" && v.type.optional)
814
+ return { c: `((${v.c}).ptr ${neg ? "!=" : "=="} NULL)`, type: BOOL };
815
+ if (v.type.kind !== "option" && v.type.kind !== "optionArg")
816
+ this.fail(other, "only Option values can be compared with null");
814
817
  return { c: neg ? `((${v.c}).some != 0)` : `((${v.c}).some == 0)`, type: BOOL };
815
818
  }
816
819
  const isCmp = op === K.LessThanToken || op === K.LessThanEqualsToken || op === K.GreaterThanToken || op === K.GreaterThanEqualsToken;
@@ -1,3 +1,4 @@
1
+ import ts from "typescript";
1
2
  import { type AccountParam, type Instruction } from "../model.js";
2
3
  import { StatementEmitter } from "./statements.js";
3
4
  /**
@@ -7,6 +8,12 @@ import { StatementEmitter } from "./statements.js";
7
8
  export declare class FunctionEmitter extends StatementEmitter {
8
9
  emitHelper(): string;
9
10
  emitInstruction(): string;
11
+ /**
12
+ * How many statements at the start of `body` create this instruction's Init / InitIfNeeded accounts
13
+ * (`acct.create(…)`, `acct.createIfNeeded(…)`, `systemProgram.createPda(…)`, alone, as a const's value or assigned). 0 when none do, or when one reads a
14
+ * bump the constraint checks find (`acct.pdaBump` of a Seeds account), which must run first.
15
+ */
16
+ protected leadingCreates(ix: Instruction, body: readonly ts.Statement[]): number;
10
17
  /** CloseTo<…> accounts are closed when the instruction succeeds, at every return. */
11
18
  protected epilogue(): string[];
12
19
  /**