@typesol/cli 0.46.0 → 0.47.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/CHANGELOG.md CHANGED
@@ -6,6 +6,29 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.47.0 — 2026-11-13
10
+
11
+ A minor release: it removes an optional peer dependency (`@anchor-lang/core`) and changes what `t.coder` of
12
+ `typesol/testing` needs. Compiled programs do not change: every program builds to the same bytes as with 0.46.0.
13
+
14
+ - Changed: `typesol init` no longer adds `@anchor-lang/core` to a project's `devDependencies`, and `@typesol/cli` no
15
+ longer lists it as an optional peer dependency. `typesol/testing` used that package (and through it Solana web3.js
16
+ 1.x) only to encode instruction arguments and decode accounts and return data; it now does both with its own Borsh
17
+ coder, read from the IDL as Anchor's `BorshCoder` reads it (test/client/idl-coder.test.ts compares the two on random
18
+ values for every example, template and shape program). A new project's `npm install` adds 96 packages instead of 156
19
+ and reports 0 vulnerabilities instead of 7 (4 moderate, 3 high). Existing projects can remove `@anchor-lang/core`
20
+ from `devDependencies` after upgrading, unless their tests import it or read `t.coder`. Compiled programs and IDLs
21
+ do not change.
22
+ - Changed: `t.coder` is still Anchor's `BorshCoder`, now loaded from `@anchor-lang/core` the first time it is read; it
23
+ throws an error saying to install the package when it is missing. `TestProgram.idl` and `programHarness`'s `idl`
24
+ parameter are typed with `TestIdl`, a structural type an Anchor `Idl` satisfies, and `t.coder` with
25
+ `AnchorBorshCoder`.
26
+ - Changed: an integer of 64 bits or more outside its type's range now fails with an error naming the argument; Anchor's
27
+ coder wrote it wrong (a negative `u64` as its absolute value, `2n ** 63n` as an `i64` as that type's minimum). A
28
+ missing argument of variable size (a string, a Vec) fails with an error naming it instead of a buffer offset error.
29
+ `bytes` arguments also take a `Uint8Array` or a `number[]` (Anchor's coder took only a Buffer), and instruction data
30
+ is no longer limited to 1,000 bytes.
31
+
9
32
  ## 0.46.0 — 2026-11-13
10
33
 
11
34
  A minor release: it adds a flag (`init --no-agent-files`) and an export of `typesol/compiler` (`typescriptMessage`),
package/README.md CHANGED
@@ -207,9 +207,8 @@ and runs it in LiteSVM, an in-process Solana runtime. `build` writes `target/cou
207
207
  IDL), `counter.client.ts` and `counter.build.json`.
208
208
 
209
209
  `init` also writes rules and an MCP server config for AI coding agents (AGENTS.md, CLAUDE.md, `.cursor/`, `.mcp.json`)
210
- and lists them; `--no-agent-files` leaves them out. `npm install` reports advisories (moderate and high) and packages
211
- with install scripts: they come from `@anchor-lang/core` and the Solana web3.js it depends on, which `typesol/testing`
212
- uses to encode instructions and decode accounts, so the tests need it; none of it is in the program you deploy.
210
+ and lists them; `--no-agent-files` leaves them out. `typesol/testing` encodes instructions and decodes accounts from
211
+ the IDL itself, so a new project installs neither Anchor's TypeScript package nor Solana web3.js 1.x.
213
212
 
214
213
  Other versions work, but their binaries are not covered by the project's tests: `typesol build` warns once when the
215
214
  clang is another one (`--toolchain-strict` or `TYPESOL_TOOLCHAIN=strict` makes that an error), and every build records
@@ -0,0 +1,110 @@
1
+ export type IdlTypeSpec = string | {
2
+ option: IdlTypeSpec;
3
+ } | {
4
+ coption: IdlTypeSpec;
5
+ } | {
6
+ vec: IdlTypeSpec;
7
+ } | {
8
+ array: [IdlTypeSpec, number | {
9
+ generic: string;
10
+ }];
11
+ } | {
12
+ defined: {
13
+ name: string;
14
+ generics?: IdlGenericArg[];
15
+ };
16
+ } | {
17
+ generic: string;
18
+ };
19
+ export type IdlGenericArg = {
20
+ kind: "type";
21
+ type: IdlTypeSpec;
22
+ } | {
23
+ kind: "const";
24
+ value: string;
25
+ };
26
+ export type IdlFieldsSpec = {
27
+ name: string;
28
+ type: IdlTypeSpec;
29
+ }[] | IdlTypeSpec[];
30
+ export interface IdlTypeDefSpec {
31
+ name: string;
32
+ generics?: ({
33
+ kind: "type";
34
+ name: string;
35
+ } | {
36
+ kind: "const";
37
+ name: string;
38
+ type?: string;
39
+ })[];
40
+ type: {
41
+ kind: "struct";
42
+ fields?: IdlFieldsSpec;
43
+ } | {
44
+ kind: "enum";
45
+ variants: {
46
+ name: string;
47
+ fields?: IdlFieldsSpec;
48
+ }[];
49
+ } | {
50
+ kind: "type";
51
+ alias: IdlTypeSpec;
52
+ };
53
+ }
54
+ /** The parts of an IDL the coder reads. */
55
+ export interface CoderIdl {
56
+ instructions: readonly {
57
+ name: string;
58
+ discriminator: readonly number[];
59
+ args: readonly {
60
+ name: string;
61
+ type: unknown;
62
+ }[];
63
+ }[];
64
+ accounts?: readonly {
65
+ name: string;
66
+ discriminator: readonly number[];
67
+ }[];
68
+ types?: readonly unknown[];
69
+ }
70
+ export declare class IdlCoder {
71
+ private readonly types;
72
+ private readonly instructions;
73
+ private readonly accountDefs;
74
+ private readonly enc;
75
+ private readonly dec;
76
+ constructor(idl: CoderIdl);
77
+ private resolve;
78
+ private arrayLen;
79
+ /** A defined type and the environment its fields are read in. */
80
+ private definition;
81
+ /** Throws for a shape the coder cannot read, naming it. A type may only contain itself inside an option or vec. */
82
+ private check;
83
+ /** The type's size when every value of it has the same size (as Anchor's layouts give a span), else undefined. */
84
+ private fixedSize;
85
+ private bigint;
86
+ private pubkey;
87
+ private write;
88
+ private items;
89
+ /**
90
+ * A struct's fields in order. A field left undefined is written as zeros when its size is fixed (what Anchor's coder
91
+ * does); a variable-size one cannot be, and throws.
92
+ */
93
+ private fields;
94
+ /** Instruction data: the IDL's discriminator, then the arguments. */
95
+ encodeInstruction(name: string, args: Record<string, unknown>): Buffer;
96
+ /** Account data: the discriminator, then the account's fields. */
97
+ encodeAccount(name: string, value: unknown): Buffer;
98
+ /** A defined type's bytes. */
99
+ encodeType(name: string, value: unknown): Buffer;
100
+ private need;
101
+ /** The value of `type` at `at`, and the offset after it. */
102
+ private read;
103
+ private readFields;
104
+ /** An account's fields, after checking its discriminator. Bytes after the fields are ignored. */
105
+ decodeAccount(name: string, data: Uint8Array): Record<string, unknown>;
106
+ /** A defined type read from the start of `data`. Bytes after it are ignored. */
107
+ decodeType(name: string, data: Uint8Array): unknown;
108
+ /** An instruction's arguments read back from its data (after checking the discriminator). */
109
+ decodeInstruction(name: string, data: Uint8Array): Record<string, unknown>;
110
+ }
@@ -0,0 +1,529 @@
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.
4
+ *
5
+ * It reads the IDL as Anchor's TypeScript `BorshCoder` does (test/client/idl-coder.test.ts compares the two byte for
6
+ * byte): the discriminators are the IDL's own, `serialization` and `repr` do not change the layout (account data is read
7
+ * field after field), and Options, Vecs, strings and enums are Borsh's. Values:
8
+ *
9
+ * - u8 to u32, i8 to i32, f32, f64: numbers. u64 and wider: bigints (a number or a decimal string is taken too).
10
+ * - bool: a boolean. pubkey: an address string (32 bytes are taken too).
11
+ * - string: a string. bytes: a Buffer (a Uint8Array or a number[] is taken too).
12
+ * - option: null for None. vec and array: arrays. A struct: an object by the IDL's field names ("0", "1"… for a tuple
13
+ * struct). An enum: `{ Variant: { field: value } }` (`{ Variant: {} }` for a variant without fields).
14
+ *
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
+ import { getAddressDecoder, getAddressEncoder, isAddress } from "@solana/kit";
18
+ const INTS = {
19
+ u8: { bytes: 1, signed: false },
20
+ i8: { bytes: 1, signed: true },
21
+ u16: { bytes: 2, signed: false },
22
+ i16: { bytes: 2, signed: true },
23
+ u32: { bytes: 4, signed: false },
24
+ i32: { bytes: 4, signed: true },
25
+ };
26
+ const BIGS = {
27
+ u64: { bytes: 8, signed: false },
28
+ i64: { bytes: 8, signed: true },
29
+ u128: { bytes: 16, signed: false },
30
+ i128: { bytes: 16, signed: true },
31
+ u256: { bytes: 32, signed: false },
32
+ i256: { bytes: 32, signed: true },
33
+ };
34
+ const FIXED = { bool: 1, f32: 4, f64: 8, pubkey: 32 };
35
+ for (const [k, v] of Object.entries({ ...INTS, ...BIGS }))
36
+ FIXED[k] = v.bytes;
37
+ const NO_ENV = new Map();
38
+ const describe = (t) => (typeof t === "string" ? t : JSON.stringify(t));
39
+ /** Named fields of a struct or variant, or a tuple's fields named "0", "1"… (as Anchor's coder names them). */
40
+ function fieldsOf(fields) {
41
+ if (!fields?.length)
42
+ return [];
43
+ if (typeof fields[0] === "object" && fields[0] !== null && "name" in fields[0] && fields[0].name)
44
+ return fields;
45
+ return fields.map((type, i) => ({ name: String(i), type }));
46
+ }
47
+ class Writer {
48
+ buf = Buffer.alloc(256);
49
+ len = 0;
50
+ room(n) {
51
+ if (this.len + n <= this.buf.length)
52
+ return;
53
+ const next = Buffer.alloc(Math.max(this.buf.length * 2, this.len + n));
54
+ this.buf.copy(next, 0, 0, this.len);
55
+ this.buf = next;
56
+ }
57
+ /** `n` bytes written by `f` at the current end. */
58
+ write(n, f) {
59
+ this.room(n);
60
+ f(this.buf, this.len);
61
+ this.len += n;
62
+ }
63
+ bytes(b) {
64
+ this.write(b.length, (buf, at) => buf.set(b, at));
65
+ }
66
+ done() {
67
+ return Buffer.from(this.buf.subarray(0, this.len));
68
+ }
69
+ }
70
+ export class IdlCoder {
71
+ types;
72
+ instructions;
73
+ accountDefs;
74
+ enc = getAddressEncoder();
75
+ dec = getAddressDecoder();
76
+ constructor(idl) {
77
+ const types = (idl.types ?? []);
78
+ this.types = new Map(types.map((t) => [t.name, t]));
79
+ // Every layout is checked now, as Anchor's coder builds them all when it is made.
80
+ this.instructions = new Map(idl.instructions.map((ix) => {
81
+ const args = ix.args.map((a) => ({ name: a.name, type: a.type }));
82
+ for (const a of args)
83
+ this.check(a.type, NO_ENV, [], false, a.name);
84
+ return [ix.name, { discriminator: Buffer.from(ix.discriminator), args }];
85
+ }));
86
+ if (idl.accounts?.length && !idl.types)
87
+ throw new Error("Accounts require `idl.types`");
88
+ this.accountDefs = new Map((idl.accounts ?? []).map((acc) => {
89
+ if (!this.types.has(acc.name))
90
+ throw new Error(`Account not found: ${acc.name}`);
91
+ const type = { defined: { name: acc.name } };
92
+ this.check(type, NO_ENV, [], false, acc.name);
93
+ return [acc.name, { discriminator: Buffer.from(acc.discriminator), type }];
94
+ }));
95
+ for (const t of types)
96
+ if (!t.generics?.length)
97
+ this.check({ defined: { name: t.name } }, NO_ENV, [], false, t.name);
98
+ }
99
+ // ---- the IDL's shapes ----
100
+ resolve(type, env) {
101
+ if (typeof type === "object" && "generic" in type) {
102
+ const arg = env.get(type.generic);
103
+ if (arg?.kind !== "type")
104
+ throw new Error(`IDL generic ${type.generic} has no type argument`);
105
+ return arg.type;
106
+ }
107
+ return type;
108
+ }
109
+ arrayLen(len, env) {
110
+ if (typeof len === "number")
111
+ return len;
112
+ const arg = env.get(len.generic);
113
+ if (arg?.kind !== "const")
114
+ throw new Error(`IDL array length ${len.generic} has no const argument`);
115
+ return Number(arg.value);
116
+ }
117
+ /** A defined type and the environment its fields are read in. */
118
+ definition(type, env) {
119
+ const def = this.types.get(type.defined.name);
120
+ if (!def)
121
+ throw new Error(`Type not found: ${type.defined.name}`);
122
+ const inner = new Map();
123
+ (def.generics ?? []).forEach((g, i) => {
124
+ const arg = type.defined.generics?.[i];
125
+ if (!arg)
126
+ throw new Error(`${def.name}: missing generic argument ${g.name}`);
127
+ inner.set(g.name, arg.kind === "type" ? { kind: "type", type: this.resolve(arg.type, env) } : arg);
128
+ });
129
+ return [def, inner];
130
+ }
131
+ /** Throws for a shape the coder cannot read, naming it. A type may only contain itself inside an option or vec. */
132
+ check(type, env, stack, wrapped, where) {
133
+ type = this.resolve(type, env);
134
+ if (typeof type === "string") {
135
+ if (type in FIXED || type === "string" || type === "bytes")
136
+ return;
137
+ throw new Error(`${where}: the IDL type ${type} is not supported`);
138
+ }
139
+ if ("option" in type)
140
+ return this.check(type.option, env, stack, true, where);
141
+ if ("vec" in type)
142
+ return this.check(type.vec, env, stack, true, where);
143
+ if ("array" in type) {
144
+ this.arrayLen(type.array[1], env);
145
+ return this.check(type.array[0], env, stack, wrapped, where);
146
+ }
147
+ if ("defined" in type) {
148
+ const name = type.defined.name;
149
+ if (stack.includes(name)) {
150
+ if (!wrapped)
151
+ throw new Error(`Recursive type must be wrapped in an option or vector: ${name}`);
152
+ return;
153
+ }
154
+ const [def, inner] = this.definition(type, env);
155
+ const next = [...stack, name];
156
+ if (def.type.kind === "struct")
157
+ for (const f of fieldsOf(def.type.fields))
158
+ this.check(f.type, inner, next, false, `${name}.${f.name}`);
159
+ else if (def.type.kind === "enum")
160
+ for (const v of def.type.variants)
161
+ for (const f of fieldsOf(v.fields))
162
+ this.check(f.type, inner, next, false, `${name}.${v.name}.${f.name}`);
163
+ else if (def.type.kind === "type")
164
+ this.check(def.type.alias, inner, next, false, name);
165
+ else
166
+ throw new Error(`${name}: the IDL type kind ${def.type.kind} is not supported`);
167
+ return;
168
+ }
169
+ throw new Error(`${where}: the IDL type ${describe(type)} is not supported`);
170
+ }
171
+ /** The type's size when every value of it has the same size (as Anchor's layouts give a span), else undefined. */
172
+ fixedSize(type, env, stack = []) {
173
+ type = this.resolve(type, env);
174
+ if (typeof type === "string")
175
+ return FIXED[type];
176
+ if ("array" in type) {
177
+ const n = this.fixedSize(type.array[0], env, stack);
178
+ return n !== undefined && n > 0 ? n * this.arrayLen(type.array[1], env) : undefined;
179
+ }
180
+ if ("defined" in type && !stack.includes(type.defined.name)) {
181
+ const [def, inner] = this.definition(type, env);
182
+ const next = [...stack, type.defined.name];
183
+ if (def.type.kind === "type")
184
+ return this.fixedSize(def.type.alias, inner, next);
185
+ if (def.type.kind !== "struct")
186
+ return undefined; // an enum is read by its tag
187
+ let total = 0;
188
+ for (const f of fieldsOf(def.type.fields)) {
189
+ const n = this.fixedSize(f.type, inner, next);
190
+ if (n === undefined)
191
+ return undefined;
192
+ total += n;
193
+ }
194
+ return total;
195
+ }
196
+ return undefined;
197
+ }
198
+ // ---- encoding ----
199
+ bigint(v, t, where) {
200
+ const { bytes, signed } = BIGS[t];
201
+ let n;
202
+ if (typeof v === "bigint")
203
+ n = v;
204
+ else {
205
+ const s = String(v);
206
+ if (!/^-?\d+$/.test(s))
207
+ throw new Error(`${where}: ${s} is not an integer (${t})`);
208
+ n = BigInt(s);
209
+ }
210
+ const bits = BigInt(bytes * 8);
211
+ const [min, max] = signed ? [-(1n << (bits - 1n)), (1n << (bits - 1n)) - 1n] : [0n, (1n << bits) - 1n];
212
+ if (n < min || n > max)
213
+ throw new RangeError(`${where}: ${n} is out of range for ${t}`);
214
+ return n;
215
+ }
216
+ pubkey(v, where) {
217
+ if (typeof v === "string") {
218
+ if (!isAddress(v))
219
+ throw new Error(`${where}: expected an address`);
220
+ return new Uint8Array(this.enc.encode(v));
221
+ }
222
+ if (v instanceof Uint8Array && v.length === 32)
223
+ return v;
224
+ // An object with Solana web3.js 1.x's PublicKey methods.
225
+ const o = v;
226
+ const b = typeof o?.toBuffer === "function" ? o.toBuffer() : typeof o?.toBytes === "function" ? o.toBytes() : undefined;
227
+ if (b instanceof Uint8Array && b.length === 32)
228
+ return b;
229
+ throw new Error(`${where}: expected an address`);
230
+ }
231
+ write(w, type, v, env, where) {
232
+ type = this.resolve(type, env);
233
+ if (typeof type === "string") {
234
+ const int = INTS[type];
235
+ // Buffer's own writers, as Anchor's layouts use them: the same range errors and the same rounding.
236
+ if (int)
237
+ return w.write(int.bytes, (b, at) => (int.signed ? b.writeIntLE(v, at, int.bytes) : b.writeUIntLE(v, at, int.bytes)));
238
+ const big = BIGS[type];
239
+ if (big) {
240
+ let n = BigInt.asUintN(big.bytes * 8, this.bigint(v, type, where));
241
+ return w.write(big.bytes, (b, at) => {
242
+ for (let i = 0; i < big.bytes; i++, n >>= 8n)
243
+ b[at + i] = Number(n & 0xffn);
244
+ });
245
+ }
246
+ switch (type) {
247
+ case "bool":
248
+ return w.write(1, (b, at) => (b[at] = v ? 1 : 0));
249
+ case "f32":
250
+ return w.write(4, (b, at) => b.writeFloatLE(v, at));
251
+ case "f64":
252
+ return w.write(8, (b, at) => b.writeDoubleLE(v, at));
253
+ case "pubkey":
254
+ return w.bytes(this.pubkey(v, where));
255
+ case "string":
256
+ case "bytes": {
257
+ if (type === "string" && typeof v !== "string" && !(v instanceof Uint8Array))
258
+ throw new TypeError(`${where}: expected a string`);
259
+ if (type === "bytes" && !(v instanceof Uint8Array) && !Array.isArray(v))
260
+ throw new TypeError(`${where}: expected bytes`);
261
+ const body = type === "string" ? Buffer.from(v, "utf8") : Buffer.from(v);
262
+ w.write(4, (b, at) => b.writeUInt32LE(body.length, at));
263
+ return w.bytes(body);
264
+ }
265
+ }
266
+ throw new Error(`${where}: the IDL type ${type} is not supported`);
267
+ }
268
+ if ("option" in type) {
269
+ if (v === null || v === undefined)
270
+ return w.write(1, (b, at) => (b[at] = 0));
271
+ w.write(1, (b, at) => (b[at] = 1));
272
+ return this.write(w, type.option, v, env, where);
273
+ }
274
+ if ("vec" in type) {
275
+ const items = this.items(v, where);
276
+ w.write(4, (b, at) => b.writeUInt32LE(items.length, at));
277
+ items.forEach((x, i) => this.write(w, type.vec, x, env, `${where}[${i}]`));
278
+ return;
279
+ }
280
+ if ("array" in type) {
281
+ const items = this.items(v, where);
282
+ const len = this.arrayLen(type.array[1], env);
283
+ if (items.length !== len)
284
+ throw new RangeError(`${where}: expected ${len} items, received ${items.length}`);
285
+ items.forEach((x, i) => this.write(w, type.array[0], x, env, `${where}[${i}]`));
286
+ return;
287
+ }
288
+ if ("defined" in type) {
289
+ const [def, inner] = this.definition(type, env);
290
+ if (def.type.kind === "type")
291
+ return this.write(w, def.type.alias, v, inner, where);
292
+ if (def.type.kind === "struct")
293
+ return this.fields(w, fieldsOf(def.type.fields), v, inner, where);
294
+ if (def.type.kind === "enum") {
295
+ if (typeof v !== "object" || v === null)
296
+ throw new TypeError(`${where}: expected a variant of ${def.name}, as { Variant: {…} }`);
297
+ // The first variant (in the IDL's order) the object names, as Anchor's coder picks it.
298
+ const i = def.type.variants.findIndex((x) => Object.prototype.hasOwnProperty.call(v, x.name));
299
+ if (i < 0)
300
+ throw new Error(`${where}: no variant of ${def.name} in { ${Object.keys(v).join(", ")} }`);
301
+ const variant = def.type.variants[i];
302
+ if (i > 255)
303
+ throw new RangeError(`${def.name}: more than 256 variants`);
304
+ w.write(1, (b, at) => (b[at] = i));
305
+ const fields = fieldsOf(variant.fields);
306
+ if (fields.length)
307
+ this.fields(w, fields, v[variant.name], inner, `${where}.${variant.name}`);
308
+ return;
309
+ }
310
+ }
311
+ throw new Error(`${where}: the IDL type ${describe(type)} is not supported`);
312
+ }
313
+ items(v, where) {
314
+ if (Array.isArray(v))
315
+ return v;
316
+ if (ArrayBuffer.isView(v) && !(v instanceof DataView))
317
+ return Array.from(v);
318
+ throw new TypeError(`${where}: expected an array`);
319
+ }
320
+ /**
321
+ * 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.
323
+ */
324
+ fields(w, fields, v, env, where) {
325
+ if (fields.length && (typeof v !== "object" || v === null))
326
+ throw new TypeError(`${where}: expected an object with ${fields.map((f) => f.name).join(", ")}`);
327
+ const o = v;
328
+ for (const f of fields) {
329
+ const x = o[f.name];
330
+ if (x === undefined) {
331
+ const isOption = (() => {
332
+ const t = this.resolve(f.type, env);
333
+ return typeof t === "object" && "option" in t;
334
+ })();
335
+ if (isOption) {
336
+ this.write(w, f.type, null, env, `${where}.${f.name}`);
337
+ continue;
338
+ }
339
+ const n = this.fixedSize(f.type, env);
340
+ if (n === undefined)
341
+ throw new Error(`${where}.${f.name}: missing`);
342
+ w.write(n, (b, at) => b.fill(0, at, at + n));
343
+ continue;
344
+ }
345
+ this.write(w, f.type, x, env, `${where}.${f.name}`);
346
+ }
347
+ }
348
+ /** Instruction data: the IDL's discriminator, then the arguments. */
349
+ encodeInstruction(name, args) {
350
+ const ix = this.instructions.get(name);
351
+ if (!ix)
352
+ throw new Error(`Unknown method: ${name}`);
353
+ if (ix.args.length && (args === null || typeof args !== "object" || Array.isArray(args)))
354
+ throw new Error(`Invalid arguments for instruction "${name}": expected an object with fields { ${ix.args.map((a) => a.name).join(", ")} }`);
355
+ const isOption = (t) => typeof t === "object" && "option" in t;
356
+ const missing = ix.args.filter((a) => !isOption(a.type) && !Object.prototype.hasOwnProperty.call(args, a.name)).map((a) => `\`${a.name}\``);
357
+ if (missing.length)
358
+ throw new Error(`Invalid arguments for instruction "${name}": missing field${missing.length > 1 ? "s" : ""} ${missing.join(", ")}.`);
359
+ const w = new Writer();
360
+ w.bytes(ix.discriminator);
361
+ this.fields(w, ix.args, args ?? {}, NO_ENV, name);
362
+ return w.done();
363
+ }
364
+ /** Account data: the discriminator, then the account's fields. */
365
+ encodeAccount(name, value) {
366
+ const acc = this.accountDefs.get(name);
367
+ if (!acc)
368
+ throw new Error(`Account not found: ${name}`);
369
+ const w = new Writer();
370
+ w.bytes(acc.discriminator);
371
+ this.write(w, acc.type, value, NO_ENV, name);
372
+ return w.done();
373
+ }
374
+ /** A defined type's bytes. */
375
+ encodeType(name, value) {
376
+ const def = this.types.get(name);
377
+ if (!def || def.generics?.length)
378
+ throw new Error(`Unknown type: ${name}`);
379
+ const w = new Writer();
380
+ this.write(w, { defined: { name } }, value, NO_ENV, name);
381
+ return w.done();
382
+ }
383
+ // ---- decoding ----
384
+ need(b, at, n, what) {
385
+ if (at + n > b.length)
386
+ throw new RangeError(`${what}: need ${n} bytes at offset ${at}, the data has ${b.length}`);
387
+ }
388
+ /** The value of `type` at `at`, and the offset after it. */
389
+ read(b, at, type, env, where) {
390
+ type = this.resolve(type, env);
391
+ if (typeof type === "string") {
392
+ const int = INTS[type];
393
+ if (int) {
394
+ this.need(b, at, int.bytes, where);
395
+ return [int.signed ? b.readIntLE(at, int.bytes) : b.readUIntLE(at, int.bytes), at + int.bytes];
396
+ }
397
+ // Data cut short (return data loses its trailing zero bytes) is read as Anchor's coder reads it: a wide integer
398
+ // from the bytes that are there, the missing high bytes zero; a pubkey from them, padded with zeros in front.
399
+ const big = BIGS[type];
400
+ if (big) {
401
+ const have = b.subarray(at, at + big.bytes);
402
+ let n = 0n;
403
+ for (let i = have.length - 1; i >= 0; i--)
404
+ n = (n << 8n) | BigInt(have[i]);
405
+ return [big.signed ? BigInt.asIntN(big.bytes * 8, n) : n, at + big.bytes];
406
+ }
407
+ switch (type) {
408
+ case "bool": {
409
+ this.need(b, at, 1, where);
410
+ const x = b[at];
411
+ if (x > 1)
412
+ throw new Error(`Invalid bool: ${x}`);
413
+ return [x === 1, at + 1];
414
+ }
415
+ case "f32":
416
+ this.need(b, at, 4, where);
417
+ return [b.readFloatLE(at), at + 4];
418
+ case "f64":
419
+ this.need(b, at, 8, where);
420
+ return [b.readDoubleLE(at), at + 8];
421
+ case "pubkey": {
422
+ const have = b.subarray(at, at + 32);
423
+ const key = new Uint8Array(32);
424
+ key.set(have, 32 - have.length);
425
+ return [this.dec.decode(key), at + 32];
426
+ }
427
+ case "string":
428
+ case "bytes": {
429
+ this.need(b, at, 4, where);
430
+ const len = b.readUInt32LE(at);
431
+ this.need(b, at + 4, len, where);
432
+ const body = b.subarray(at + 4, at + 4 + len);
433
+ return [type === "string" ? body.toString("utf8") : body, at + 4 + len];
434
+ }
435
+ }
436
+ throw new Error(`${where}: the IDL type ${type} is not supported`);
437
+ }
438
+ if ("option" in type) {
439
+ this.need(b, at, 1, where);
440
+ if (b[at] === 0)
441
+ return [null, at + 1];
442
+ if (b[at] !== 1)
443
+ throw new Error(`Invalid option ${where}`);
444
+ return this.read(b, at + 1, type.option, env, where);
445
+ }
446
+ if ("vec" in type || "array" in type) {
447
+ let count;
448
+ let elem;
449
+ if ("vec" in type) {
450
+ this.need(b, at, 4, where);
451
+ count = b.readUInt32LE(at);
452
+ at += 4;
453
+ elem = type.vec;
454
+ }
455
+ else {
456
+ count = this.arrayLen(type.array[1], env);
457
+ elem = type.array[0];
458
+ }
459
+ // A count the data cannot hold is refused before reading: elements of a fixed size need count × size bytes, others
460
+ // at least a byte each. Unlike a value on its own, an element may not run past the end.
461
+ const size = this.fixedSize(elem, env);
462
+ const left = Math.max(0, b.length - at);
463
+ if (size !== undefined && size > 0 ? count * size > left : size === undefined && count > left)
464
+ throw new RangeError(`${where}: ${count} items do not fit in the ${left} bytes left`);
465
+ const out = [];
466
+ for (let i = 0; i < count; i++) {
467
+ const [x, next] = this.read(b, at, elem, env, `${where}[${i}]`);
468
+ if (next > b.length)
469
+ throw new RangeError(`${where}[${i}]: read past the end of the data`);
470
+ out.push(x);
471
+ at = next;
472
+ }
473
+ return [out, at];
474
+ }
475
+ if ("defined" in type) {
476
+ const [def, inner] = this.definition(type, env);
477
+ if (def.type.kind === "type")
478
+ return this.read(b, at, def.type.alias, inner, where);
479
+ if (def.type.kind === "struct")
480
+ return this.readFields(b, at, fieldsOf(def.type.fields), inner, where);
481
+ if (def.type.kind === "enum") {
482
+ this.need(b, at, 1, where);
483
+ const variant = def.type.variants[b[at]];
484
+ if (!variant)
485
+ throw new Error(`${where}: ${b[at]} is not a variant of ${def.name}`);
486
+ const [body, next] = this.readFields(b, at + 1, fieldsOf(variant.fields), inner, `${where}.${variant.name}`);
487
+ return [{ [variant.name]: body }, next];
488
+ }
489
+ }
490
+ throw new Error(`${where}: the IDL type ${describe(type)} is not supported`);
491
+ }
492
+ readFields(b, at, fields, env, where) {
493
+ const out = {};
494
+ for (const f of fields) {
495
+ const [x, next] = this.read(b, at, f.type, env, `${where}.${f.name}`);
496
+ out[f.name] = x;
497
+ at = next;
498
+ }
499
+ return [out, at];
500
+ }
501
+ /** An account's fields, after checking its discriminator. Bytes after the fields are ignored. */
502
+ decodeAccount(name, data) {
503
+ const acc = this.accountDefs.get(name);
504
+ if (!acc)
505
+ throw new Error(`Account not found: ${name}`);
506
+ const b = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
507
+ if (acc.discriminator.compare(b.subarray(0, acc.discriminator.length)) !== 0)
508
+ throw new Error("Invalid account discriminator");
509
+ return this.read(b, acc.discriminator.length, acc.type, NO_ENV, name)[0];
510
+ }
511
+ /** A defined type read from the start of `data`. Bytes after it are ignored. */
512
+ decodeType(name, data) {
513
+ const def = this.types.get(name);
514
+ if (!def || def.generics?.length)
515
+ throw new Error(`Unknown type: ${name}`);
516
+ const b = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
517
+ return this.read(b, 0, { defined: { name } }, NO_ENV, name)[0];
518
+ }
519
+ /** An instruction's arguments read back from its data (after checking the discriminator). */
520
+ decodeInstruction(name, data) {
521
+ const ix = this.instructions.get(name);
522
+ if (!ix)
523
+ throw new Error(`Unknown method: ${name}`);
524
+ const b = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
525
+ if (ix.discriminator.compare(b.subarray(0, ix.discriminator.length)) !== 0)
526
+ throw new Error(`Invalid instruction discriminator for ${name}`);
527
+ return this.readFields(b, ix.discriminator.length, ix.args, NO_ENV, name)[0];
528
+ }
529
+ }