@typesol/cli 0.47.0 → 0.49.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 (53) hide show
  1. package/CHANGELOG.md +299 -0
  2. package/NOTICE +17 -0
  3. package/README.md +106 -37
  4. package/SECURITY.md +5 -0
  5. package/dist/compiler/emit/base.d.ts +12 -4
  6. package/dist/compiler/emit/base.js +19 -5
  7. package/dist/compiler/emit/calls.js +59 -1
  8. package/dist/compiler/emit/cpi.js +3 -1
  9. package/dist/compiler/emit/expressions.js +3 -1
  10. package/dist/compiler/emit/function.js +7 -2
  11. package/dist/compiler/emit/program.js +9 -4
  12. package/dist/compiler/emit/statements.d.ts +29 -2
  13. package/dist/compiler/emit/statements.js +149 -6
  14. package/dist/compiler/emit/storage.js +8 -3
  15. package/dist/compiler/emit/token.js +18 -1
  16. package/dist/compiler/hints.js +3 -0
  17. package/dist/compiler/toolchain.js +1 -0
  18. package/dist/idl-coder.d.ts +21 -2
  19. package/dist/idl-coder.js +42 -4
  20. package/dist/testing.d.ts +14 -3
  21. package/dist/testing.js +87 -17
  22. package/docker/deps/0.48.0.lock.json +1206 -0
  23. package/docker/deps/0.49.0.lock.json +1206 -0
  24. package/docs/architecture.md +2 -2
  25. package/docs/audit.md +31 -15
  26. package/docs/case-study-escrow.md +7 -5
  27. package/docs/case-study-marginfi.md +15 -2
  28. package/docs/case-study-multisig.md +2 -1
  29. package/docs/case-study-raydium-amm.md +2 -1
  30. package/docs/case-study-spl-stake-pool.md +4 -3
  31. package/docs/language-accounts.md +5 -6
  32. package/docs/language-basics.md +2 -1
  33. package/docs/language-builtins.md +5 -1
  34. package/docs/language-chain.md +13 -1
  35. package/docs/language-cpi.md +26 -0
  36. package/docs/language-errors-events.md +16 -1
  37. package/docs/language-native.md +23 -3
  38. package/docs/language-statements.md +4 -2
  39. package/docs/language.md +2 -2
  40. package/docs/mainnet.md +1 -1
  41. package/docs/runtime.md +7 -0
  42. package/docs/security-model.md +11 -4
  43. package/docs/stability.md +9 -4
  44. package/docs/test-your-program.md +43 -4
  45. package/docs/testing.md +16 -4
  46. package/docs/troubleshooting.md +1 -1
  47. package/lib/typesol.d.ts +46 -1
  48. package/llms-full.txt +164 -34
  49. package/llms.txt +2 -1
  50. package/package.json +3 -3
  51. package/releases/0.47.0.json +837 -0
  52. package/releases/0.48.0.json +847 -0
  53. package/runtime/typesol_rt.h +276 -1
package/dist/idl-coder.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * A Borsh coder driven by an Anchor IDL (spec 0.1.0): instruction data, account data and the IDL's defined types.
3
- * `typesol/testing` encodes arguments and decodes accounts and return data with it.
2
+ * A Borsh coder driven by an Anchor IDL (spec 0.1.0): instruction data, account data, events and the IDL's defined
3
+ * types. `typesol/testing` encodes arguments and decodes accounts, return data and events with it.
4
4
  *
5
5
  * It reads the IDL as Anchor's TypeScript `BorshCoder` does (test/client/idl-coder.test.ts compares the two byte for
6
6
  * byte): the discriminators are the IDL's own, `serialization` and `repr` do not change the layout (account data is read
@@ -13,6 +13,10 @@
13
13
  * struct). An enum: `{ Variant: { field: value } }` (`{ Variant: {} }` for a variant without fields).
14
14
  *
15
15
  * A type the IDL can name but this coder does not handle (`coption`) fails when the coder is made, naming the type.
