@typesol/cli 0.46.0 → 0.48.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.
package/dist/testing.js CHANGED
@@ -12,16 +12,18 @@
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
- * Needs `litesvm` and `@anchor-lang/core`, which `typesol init` projects have.
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), events too.
18
19
  */
19
- import anchor from "@anchor-lang/core";
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";
22
22
  import { createHash } from "node:crypto";
23
+ import { createRequire } from "node:module";
23
24
  import path from "node:path";
24
25
  import { fileURLToPath } from "node:url";
26
+ import { IdlCoder } from "./idl-coder.js";
25
27
  import { TYPESOL_ERRORS } from "./tools/clientgen.js";
26
28
  import { loadClonedAccounts } from "./tools/clone.js";
27
29
  import { svmConnection } from "./tools/svmrpc.js";
@@ -30,8 +32,21 @@ export { svmConnection };
30
32
  export * from "./testing-stake.js";
31
33
  /** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
32
34
  export { loadClonedAccounts };
33
- // @anchor-lang/core is CommonJS: Node 22 cannot import its classes by name from an installed ES module.
34
- const { BN, BorshCoder } = anchor;
35
+ /** `new BorshCoder(idl)` from `@anchor-lang/core`, found next to typesol or in the project being tested. */
36
+ function anchorCoder(idl) {
37
+ for (const from of [import.meta.url, path.join(process.cwd(), "package.json")]) {
38
+ let anchor;
39
+ try {
40
+ // CommonJS: loaded with require, as Node cannot import its classes by name from an ES module.
41
+ anchor = createRequire(from)("@anchor-lang/core");
42
+ }
43
+ catch {
44
+ continue;
45
+ }
46
+ return new anchor.BorshCoder(idl);
47
+ }
48
+ throw new Error("t.coder is Anchor's BorshCoder: install @anchor-lang/core (npm install -D @anchor-lang/core) to use it");
49
+ }
35
50
  /**
36
51
  * An instruction's accounts with groups flattened as the generated client does: `pool.vault` becomes `pool_vault`
37
52
  * (`poolVault` in `t.ix`), and a seed naming a field of the same group names its flattened account.
@@ -51,11 +66,12 @@ function flattenAccounts(items, prefix = "") {
51
66
  }
52
67
  return out;
53
68
  }
54
- const BIG = new Set(["u64", "i64", "u128", "i128"]);
55
69
  const snake = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
56
70
  const camel = (s) => s.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
57
71
  const isSigner = (v) => typeof v === "object" && v !== null && "address" in v && "signTransactions" in v;
58
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]);
59
75
  /** Build `program` of the project around `from` (a file URL such as import.meta.url, or a directory) and load it. */
60
76
  export async function testProgram(program, from) {
61
77
  const start = typeof from === "string" && !from.startsWith("file:") ? from : path.dirname(fileURLToPath(from));
@@ -76,23 +92,44 @@ export async function testProgram(program, from) {
76
92
  }
77
93
  /** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */
78
94
  export function programHarness(svm, programId, idl) {
79
- const coder = new BorshCoder(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 });
97
+ let anchor;
80
98
  const source = idl;
81
99
  const pidl = { ...source, instructions: source.instructions.map((ix) => ({ ...ix, accounts: flattenAccounts(ix.accounts) })) };
82
100
  const types = new Map((pidl.types ?? []).map((t) => [t.name, t]));
83
101
  const enc = getAddressEncoder();
84
- /** A plain value → what the Anchor coder expects for `type`. */
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
+ };
121
+ /** A plain value → what the coder expects for `type` (integers of 64 bits and more it parses itself). */
85
122
  const toCoder = (v, type, where) => {
86
123
  if (typeof type === "string") {
87
- if (BIG.has(type))
88
- return new BN(String(v));
124
+ if (v === null || v === undefined)
125
+ throw new Error(`${where} is ${String(v)}, but it is a ${type}, not an Option`);
89
126
  if (/^[ui](8|16|32)$/.test(type))
90
127
  return Number(v);
91
128
  if (type === "pubkey") {
92
129
  const a = isSigner(v) ? v.address : v;
93
130
  if (typeof a !== "string" || !isAddress(a))
94
131
  throw new Error(`${where}: expected an address`);
95
- return { toBuffer: () => Buffer.from(enc.encode(a)) };
132
+ return a;
96
133
  }
97
134
  return v;
98
135
  }
@@ -103,47 +140,44 @@ export function programHarness(svm, programId, idl) {
103
140
  if ("array" in type)
104
141
  return v.map((x, i) => toCoder(x, type.array[0], `${where}[${i}]`));
105
142
  const def = types.get(type.defined.name);
106
- if (def?.type.kind === "struct" && def.type.fields && typeof v === "object" && v !== null) {
107
- const o = v;
108
- return Object.fromEntries(def.type.fields.map((f) => [f.name, toCoder(o[f.name] ?? o[camel(f.name)], f.type, `${where}.${f.name}`)]));
109
- }
110
- // 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);
111
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: {} }.
112
149
  const unitObject = typeof v === "object" && v !== null && Object.keys(v).length === 1 && !Object.values(v)[0];
113
150
  const emptyObject = typeof v === "object" && v !== null && Object.keys(v).length === 1 && Object.keys(Object.values(v)[0]).length === 0;
114
151
  if (def?.type.kind === "enum" && variants && (typeof v === "number" || typeof v === "bigint" || typeof v === "string" || unitObject || emptyObject)) {
115
152
  const key = typeof v === "object" ? Object.keys(v)[0] : v;
116
153
  const same = (x) => x.name === key || camel(x.name) === key || x.name.toLowerCase() === String(key).toLowerCase();
117
154
  const i = typeof key === "string" ? variants.findIndex(same) : Number(key);
118
- if (!variants[i])
155
+ const variant = variants[i];
156
+ if (!variant)
119
157
  throw new Error(`${where}: ${String(v)} is not a variant of ${type.defined.name}`);
120
- 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]: {} };
121
162
  }
