@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/CHANGELOG.md +164 -0
- package/NOTICE +10 -0
- package/README.md +9 -3
- package/dist/compiler/emit/base.d.ts +6 -0
- package/dist/compiler/emit/base.js +8 -0
- package/dist/compiler/emit/calls.js +18 -0
- package/dist/compiler/emit/cpi.js +3 -1
- package/dist/compiler/emit/function.js +7 -2
- package/dist/compiler/emit/program.js +5 -0
- package/dist/compiler/emit/statements.d.ts +29 -2
- package/dist/compiler/emit/statements.js +149 -6
- package/dist/compiler/emit/token.js +18 -1
- package/dist/compiler/toolchain.js +1 -0
- package/dist/idl-coder.d.ts +129 -0
- package/dist/idl-coder.js +567 -0
- package/dist/testing.d.ts +56 -8
- package/dist/testing.js +115 -34
- package/dist/workspace.js +0 -1
- package/docker/deps/0.47.0.lock.json +1206 -0
- package/docker/deps/0.48.0.lock.json +1206 -0
- package/docs/audit.md +6 -6
- package/docs/language-basics.md +2 -1
- package/docs/language-builtins.md +3 -1
- package/docs/language-chain.md +13 -1
- package/docs/language-cpi.md +26 -0
- package/docs/language-errors-events.md +15 -0
- package/docs/language-statements.md +1 -0
- package/docs/test-your-program.md +45 -4
- package/lib/typesol.d.ts +27 -0
- package/llms-full.txt +107 -10
- package/package.json +1 -5
- package/releases/0.46.0.json +817 -0
- package/releases/0.47.0.json +837 -0
- package/runtime/typesol_rt.h +274 -0
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
/**
|
|
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
|
+
*
|
|
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
|
+
* 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).
|
|
20
|
+
*/
|
|
21
|
+
import { getAddressDecoder, getAddressEncoder, isAddress } from "@solana/kit";
|
|
22
|
+
const INTS = {
|
|
23
|
+
u8: { bytes: 1, signed: false },
|
|
24
|
+
i8: { bytes: 1, signed: true },
|
|
25
|
+
u16: { bytes: 2, signed: false },
|
|
26
|
+
i16: { bytes: 2, signed: true },
|
|
27
|
+
u32: { bytes: 4, signed: false },
|
|
28
|
+
i32: { bytes: 4, signed: true },
|
|
29
|
+
};
|
|
30
|
+
const BIGS = {
|
|
31
|
+
u64: { bytes: 8, signed: false },
|
|
32
|
+
i64: { bytes: 8, signed: true },
|
|
33
|
+
u128: { bytes: 16, signed: false },
|
|
34
|
+
i128: { bytes: 16, signed: true },
|
|
35
|
+
u256: { bytes: 32, signed: false },
|
|
36
|
+
i256: { bytes: 32, signed: true },
|
|
37
|
+
};
|
|
38
|
+
const FIXED = { bool: 1, f32: 4, f64: 8, pubkey: 32 };
|
|
39
|
+
for (const [k, v] of Object.entries({ ...INTS, ...BIGS }))
|
|
40
|
+
FIXED[k] = v.bytes;
|
|
41
|
+
const NO_ENV = new Map();
|
|
42
|
+
const describe = (t) => (typeof t === "string" ? t : JSON.stringify(t));
|
|
43
|
+
/** Named fields of a struct or variant, or a tuple's fields named "0", "1"… (as Anchor's coder names them). */
|
|
44
|
+
function fieldsOf(fields) {
|
|
45
|
+
if (!fields?.length)
|
|
46
|
+
return [];
|
|
47
|
+
if (typeof fields[0] === "object" && fields[0] !== null && "name" in fields[0] && fields[0].name)
|
|
48
|
+
return fields;
|
|
49
|
+
return fields.map((type, i) => ({ name: String(i), type }));
|
|
50
|
+
}
|
|
51
|
+
class Writer {
|
|
52
|
+
buf = Buffer.alloc(256);
|
|
53
|
+
len = 0;
|
|
54
|
+
room(n) {
|
|
55
|
+
if (this.len + n <= this.buf.length)
|
|
56
|
+
return;
|
|
57
|
+
const next = Buffer.alloc(Math.max(this.buf.length * 2, this.len + n));
|
|
58
|
+
this.buf.copy(next, 0, 0, this.len);
|
|
59
|
+
this.buf = next;
|
|
60
|
+
}
|
|
61
|
+
/** `n` bytes written by `f` at the current end. */
|
|
62
|
+
write(n, f) {
|
|
63
|
+
this.room(n);
|
|
64
|
+
f(this.buf, this.len);
|
|
65
|
+
this.len += n;
|
|
66
|
+
}
|
|
67
|
+
bytes(b) {
|
|
68
|
+
this.write(b.length, (buf, at) => buf.set(b, at));
|
|
69
|
+
}
|
|
70
|
+
done() {
|
|
71
|
+
return Buffer.from(this.buf.subarray(0, this.len));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export class IdlCoder {
|
|
75
|
+
types;
|
|
76
|
+
instructions;
|
|
77
|
+
accountDefs;
|
|
78
|
+
eventDefs;
|
|
79
|
+
strict;
|
|
80
|
+
enc = getAddressEncoder();
|
|
81
|
+
dec = getAddressDecoder();
|
|
82
|
+
constructor(idl, options = {}) {
|
|
83
|
+
this.strict = options.strict ?? false;
|
|
84
|
+
const types = (idl.types ?? []);
|
|
85
|
+
this.types = new Map(types.map((t) => [t.name, t]));
|
|
86
|
+
// Every layout is checked now, as Anchor's coder builds them all when it is made.
|
|
87
|
+
this.instructions = new Map(idl.instructions.map((ix) => {
|
|
88
|
+
const args = ix.args.map((a) => ({ name: a.name, type: a.type }));
|
|
89
|
+
for (const a of args)
|
|
90
|
+
this.check(a.type, NO_ENV, [], false, a.name);
|
|
91
|
+
return [ix.name, { discriminator: Buffer.from(ix.discriminator), args }];
|
|
92
|
+
}));
|
|
93
|
+
if (idl.accounts?.length && !idl.types)
|
|
94
|
+
throw new Error("Accounts require `idl.types`");
|
|
95
|
+
this.accountDefs = new Map((idl.accounts ?? []).map((acc) => {
|
|
96
|
+
if (!this.types.has(acc.name))
|
|
97
|
+
throw new Error(`Account not found: ${acc.name}`);
|
|
98
|
+
const type = { defined: { name: acc.name } };
|
|
99
|
+
this.check(type, NO_ENV, [], false, acc.name);
|
|
100
|
+
return [acc.name, { discriminator: Buffer.from(acc.discriminator), type }];
|
|
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
|
+
});
|
|
111
|
+
for (const t of types)
|
|
112
|
+
if (!t.generics?.length)
|
|
113
|
+
this.check({ defined: { name: t.name } }, NO_ENV, [], false, t.name);
|
|
114
|
+
}
|
|
115
|
+
// ---- the IDL's shapes ----
|
|
116
|
+
resolve(type, env) {
|
|
117
|
+
if (typeof type === "object" && "generic" in type) {
|
|
118
|
+
const arg = env.get(type.generic);
|
|
119
|
+
if (arg?.kind !== "type")
|
|
120
|
+
throw new Error(`IDL generic ${type.generic} has no type argument`);
|
|
121
|
+
return arg.type;
|
|
122
|
+
}
|
|
123
|
+
return type;
|
|
124
|
+
}
|
|
125
|
+
arrayLen(len, env) {
|
|
126
|
+
if (typeof len === "number")
|
|
127
|
+
return len;
|
|
128
|
+
const arg = env.get(len.generic);
|
|
129
|
+
if (arg?.kind !== "const")
|
|
130
|
+
throw new Error(`IDL array length ${len.generic} has no const argument`);
|
|
131
|
+
return Number(arg.value);
|
|
132
|
+
}
|
|
133
|
+
/** A defined type and the environment its fields are read in. */
|
|
134
|
+
definition(type, env) {
|
|
135
|
+
const def = this.types.get(type.defined.name);
|
|
136
|
+
if (!def)
|
|
137
|
+
throw new Error(`Type not found: ${type.defined.name}`);
|
|
138
|
+
const inner = new Map();
|
|
139
|
+
(def.generics ?? []).forEach((g, i) => {
|
|
140
|
+
const arg = type.defined.generics?.[i];
|
|
141
|
+
if (!arg)
|
|
142
|
+
throw new Error(`${def.name}: missing generic argument ${g.name}`);
|
|
143
|
+
inner.set(g.name, arg.kind === "type" ? { kind: "type", type: this.resolve(arg.type, env) } : arg);
|
|
144
|
+
});
|
|
145
|
+
return [def, inner];
|
|
146
|
+
}
|
|
147
|
+
/** Throws for a shape the coder cannot read, naming it. A type may only contain itself inside an option or vec. */
|
|
148
|
+
check(type, env, stack, wrapped, where) {
|
|
149
|
+
type = this.resolve(type, env);
|
|
150
|
+
if (typeof type === "string") {
|
|
151
|
+
if (type in FIXED || type === "string" || type === "bytes")
|
|
152
|
+
return;
|
|
153
|
+
throw new Error(`${where}: the IDL type ${type} is not supported`);
|
|
154
|
+
}
|
|
155
|
+
if ("option" in type)
|
|
156
|
+
return this.check(type.option, env, stack, true, where);
|
|
157
|
+
if ("vec" in type)
|
|
158
|
+
return this.check(type.vec, env, stack, true, where);
|
|
159
|
+
if ("array" in type) {
|
|
160
|
+
this.arrayLen(type.array[1], env);
|
|
161
|
+
return this.check(type.array[0], env, stack, wrapped, where);
|
|
162
|
+
}
|
|
163
|
+
if ("defined" in type) {
|
|
164
|
+
const name = type.defined.name;
|
|
165
|
+
if (stack.includes(name)) {
|
|
166
|
+
if (!wrapped)
|
|
167
|
+
throw new Error(`Recursive type must be wrapped in an option or vector: ${name}`);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const [def, inner] = this.definition(type, env);
|
|
171
|
+
const next = [...stack, name];
|
|
172
|
+
if (def.type.kind === "struct")
|
|
173
|
+
for (const f of fieldsOf(def.type.fields))
|
|
174
|
+
this.check(f.type, inner, next, false, `${name}.${f.name}`);
|
|
175
|
+
else if (def.type.kind === "enum")
|
|
176
|
+
for (const v of def.type.variants)
|
|
177
|
+
for (const f of fieldsOf(v.fields))
|
|
178
|
+
this.check(f.type, inner, next, false, `${name}.${v.name}.${f.name}`);
|
|
179
|
+
else if (def.type.kind === "type")
|
|
180
|
+
this.check(def.type.alias, inner, next, false, name);
|
|
181
|
+
else
|
|
182
|
+
throw new Error(`${name}: the IDL type kind ${def.type.kind} is not supported`);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
throw new Error(`${where}: the IDL type ${describe(type)} is not supported`);
|
|
186
|
+
}
|
|
187
|
+
/** The type's size when every value of it has the same size (as Anchor's layouts give a span), else undefined. */
|
|
188
|
+
fixedSize(type, env, stack = []) {
|
|
189
|
+
type = this.resolve(type, env);
|
|
190
|
+
if (typeof type === "string")
|
|
191
|
+
return FIXED[type];
|
|
192
|
+
if ("array" in type) {
|
|
193
|
+
const n = this.fixedSize(type.array[0], env, stack);
|
|
194
|
+
return n !== undefined && n > 0 ? n * this.arrayLen(type.array[1], env) : undefined;
|
|
195
|
+
}
|
|
196
|
+
if ("defined" in type && !stack.includes(type.defined.name)) {
|
|
197
|
+
const [def, inner] = this.definition(type, env);
|
|
198
|
+
const next = [...stack, type.defined.name];
|
|
199
|
+
if (def.type.kind === "type")
|
|
200
|
+
return this.fixedSize(def.type.alias, inner, next);
|
|
201
|
+
if (def.type.kind !== "struct")
|
|
202
|
+
return undefined; // an enum is read by its tag
|
|
203
|
+
let total = 0;
|
|
204
|
+
for (const f of fieldsOf(def.type.fields)) {
|
|
205
|
+
const n = this.fixedSize(f.type, inner, next);
|
|
206
|
+
if (n === undefined)
|
|
207
|
+
return undefined;
|
|
208
|
+
total += n;
|
|
209
|
+
}
|
|
210
|
+
return total;
|
|
211
|
+
}
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
// ---- encoding ----
|
|
215
|
+
bigint(v, t, where) {
|
|
216
|
+
const { bytes, signed } = BIGS[t];
|
|
217
|
+
let n;
|
|
218
|
+
if (typeof v === "bigint")
|
|
219
|
+
n = v;
|
|
220
|
+
else {
|
|
221
|
+
const s = String(v);
|
|
222
|
+
if (!/^-?\d+$/.test(s))
|
|
223
|
+
throw new Error(`${where}: ${s} is not an integer (${t})`);
|
|
224
|
+
n = BigInt(s);
|
|
225
|
+
}
|
|
226
|
+
const bits = BigInt(bytes * 8);
|
|
227
|
+
const [min, max] = signed ? [-(1n << (bits - 1n)), (1n << (bits - 1n)) - 1n] : [0n, (1n << bits) - 1n];
|
|
228
|
+
if (n < min || n > max)
|
|
229
|
+
throw new RangeError(`${where}: ${n} is out of range for ${t}`);
|
|
230
|
+
return n;
|
|
231
|
+
}
|
|
232
|
+
pubkey(v, where) {
|
|
233
|
+
if (typeof v === "string") {
|
|
234
|
+
if (!isAddress(v))
|
|
235
|
+
throw new Error(`${where}: expected an address`);
|
|
236
|
+
return new Uint8Array(this.enc.encode(v));
|
|
237
|
+
}
|
|
238
|
+
if (v instanceof Uint8Array && v.length === 32)
|
|
239
|
+
return v;
|
|
240
|
+
// An object with Solana web3.js 1.x's PublicKey methods.
|
|
241
|
+
const o = v;
|
|
242
|
+
const b = typeof o?.toBuffer === "function" ? o.toBuffer() : typeof o?.toBytes === "function" ? o.toBytes() : undefined;
|
|
243
|
+
if (b instanceof Uint8Array && b.length === 32)
|
|
244
|
+
return b;
|
|
245
|
+
throw new Error(`${where}: expected an address`);
|
|
246
|
+
}
|
|
247
|
+
write(w, type, v, env, where) {
|
|
248
|
+
type = this.resolve(type, env);
|
|
249
|
+
if (typeof type === "string") {
|
|
250
|
+
const int = INTS[type];
|
|
251
|
+
// Buffer's own writers, as Anchor's layouts use them: the same range errors and the same rounding.
|
|
252
|
+
if (int)
|
|
253
|
+
return w.write(int.bytes, (b, at) => (int.signed ? b.writeIntLE(v, at, int.bytes) : b.writeUIntLE(v, at, int.bytes)));
|
|
254
|
+
const big = BIGS[type];
|
|
255
|
+
if (big) {
|
|
256
|
+
let n = BigInt.asUintN(big.bytes * 8, this.bigint(v, type, where));
|
|
257
|
+
return w.write(big.bytes, (b, at) => {
|
|
258
|
+
for (let i = 0; i < big.bytes; i++, n >>= 8n)
|
|
259
|
+
b[at + i] = Number(n & 0xffn);
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
switch (type) {
|
|
263
|
+
case "bool":
|
|
264
|
+
return w.write(1, (b, at) => (b[at] = v ? 1 : 0));
|
|
265
|
+
case "f32":
|
|
266
|
+
return w.write(4, (b, at) => b.writeFloatLE(v, at));
|
|
267
|
+
case "f64":
|
|
268
|
+
return w.write(8, (b, at) => b.writeDoubleLE(v, at));
|
|
269
|
+
case "pubkey":
|
|
270
|
+
return w.bytes(this.pubkey(v, where));
|
|
271
|
+
case "string":
|
|
272
|
+
case "bytes": {
|
|
273
|
+
if (type === "string" && typeof v !== "string" && !(v instanceof Uint8Array))
|
|
274
|
+
throw new TypeError(`${where}: expected a string`);
|
|
275
|
+
if (type === "bytes" && !(v instanceof Uint8Array) && !Array.isArray(v))
|
|
276
|
+
throw new TypeError(`${where}: expected bytes`);
|
|
277
|
+
const body = type === "string" ? Buffer.from(v, "utf8") : Buffer.from(v);
|
|
278
|
+
w.write(4, (b, at) => b.writeUInt32LE(body.length, at));
|
|
279
|
+
return w.bytes(body);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
throw new Error(`${where}: the IDL type ${type} is not supported`);
|
|
283
|
+
}
|
|
284
|
+
if ("option" in type) {
|
|
285
|
+
if (v === null || v === undefined)
|
|
286
|
+
return w.write(1, (b, at) => (b[at] = 0));
|
|
287
|
+
w.write(1, (b, at) => (b[at] = 1));
|
|
288
|
+
return this.write(w, type.option, v, env, where);
|
|
289
|
+
}
|
|
290
|
+
if ("vec" in type) {
|
|
291
|
+
const items = this.items(v, where);
|
|
292
|
+
w.write(4, (b, at) => b.writeUInt32LE(items.length, at));
|
|
293
|
+
items.forEach((x, i) => this.write(w, type.vec, x, env, `${where}[${i}]`));
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if ("array" in type) {
|
|
297
|
+
const items = this.items(v, where);
|
|
298
|
+
const len = this.arrayLen(type.array[1], env);
|
|
299
|
+
if (items.length !== len)
|
|
300
|
+
throw new RangeError(`${where}: expected ${len} items, received ${items.length}`);
|
|
301
|
+
items.forEach((x, i) => this.write(w, type.array[0], x, env, `${where}[${i}]`));
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
if ("defined" in type) {
|
|
305
|
+
const [def, inner] = this.definition(type, env);
|
|
306
|
+
if (def.type.kind === "type")
|
|
307
|
+
return this.write(w, def.type.alias, v, inner, where);
|
|
308
|
+
if (def.type.kind === "struct")
|
|
309
|
+
return this.fields(w, fieldsOf(def.type.fields), v, inner, where);
|
|
310
|
+
if (def.type.kind === "enum") {
|
|
311
|
+
if (typeof v !== "object" || v === null)
|
|
312
|
+
throw new TypeError(`${where}: expected a variant of ${def.name}, as { Variant: {…} }`);
|
|
313
|
+
// The first variant (in the IDL's order) the object names, as Anchor's coder picks it.
|
|
314
|
+
const i = def.type.variants.findIndex((x) => Object.prototype.hasOwnProperty.call(v, x.name));
|
|
315
|
+
if (i < 0)
|
|
316
|
+
throw new Error(`${where}: no variant of ${def.name} in { ${Object.keys(v).join(", ")} }`);
|
|
317
|
+
const variant = def.type.variants[i];
|
|
318
|
+
if (i > 255)
|
|
319
|
+
throw new RangeError(`${def.name}: more than 256 variants`);
|
|
320
|
+
w.write(1, (b, at) => (b[at] = i));
|
|
321
|
+
const fields = fieldsOf(variant.fields);
|
|
322
|
+
if (fields.length)
|
|
323
|
+
this.fields(w, fields, v[variant.name], inner, `${where}.${variant.name}`);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
throw new Error(`${where}: the IDL type ${describe(type)} is not supported`);
|
|
328
|
+
}
|
|
329
|
+
items(v, where) {
|
|
330
|
+
if (Array.isArray(v))
|
|
331
|
+
return v;
|
|
332
|
+
if (ArrayBuffer.isView(v) && !(v instanceof DataView))
|
|
333
|
+
return Array.from(v);
|
|
334
|
+
throw new TypeError(`${where}: expected an array`);
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* A struct's fields in order. A field left undefined is written as zeros when its size is fixed (what Anchor's coder
|
|
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.
|
|
340
|
+
*/
|
|
341
|
+
fields(w, fields, v, env, where) {
|
|
342
|
+
if (fields.length && (typeof v !== "object" || v === null))
|
|
343
|
+
throw new TypeError(`${where}: expected an object with ${fields.map((f) => f.name).join(", ")}`);
|
|
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"})`);
|
|
349
|
+
for (const f of fields) {
|
|
350
|
+
const x = o[f.name];
|
|
351
|
+
if (x === undefined) {
|
|
352
|
+
const isOption = (() => {
|
|
353
|
+
const t = this.resolve(f.type, env);
|
|
354
|
+
return typeof t === "object" && "option" in t;
|
|
355
|
+
})();
|
|
356
|
+
if (isOption) {
|
|
357
|
+
this.write(w, f.type, null, env, `${where}.${f.name}`);
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
if (this.strict)
|
|
361
|
+
throw new Error(`${where}.${f.name}: missing (only an Option may be left out)`);
|
|
362
|
+
const n = this.fixedSize(f.type, env);
|
|
363
|
+
if (n === undefined)
|
|
364
|
+
throw new Error(`${where}.${f.name}: missing`);
|
|
365
|
+
w.write(n, (b, at) => b.fill(0, at, at + n));
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
this.write(w, f.type, x, env, `${where}.${f.name}`);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
/** Instruction data: the IDL's discriminator, then the arguments. */
|
|
372
|
+
encodeInstruction(name, args) {
|
|
373
|
+
const ix = this.instructions.get(name);
|
|
374
|
+
if (!ix)
|
|
375
|
+
throw new Error(`Unknown method: ${name}`);
|
|
376
|
+
if (ix.args.length && (args === null || typeof args !== "object" || Array.isArray(args)))
|
|
377
|
+
throw new Error(`Invalid arguments for instruction "${name}": expected an object with fields { ${ix.args.map((a) => a.name).join(", ")} }`);
|
|
378
|
+
const isOption = (t) => typeof t === "object" && "option" in t;
|
|
379
|
+
const missing = ix.args.filter((a) => !isOption(a.type) && !Object.prototype.hasOwnProperty.call(args, a.name)).map((a) => `\`${a.name}\``);
|
|
380
|
+
if (missing.length)
|
|
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"})`);
|
|
386
|
+
const w = new Writer();
|
|
387
|
+
w.bytes(ix.discriminator);
|
|
388
|
+
this.fields(w, ix.args, args ?? {}, NO_ENV, name);
|
|
389
|
+
return w.done();
|
|
390
|
+
}
|
|
391
|
+
/** Account data: the discriminator, then the account's fields. */
|
|
392
|
+
encodeAccount(name, value) {
|
|
393
|
+
const acc = this.accountDefs.get(name);
|
|
394
|
+
if (!acc)
|
|
395
|
+
throw new Error(`Account not found: ${name}`);
|
|
396
|
+
const w = new Writer();
|
|
397
|
+
w.bytes(acc.discriminator);
|
|
398
|
+
this.write(w, acc.type, value, NO_ENV, name);
|
|
399
|
+
return w.done();
|
|
400
|
+
}
|
|
401
|
+
/** A defined type's bytes. */
|
|
402
|
+
encodeType(name, value) {
|
|
403
|
+
const def = this.types.get(name);
|
|
404
|
+
if (!def || def.generics?.length)
|
|
405
|
+
throw new Error(`Unknown type: ${name}`);
|
|
406
|
+
const w = new Writer();
|
|
407
|
+
this.write(w, { defined: { name } }, value, NO_ENV, name);
|
|
408
|
+
return w.done();
|
|
409
|
+
}
|
|
410
|
+
// ---- decoding ----
|
|
411
|
+
need(b, at, n, what) {
|
|
412
|
+
if (at + n > b.length)
|
|
413
|
+
throw new RangeError(`${what}: need ${n} bytes at offset ${at}, the data has ${b.length}`);
|
|
414
|
+
}
|
|
415
|
+
/** The value of `type` at `at`, and the offset after it. */
|
|
416
|
+
read(b, at, type, env, where) {
|
|
417
|
+
type = this.resolve(type, env);
|
|
418
|
+
if (typeof type === "string") {
|
|
419
|
+
const int = INTS[type];
|
|
420
|
+
if (int) {
|
|
421
|
+
this.need(b, at, int.bytes, where);
|
|
422
|
+
return [int.signed ? b.readIntLE(at, int.bytes) : b.readUIntLE(at, int.bytes), at + int.bytes];
|
|
423
|
+
}
|
|
424
|
+
// Data cut short (return data loses its trailing zero bytes) is read as Anchor's coder reads it: a wide integer
|
|
425
|
+
// from the bytes that are there, the missing high bytes zero; a pubkey from them, padded with zeros in front.
|
|
426
|
+
const big = BIGS[type];
|
|
427
|
+
if (big) {
|
|
428
|
+
const have = b.subarray(at, at + big.bytes);
|
|
429
|
+
let n = 0n;
|
|
430
|
+
for (let i = have.length - 1; i >= 0; i--)
|
|
431
|
+
n = (n << 8n) | BigInt(have[i]);
|
|
432
|
+
return [big.signed ? BigInt.asIntN(big.bytes * 8, n) : n, at + big.bytes];
|
|
433
|
+
}
|
|
434
|
+
switch (type) {
|
|
435
|
+
case "bool": {
|
|
436
|
+
this.need(b, at, 1, where);
|
|
437
|
+
const x = b[at];
|
|
438
|
+
if (x > 1)
|
|
439
|
+
throw new Error(`Invalid bool: ${x}`);
|
|
440
|
+
return [x === 1, at + 1];
|
|
441
|
+
}
|
|
442
|
+
case "f32":
|
|
443
|
+
this.need(b, at, 4, where);
|
|
444
|
+
return [b.readFloatLE(at), at + 4];
|
|
445
|
+
case "f64":
|
|
446
|
+
this.need(b, at, 8, where);
|
|
447
|
+
return [b.readDoubleLE(at), at + 8];
|
|
448
|
+
case "pubkey": {
|
|
449
|
+
const have = b.subarray(at, at + 32);
|
|
450
|
+
const key = new Uint8Array(32);
|
|
451
|
+
key.set(have, 32 - have.length);
|
|
452
|
+
return [this.dec.decode(key), at + 32];
|
|
453
|
+
}
|
|
454
|
+
case "string":
|
|
455
|
+
case "bytes": {
|
|
456
|
+
this.need(b, at, 4, where);
|
|
457
|
+
const len = b.readUInt32LE(at);
|
|
458
|
+
this.need(b, at + 4, len, where);
|
|
459
|
+
const body = b.subarray(at + 4, at + 4 + len);
|
|
460
|
+
return [type === "string" ? body.toString("utf8") : body, at + 4 + len];
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
throw new Error(`${where}: the IDL type ${type} is not supported`);
|
|
464
|
+
}
|
|
465
|
+
if ("option" in type) {
|
|
466
|
+
this.need(b, at, 1, where);
|
|
467
|
+
if (b[at] === 0)
|
|
468
|
+
return [null, at + 1];
|
|
469
|
+
if (b[at] !== 1)
|
|
470
|
+
throw new Error(`Invalid option ${where}`);
|
|
471
|
+
return this.read(b, at + 1, type.option, env, where);
|
|
472
|
+
}
|
|
473
|
+
if ("vec" in type || "array" in type) {
|
|
474
|
+
let count;
|
|
475
|
+
let elem;
|
|
476
|
+
if ("vec" in type) {
|
|
477
|
+
this.need(b, at, 4, where);
|
|
478
|
+
count = b.readUInt32LE(at);
|
|
479
|
+
at += 4;
|
|
480
|
+
elem = type.vec;
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
count = this.arrayLen(type.array[1], env);
|
|
484
|
+
elem = type.array[0];
|
|
485
|
+
}
|
|
486
|
+
// A count the data cannot hold is refused before reading: elements of a fixed size need count × size bytes, others
|
|
487
|
+
// at least a byte each. Unlike a value on its own, an element may not run past the end.
|
|
488
|
+
const size = this.fixedSize(elem, env);
|
|
489
|
+
const left = Math.max(0, b.length - at);
|
|
490
|
+
if (size !== undefined && size > 0 ? count * size > left : size === undefined && count > left)
|
|
491
|
+
throw new RangeError(`${where}: ${count} items do not fit in the ${left} bytes left`);
|
|
492
|
+
const out = [];
|
|
493
|
+
for (let i = 0; i < count; i++) {
|
|
494
|
+
const [x, next] = this.read(b, at, elem, env, `${where}[${i}]`);
|
|
495
|
+
if (next > b.length)
|
|
496
|
+
throw new RangeError(`${where}[${i}]: read past the end of the data`);
|
|
497
|
+
out.push(x);
|
|
498
|
+
at = next;
|
|
499
|
+
}
|
|
500
|
+
return [out, at];
|
|
501
|
+
}
|
|
502
|
+
if ("defined" in type) {
|
|
503
|
+
const [def, inner] = this.definition(type, env);
|
|
504
|
+
if (def.type.kind === "type")
|
|
505
|
+
return this.read(b, at, def.type.alias, inner, where);
|
|
506
|
+
if (def.type.kind === "struct")
|
|
507
|
+
return this.readFields(b, at, fieldsOf(def.type.fields), inner, where);
|
|
508
|
+
if (def.type.kind === "enum") {
|
|
509
|
+
this.need(b, at, 1, where);
|
|
510
|
+
const variant = def.type.variants[b[at]];
|
|
511
|
+
if (!variant)
|
|
512
|
+
throw new Error(`${where}: ${b[at]} is not a variant of ${def.name}`);
|
|
513
|
+
const [body, next] = this.readFields(b, at + 1, fieldsOf(variant.fields), inner, `${where}.${variant.name}`);
|
|
514
|
+
return [{ [variant.name]: body }, next];
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
throw new Error(`${where}: the IDL type ${describe(type)} is not supported`);
|
|
518
|
+
}
|
|
519
|
+
readFields(b, at, fields, env, where) {
|
|
520
|
+
const out = {};
|
|
521
|
+
for (const f of fields) {
|
|
522
|
+
const [x, next] = this.read(b, at, f.type, env, `${where}.${f.name}`);
|
|
523
|
+
out[f.name] = x;
|
|
524
|
+
at = next;
|
|
525
|
+
}
|
|
526
|
+
return [out, at];
|
|
527
|
+
}
|
|
528
|
+
/** An account's fields, after checking its discriminator. Bytes after the fields are ignored. */
|
|
529
|
+
decodeAccount(name, data) {
|
|
530
|
+
const acc = this.accountDefs.get(name);
|
|
531
|
+
if (!acc)
|
|
532
|
+
throw new Error(`Account not found: ${name}`);
|
|
533
|
+
const b = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
534
|
+
if (acc.discriminator.compare(b.subarray(0, acc.discriminator.length)) !== 0)
|
|
535
|
+
throw new Error("Invalid account discriminator");
|
|
536
|
+
return this.read(b, acc.discriminator.length, acc.type, NO_ENV, name)[0];
|
|
537
|
+
}
|
|
538
|
+
/** A defined type read from the start of `data`. Bytes after it are ignored. */
|
|
539
|
+
decodeType(name, data) {
|
|
540
|
+
const def = this.types.get(name);
|
|
541
|
+
if (!def || def.generics?.length)
|
|
542
|
+
throw new Error(`Unknown type: ${name}`);
|
|
543
|
+
const b = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
544
|
+
return this.read(b, 0, { defined: { name } }, NO_ENV, name)[0];
|
|
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
|
+
}
|
|
557
|
+
/** An instruction's arguments read back from its data (after checking the discriminator). */
|
|
558
|
+
decodeInstruction(name, data) {
|
|
559
|
+
const ix = this.instructions.get(name);
|
|
560
|
+
if (!ix)
|
|
561
|
+
throw new Error(`Unknown method: ${name}`);
|
|
562
|
+
const b = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
563
|
+
if (ix.discriminator.compare(b.subarray(0, ix.discriminator.length)) !== 0)
|
|
564
|
+
throw new Error(`Invalid instruction discriminator for ${name}`);
|
|
565
|
+
return this.readFields(b, ix.discriminator.length, ix.args, NO_ENV, name)[0];
|
|
566
|
+
}
|
|
567
|
+
}
|
package/dist/testing.d.ts
CHANGED
|
@@ -12,11 +12,11 @@
|
|
|
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
|
|
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, { type Idl } from "@anchor-lang/core";
|
|
20
20
|
import { type Address, type Instruction, type KeyPairSigner } from "@solana/kit";
|
|
21
21
|
import { FailedTransactionMetadata, LiteSVM, TransactionMetadata } from "litesvm";
|
|
22
22
|
import { loadClonedAccounts } from "./tools/clone.js";
|
|
@@ -25,8 +25,47 @@ export { type SvmConnection, svmConnection };
|
|
|
25
25
|
export * from "./testing-stake.js";
|
|
26
26
|
/** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
|
|
27
27
|
export { loadClonedAccounts };
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
/** An Anchor IDL (spec 0.1.0), as `typesol build` writes it and Anchor's `Idl` type describes it. */
|
|
29
|
+
export interface TestIdl {
|
|
30
|
+
address: string;
|
|
31
|
+
metadata?: unknown;
|
|
32
|
+
instructions: readonly {
|
|
33
|
+
name: string;
|
|
34
|
+
discriminator: readonly number[];
|
|
35
|
+
accounts: readonly unknown[];
|
|
36
|
+
args: readonly {
|
|
37
|
+
name: string;
|
|
38
|
+
type: unknown;
|
|
39
|
+
}[];
|
|
40
|
+
returns?: unknown;
|
|
41
|
+
}[];
|
|
42
|
+
accounts?: readonly {
|
|
43
|
+
name: string;
|
|
44
|
+
discriminator: readonly number[];
|
|
45
|
+
}[];
|
|
46
|
+
events?: readonly {
|
|
47
|
+
name: string;
|
|
48
|
+
discriminator: readonly number[];
|
|
49
|
+
}[];
|
|
50
|
+
errors?: readonly {
|
|
51
|
+
code: number;
|
|
52
|
+
name: string;
|
|
53
|
+
msg?: string;
|
|
54
|
+
}[];
|
|
55
|
+
types?: readonly unknown[];
|
|
56
|
+
constants?: readonly unknown[];
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Anchor's `BorshCoder` for the program's IDL (`instruction`, `accounts`, `events`, `types`), which works with BN and
|
|
60
|
+
* PublicKey values. `@anchor-lang/core` is loaded the first time `t.coder` is read: install it to use `t.coder`.
|
|
61
|
+
* The other helpers do not need it.
|
|
62
|
+
*/
|
|
63
|
+
export interface AnchorBorshCoder {
|
|
64
|
+
instruction: any;
|
|
65
|
+
accounts: any;
|
|
66
|
+
events: any;
|
|
67
|
+
types: any;
|
|
68
|
+
}
|
|
30
69
|
export type Result = TransactionMetadata | FailedTransactionMetadata;
|
|
31
70
|
/** An account for an instruction: an address, a keypair (which then signs), or null to leave an optional one out. */
|
|
32
71
|
export type AccountInput = Address | KeyPairSigner | null;
|
|
@@ -38,8 +77,9 @@ export type SeedInput = string | Address | KeyPairSigner | Uint8Array | bigint;
|
|
|
38
77
|
export interface TestProgram {
|
|
39
78
|
svm: LiteSVM;
|
|
40
79
|
programId: Address;
|
|
41
|
-
idl:
|
|
42
|
-
|
|
80
|
+
idl: TestIdl;
|
|
81
|
+
/** Anchor's BorshCoder for this IDL; needs `@anchor-lang/core` installed (loaded on first use). */
|
|
82
|
+
readonly coder: AnchorBorshCoder;
|
|
43
83
|
/** A new keypair funded with `sol` SOL (default 10). */
|
|
44
84
|
wallet(sol?: number): Promise<KeyPairSigner>;
|
|
45
85
|
/** The program's PDA for these seeds. */
|
|
@@ -62,6 +102,14 @@ export interface TestProgram {
|
|
|
62
102
|
account<T = Record<string, unknown>>(type: string, address: Address): Promise<T | null>;
|
|
63
103
|
/** A successful instruction's return data, decoded by its IDL `returns` type. */
|
|
64
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
|
+
}[];
|
|
65
113
|
/** Lamports of any account (0 when it does not exist). */
|
|
66
114
|
balance(address: Address): bigint;
|
|
67
115
|
/** A kit RPC and subscriptions pair over this LiteSVM, for the generated client (`svmConnection`). */
|
|
@@ -100,4 +148,4 @@ export interface TestProgram {
|
|
|
100
148
|
/** Build `program` of the project around `from` (a file URL such as import.meta.url, or a directory) and load it. */
|
|
101
149
|
export declare function testProgram(program: string, from: string | URL): Promise<TestProgram>;
|
|
102
150
|
/** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */
|
|
103
|
-
export declare function programHarness(svm: LiteSVM, programId: Address, idl:
|
|
151
|
+
export declare function programHarness(svm: LiteSVM, programId: Address, idl: TestIdl): TestProgram;
|