16
+ *
17
+ * By default a struct field or argument left undefined is written as zeros when its size is fixed, and keys that name
18
+ * no field are ignored, as Anchor's coder does. With `{ strict: true }` (what `typesol/testing` uses) both are errors
19
+ * naming the field; an Option may still be left out (None).
16
20
  */
17
21
  import { getAddressDecoder, getAddressEncoder, isAddress } from "@solana/kit";
18
22
  const INTS = {
@@ -71,9 +75,12 @@ export class IdlCoder {
71
75
  types;
72
76
  instructions;
73
77
  accountDefs;
78
+ eventDefs;
79
+ strict;
74
80
  enc = getAddressEncoder();
75
81
  dec = getAddressDecoder();
76
- constructor(idl) {
82
+ constructor(idl, options = {}) {
83
+ this.strict = options.strict ?? false;
77
84
  const types = (idl.types ?? []);
78
85
  this.types = new Map(types.map((t) => [t.name, t]));
79
86
  // Every layout is checked now, as Anchor's coder builds them all when it is made.
@@ -92,6 +99,15 @@ export class IdlCoder {
92
99
  this.check(type, NO_ENV, [], false, acc.name);
93
100
  return [acc.name, { discriminator: Buffer.from(acc.discriminator), type }];
94
101
  }));
102
+ if (idl.events?.length && !idl.types)
103
+ throw new Error("Events require `idl.types`");
104
+ this.eventDefs = (idl.events ?? []).map((ev) => {
105
+ if (!this.types.has(ev.name))
106
+ throw new Error(`Event not found: ${ev.name}`);
107
+ const type = { defined: { name: ev.name } };
108
+ this.check(type, NO_ENV, [], false, ev.name);
109
+ return [ev.name, { discriminator: Buffer.from(ev.discriminator), type }];
110
+ });
95
111
  for (const t of types)
96
112
  if (!t.generics?.length)
97
113
  this.check({ defined: { name: t.name } }, NO_ENV, [], false, t.name);
@@ -319,12 +335,17 @@ export class IdlCoder {
319
335
  }
320
336
  /**
321
337
  * A struct's fields in order. A field left undefined is written as zeros when its size is fixed (what Anchor's coder
322
- * does); a variable-size one cannot be, and throws.
338
+ * does); a variable-size one cannot be, and throws. Strict: a missing field that is not an Option, and a key that
339
+ * names no field, throw.
323
340
  */
324
341
  fields(w, fields, v, env, where) {
325
342
  if (fields.length && (typeof v !== "object" || v === null))
326
343
  throw new TypeError(`${where}: expected an object with ${fields.map((f) => f.name).join(", ")}`);
327
344
  const o = v;
345
+ if (this.strict && typeof o === "object" && o !== null)
346
+ for (const k of Object.keys(o))
347
+ if (!fields.some((f) => f.name === k))
348
+ throw new Error(`${where}: no field "${k}" (${fields.length ? `the fields are ${fields.map((f) => f.name).join(", ")}` : "it has no fields"})`);
328
349
  for (const f of fields) {
329
350
  const x = o[f.name];
330
351
  if (x === undefined) {
@@ -336,6 +357,8 @@ export class IdlCoder {
336
357
  this.write(w, f.type, null, env, `${where}.${f.name}`);
337
358
  continue;
338
359
  }
360
+ if (this.strict)
361
+ throw new Error(`${where}.${f.name}: missing (only an Option may be left out)`);
339
362
  const n = this.fixedSize(f.type, env);
340
363
  if (n === undefined)
341
364
  throw new Error(`${where}.${f.name}: missing`);
@@ -356,6 +379,10 @@ export class IdlCoder {
356
379
  const missing = ix.args.filter((a) => !isOption(a.type) && !Object.prototype.hasOwnProperty.call(args, a.name)).map((a) => `\`${a.name}\``);
357
380
  if (missing.length)
358
381
  throw new Error(`Invalid arguments for instruction "${name}": missing field${missing.length > 1 ? "s" : ""} ${missing.join(", ")}.`);
382
+ if (this.strict && args !== null && typeof args === "object")
383
+ for (const k of Object.keys(args))
384
+ if (!ix.args.some((a) => a.name === k))
385
+ throw new Error(`Invalid arguments for instruction "${name}": no argument \`${k}\` (${ix.args.length ? `it takes ${ix.args.map((a) => a.name).join(", ")}` : "it takes none"})`);
359
386
  const w = new Writer();
360
387
  w.bytes(ix.discriminator);
361
388
  this.fields(w, ix.args, args ?? {}, NO_ENV, name);
@@ -516,6 +543,17 @@ export class IdlCoder {
516
543
  const b = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
517
544
  return this.read(b, 0, { defined: { name } }, NO_ENV, name)[0];
518
545
  }
546
+ /**
547
+ * An event's name and fields from its bytes (the discriminator, then the fields), as Anchor's `coder.events.decode`
548
+ * gives them from the same bytes in base64; null when the bytes start with none of the IDL's event discriminators.
549
+ */
550
+ decodeEvent(data) {
551
+ const b = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
552
+ for (const [name, ev] of this.eventDefs)
553
+ if (ev.discriminator.equals(b.subarray(0, ev.discriminator.length)))
554
+ return { name, data: this.read(b, ev.discriminator.length, ev.type, NO_ENV, name)[0] };
555
+ return null;
556
+ }
519
557
  /** An instruction's arguments read back from its data (after checking the discriminator). */
520
558
  decodeInstruction(name, data) {
521
559
  const ix = this.instructions.get(name);
package/dist/testing.d.ts CHANGED
@@ -12,10 +12,10 @@
12
12
  * come from the IDL, as Anchor's `.accounts({...})` does, and PDAs seeded by constants, arguments or other accounts'
13
13
  * keys are derived when left out. Arguments take plain values: bigints or numbers for
14
14
  * integers, address strings for Pubkeys, null for an empty Option. Decoded accounts and return data come back the
15
- * same way (bigints, address strings).
15
+ * same way (bigints, address strings), and so do the events of a transaction (`t.events(res)`).
16
16
  *
17
17
  * Needs `litesvm`, which `typesol init` projects have. Instruction data, accounts and return data are encoded and
18
- * decoded from the IDL by TypeSOL's own Borsh coder (src/idl-coder.ts).
18
+ * decoded from the IDL by TypeSOL's own Borsh coder (src/idl-coder.ts), events too.
19
19
  */
20
20
  import { type Address, type Instruction, type KeyPairSigner } from "@solana/kit";
21
21
  import { FailedTransactionMetadata, LiteSVM, TransactionMetadata } from "litesvm";
@@ -43,7 +43,10 @@ export interface TestIdl {
43
43
  name: string;
44
44
  discriminator: readonly number[];
45
45
  }[];
46
- events?: readonly unknown[];
46
+ events?: readonly {
47
+ name: string;
48
+ discriminator: readonly number[];
49
+ }[];
47
50
  errors?: readonly {
48
51
  code: number;
49
52
  name: string;
@@ -99,6 +102,14 @@ export interface TestProgram {
99
102
  account<T = Record<string, unknown>>(type: string, address: Address): Promise<T | null>;
100
103
  /** A successful instruction's return data, decoded by its IDL `returns` type. */
101
104
  returned<T = unknown>(instruction: string, res: Result): T;
105
+ /**
106
+ * The events a successful transaction emitted, decoded by the IDL, in the order the program emitted them: `emit`'s
107
+ * `Program data:` log lines while this program runs, and `emitCpi`'s self-CPIs. Values as `account` gives them.
108
+ */
109
+ events<T = Record<string, unknown>>(res: Result): {
110
+ name: string;
111
+ data: T;
112
+ }[];
102
113
  /** Lamports of any account (0 when it does not exist). */
103
114
  balance(address: Address): bigint;
104
115
  /** A kit RPC and subscriptions pair over this LiteSVM, for the generated client (`svmConnection`). */
package/dist/testing.js CHANGED
@@ -12,10 +12,10 @@
12
12
  * come from the IDL, as Anchor's `.accounts({...})` does, and PDAs seeded by constants, arguments or other accounts'
13
13
  * keys are derived when left out. Arguments take plain values: bigints or numbers for
14
14
  * integers, address strings for Pubkeys, null for an empty Option. Decoded accounts and return data come back the
15
- * same way (bigints, address strings).
15
+ * same way (bigints, address strings), and so do the events of a transaction (`t.events(res)`).
16
16
  *
17
17
  * Needs `litesvm`, which `typesol init` projects have. Instruction data, accounts and return data are encoded and
18
- * decoded from the IDL by TypeSOL's own Borsh coder (src/idl-coder.ts).
18
+ * decoded from the IDL by TypeSOL's own Borsh coder (src/idl-coder.ts), events too.
19
19
  */
20
20
  import { AccountRole, appendTransactionMessageInstructions, createTransactionMessage, generateKeyPairSigner, getAddressDecoder, getAddressEncoder, getProgramDerivedAddress, isAddress, isOffCurveAddress, lamports, pipe, setTransactionMessageFeePayerSigner, signTransactionMessageWithSigners, } from "@solana/kit";
21
21
  import { FailedTransactionMetadata, LiteSVM } from "litesvm";
@@ -70,6 +70,8 @@ const snake = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
70
70
  const camel = (s) => s.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
71
71
  const isSigner = (v) => typeof v === "object" && v !== null && "address" in v && "signTransactions" in v;
72
72
  const TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
73
+ /** The first 8 bytes of Anchor's event instruction (sha256("anchor:event")[..8]), which `emitCpi` sends to the program. */
74
+ const EVENT_IX_TAG = Buffer.from([0xe4, 0x45, 0xa5, 0x2e, 0x51, 0xcb, 0x9a, 0x1d]);
73
75
  /** Build `program` of the project around `from` (a file URL such as import.meta.url, or a directory) and load it. */
74
76
  export async function testProgram(program, from) {
75
77
  const start = typeof from === "string" && !from.startsWith("file:") ? from : path.dirname(fileURLToPath(from));
@@ -90,15 +92,37 @@ export async function testProgram(program, from) {
90
92
  }
91
93
  /** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */
92
94
  export function programHarness(svm, programId, idl) {
93
- const coder = new IdlCoder(idl);
95
+ // Strict: an argument or field left out (other than an Option) or misspelt is an error, not zeros or None.
96
+ const coder = new IdlCoder(idl, { strict: true });
94
97
  let anchor;
95
98
  const source = idl;
96
99
  const pidl = { ...source, instructions: source.instructions.map((ix) => ({ ...ix, accounts: flattenAccounts(ix.accounts) })) };
97
100
  const types = new Map((pidl.types ?? []).map((t) => [t.name, t]));
98
101
  const enc = getAddressEncoder();
102
+ const isOption = (type) => typeof type === "object" && "option" in type;
103
+ /** The value of `name` in `o`, by its IDL name or its camelCase spelling. */
104
+ const valueOf = (o, name) => (Object.prototype.hasOwnProperty.call(o, name) ? o[name] : o[camel(name)]);
105
+ /**
106
+ * A struct's or data variant's fields from a plain object, converted: each field by its IDL name or camelCase. A key
107
+ * that names no field, and a field left out that is not an Option, are errors naming them.
108
+ */
109
+ const fieldsToCoder = (o, fields, where, owner) => {
110
+ const names = fields.map((f) => camel(f.name)).join(", ");
111
+ for (const k of Object.keys(o))
112
+ if (!fields.some((f) => f.name === k || camel(f.name) === k))
113
+ throw new Error(`${where} has no field "${k}" (${owner} has ${names || "no fields"})`);
114
+ return Object.fromEntries(fields.map((f) => {
115
+ const x = valueOf(o, f.name);
116
+ if (x === undefined && !isOption(f.type))
117
+ throw new Error(`${where}.${camel(f.name)} is missing (${owner} has ${names}; only an Option may be left out)`);
118
+ return [f.name, toCoder(x, f.type, `${where}.${camel(f.name)}`)];
119
+ }));
120
+ };
99
121
  /** A plain value → what the coder expects for `type` (integers of 64 bits and more it parses itself). */
100
122
  const toCoder = (v, type, where) => {
101
123
  if (typeof type === "string") {
124
+ if (v === null || v === undefined)
125
+ throw new Error(`${where} is ${String(v)}, but it is a ${type}, not an Option`);
102
126
  if (/^[ui](8|16|32)$/.test(type))
103
127
  return Number(v);
104
128
  if (type === "pubkey") {
@@ -116,35 +140,36 @@ export function programHarness(svm, programId, idl) {
116
140
  if ("array" in type)
117
141
  return v.map((x, i) => toCoder(x, type.array[0], `${where}[${i}]`));
118
142
  const def = types.get(type.defined.name);
119
- if (def?.type.kind === "struct" && def.type.fields && typeof v === "object" && v !== null) {
120
- const o = v;
121
- return Object.fromEntries(def.type.fields.map((f) => [f.name, toCoder(o[f.name] ?? o[camel(f.name)], f.type, `${where}.${f.name}`)]));
122
- }
123
- // A unit enum as its index or variant name, as well as Anchor's { Variant: {} }.
143
+ const named = (fields) => !!fields?.length && fields.every((f) => typeof f === "object" && f !== null && f.name && f.type);
144
+ if (def?.type.kind === "struct" && named(def.type.fields) && typeof v === "object" && v !== null && !Array.isArray(v))
145
+ return fieldsToCoder(v, def.type.fields, where, def.name);
124
146
  const variants = def?.type?.variants;
147
+ const variantOf = (key) => variants?.find((x) => x.name === key || camel(x.name) === key || x.name.toLowerCase() === String(key).toLowerCase());
148
+ // A unit enum as its index or variant name, as well as Anchor's { Variant: {} }.
125
149
  const unitObject = typeof v === "object" && v !== null && Object.keys(v).length === 1 && !Object.values(v)[0];
126
150
  const emptyObject = typeof v === "object" && v !== null && Object.keys(v).length === 1 && Object.keys(Object.values(v)[0]).length === 0;
127
151
  if (def?.type.kind === "enum" && variants && (typeof v === "number" || typeof v === "bigint" || typeof v === "string" || unitObject || emptyObject)) {
128
152
  const key = typeof v === "object" ? Object.keys(v)[0] : v;
129
153
  const same = (x) => x.name === key || camel(x.name) === key || x.name.toLowerCase() === String(key).toLowerCase();
130
154
  const i = typeof key === "string" ? variants.findIndex(same) : Number(key);
131
- if (!variants[i])
155
+ const variant = variants[i];
156
+ if (!variant)
132
157
  throw new Error(`${where}: ${String(v)} is not a variant of ${type.defined.name}`);
133
- return { [variants[i].name]: {} };
158
+ // A variant that has fields, named without them: an error naming the first, as for a struct.
159
+ if (named(variant.fields))
160
+ return { [variant.name]: fieldsToCoder({}, variant.fields, `${where}.${variant.name}`, variant.name) };
161
+ return { [variant.name]: {} };
134
162
  }
135
163
  // A variant with fields, { Variant: { field: value } }: its fields converted like a struct's.
136
164
  if (def?.type.kind === "enum" && variants && typeof v === "object" && v !== null && Object.keys(v).length === 1) {
137
165
  const [key, body] = Object.entries(v)[0];
138
- const variant = variants.find((x) => x.name === key || camel(x.name) === key || x.name.toLowerCase() === key.toLowerCase());
166
+ const variant = variantOf(key);
139
167
  if (!variant)
140
168
  throw new Error(`${where}: ${key} is not a variant of ${type.defined.name}`);
141
- const fields = (variant.fields ?? []);
142
- if (fields.length && fields.every((f) => typeof f === "object" && f?.name && f.type) && typeof body === "object" && body !== null) {
143
- const o = body;
169
+ if (named(variant.fields) && typeof body === "object" && body !== null && !Array.isArray(body))
144
170
  return {
145
- [variant.name]: Object.fromEntries(fields.map((f) => [f.name, toCoder(o[f.name] ?? o[camel(f.name)], f.type, `${where}.${variant.name}.${f.name}`)])),
171
+ [variant.name]: fieldsToCoder(body, variant.fields, `${where}.${variant.name}`, variant.name),
146
172
  };
147
- }
148
173
  return { [variant.name]: body };
149
174
  }
150
175
  return v;
@@ -328,7 +353,17 @@ export function programHarness(svm, programId, idl) {
328
353
  ...(r.signer ? { signer: r.signer } : {}),
329
354
  });
330
355
  const a = args;
331
- const encoded = Object.fromEntries(def.args.map((x) => [x.name, toCoder(a[x.name] ?? a[camel(x.name)], x.type, `${def.name}(${camel(x.name)})`)]));
356
+ // Every key names an argument, and every argument but an Option is given: a misspelt one is not sent as zeros.
357
+ const takes = def.args.length ? `it takes ${def.args.map((x) => camel(x.name)).join(", ")}` : "it takes no arguments";
358
+ for (const k of Object.keys(a))
359
+ if (!def.args.some((x) => x.name === k || camel(x.name) === k))
360
+ throw new Error(`${def.name} has no argument "${k}" (${takes})`);
361
+ const encoded = Object.fromEntries(def.args.map((x) => {
362
+ const v = valueOf(a, x.name);
363
+ if (v === undefined && !isOption(x.type))
364
+ throw new Error(`${def.name}: argument "${camel(x.name)}" is missing (${takes}; only an Option may be left out)`);
365
+ return [x.name, toCoder(v, x.type, `${def.name}(${camel(x.name)})`)];
366
+ }));
332
367
  return { programAddress: programId, accounts: metas, data: new Uint8Array(coder.encodeInstruction(def.name, encoded)) };
333
368
  },
334
369
  async send(payer, ...ixs) {
@@ -460,6 +495,41 @@ export function programHarness(svm, programId, idl) {
460
495
  return plain(coder.decodeType(t.defined.name, data));
461
496
  throw new Error(`decode ${instruction}'s return data yourself (${JSON.stringify(t)})`);
462
497
  },
498
+ events(res) {
499
+ const done = harness.ok(res);
500
+ // Every inner instruction of the transaction, in order. Not looked up by the top-level instruction's index:
501
+ // a precompile (Ed25519, Secp256k1) is an instruction that logs no invoke line.
502
+ const inner = done.innerInstructions().flat();
503
+ const found = [];
504
+ const add = (bytes) => {
505
+ const e = coder.decodeEvent(bytes);
506
+ if (e)
507
+ found.push({ name: e.name, data: plain(e.data) });
508
+ };
509
+ // The logs name every program invoked, in order: an `invoke` line deeper than [1] is the next inner instruction
510
+ // (where an emitCpi event is). A data line is this program's while it runs innermost.
511
+ const running = [];
512
+ let next = 0;
513
+ for (const line of done.logs()) {
514
+ const invoke = /^Program (\S+) invoke \[(\d+)\]$/.exec(line);
515
+ if (invoke) {
516
+ if (invoke[2] !== "1") {
517
+ const data = inner[next++]?.instruction().data();
518
+ if (invoke[1] === programId && data && data.length >= 8 && EVENT_IX_TAG.equals(data.subarray(0, 8)))
519
+ add(data.subarray(8));
520
+ }
521
+ running.push(invoke[1]);
522
+ continue;
523
+ }
524
+ if (/^Program \S+ (success$|failed)/.test(line)) {
525
+ running.pop();
526
+ continue;
527
+ }
528
+ if (running.at(-1) === programId && line.startsWith("Program data: "))
529
+ add(Buffer.from(line.slice("Program data: ".length), "base64"));
530
+ }
531
+ return found;
532
+ },
463
533
  balance(address) {
464
534
  return svm.getBalance(address) ?? 0n;
465
535
  },