122
163
  // A variant with fields, { Variant: { field: value } }: its fields converted like a struct's.
123
164
  if (def?.type.kind === "enum" && variants && typeof v === "object" && v !== null && Object.keys(v).length === 1) {
124
165
  const [key, body] = Object.entries(v)[0];
125
- const variant = variants.find((x) => x.name === key || camel(x.name) === key || x.name.toLowerCase() === key.toLowerCase());
166
+ const variant = variantOf(key);
126
167
  if (!variant)
127
168
  throw new Error(`${where}: ${key} is not a variant of ${type.defined.name}`);
128
- const fields = (variant.fields ?? []);
129
- if (fields.length && fields.every((f) => typeof f === "object" && f?.name && f.type) && typeof body === "object" && body !== null) {
130
- const o = body;
169
+ if (named(variant.fields) && typeof body === "object" && body !== null && !Array.isArray(body))
131
170
  return {
132
- [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),
133
172
  };
134
- }
135
173
  return { [variant.name]: body };
136
174
  }
137
175
  return v;
138
176
  };
139
- /** What the coder decodes → plain values (bigints, address strings), recursively. */
177
+ /** What the coder decodes (bigints, address strings) with TypeSOL's fixed-layout Options and strings unwrapped. */
140
178
  const plain = (v) => {
141
179
  if (v === null || v === undefined)
142
180
  return v;
143
- if (BN.isBN(v))
144
- return BigInt(v.toString());
145
- if (typeof v === "object" && typeof v.toBase58 === "function")
146
- return v.toBase58();
147
181
  if (Array.isArray(v))
148
182
  return v.map(plain);
149
183
  if (v instanceof Uint8Array)
@@ -228,7 +262,9 @@ export function programHarness(svm, programId, idl) {
228
262
  svm,
229
263
  programId,
230
264
  idl,
231
- coder,
265
+ get coder() {
266
+ return (anchor ??= anchorCoder(idl));
267
+ },
232
268
  async wallet(sol = 10) {
233
269
  const k = await generateKeyPairSigner();
234
270
  svm.airdrop(k.address, lamports(BigInt(Math.round(sol * 1e9))));
@@ -317,8 +353,18 @@ export function programHarness(svm, programId, idl) {
317
353
  ...(r.signer ? { signer: r.signer } : {}),
318
354
  });
319
355
  const a = args;
320
- 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)})`)]));
321
- return { programAddress: programId, accounts: metas, data: new Uint8Array(coder.instruction.encode(def.name, encoded)) };
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
+ }));
367
+ return { programAddress: programId, accounts: metas, data: new Uint8Array(coder.encodeInstruction(def.name, encoded)) };
322
368
  },
323
369
  async send(payer, ...ixs) {
324
370
  const tx = await pipe(createTransactionMessage({ version: 0 }), (t) => setTransactionMessageFeePayerSigner(payer, t), (t) => svm.setTransactionMessageLifetimeUsingLatestBlockhash(t), (t) => appendTransactionMessageInstructions(ixs, t), (t) => signTransactionMessageWithSigners(t));
@@ -403,7 +449,7 @@ export function programHarness(svm, programId, idl) {
403
449
  const a = svm.getAccount(address);
404
450
  if (!a.exists)
405
451
  return null;
406
- return plain(coder.accounts.decode(type, Buffer.from(a.data)));
452
+ return plain(coder.decodeAccount(type, Buffer.from(a.data)));
407
453
  },
408
454
  returned(instruction, res) {
409
455
  const def = pidl.instructions.find((i) => i.name === instruction || i.name === snake(instruction));
@@ -446,9 +492,44 @@ export function programHarness(svm, programId, idl) {
446
492
  return (bytes <= 4 ? Number(n) : n);
447
493
  }
448
494
  if ("defined" in t)
449
- return plain(coder.types.decode(t.defined.name, data));
495
+ return plain(coder.decodeType(t.defined.name, data));
450
496
  throw new Error(`decode ${instruction}'s return data yourself (${JSON.stringify(t)})`);
451
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
+ },
452
533
  balance(address) {
453
534
  return svm.getBalance(address) ?? 0n;
454
535
  },
package/dist/workspace.js CHANGED
@@ -363,7 +363,6 @@ export function scaffold(dir, name, template = "counter", opts = {}) {
363
363
  typesol: `npm:@typesol/cli@^${COMPILER_VERSION}`,
364
364
  "@types/node": "^22.0.0",
365
365
  typescript: "^6.0.3",
366
- "@anchor-lang/core": "^1.2.1",
367
366
  "@solana/kit": "^8.5.0",
368
367
  litesvm: "^1.6.1",
369
368
  vitest: "^5.0.5",