/
instruction.ts
356 lines (327 loc) · 9.45 KB
/
instruction.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import bs58 from "bs58";
import { Buffer } from "buffer";
import { Layout } from "buffer-layout";
import camelCase from "camelcase";
import { snakeCase } from "snake-case";
import { sha256 } from "js-sha256";
import * as borsh from "@coral-xyz/borsh";
import { AccountMeta, PublicKey } from "@solana/web3.js";
import {
Idl,
IdlField,
IdlType,
IdlTypeDef,
IdlAccount,
IdlAccountItem,
IdlTypeDefTyStruct,
IdlTypeVec,
IdlTypeOption,
IdlTypeDefined,
IdlAccounts,
} from "../../idl.js";
import { IdlCoder } from "./idl.js";
import { InstructionCoder } from "../index.js";
/**
* Namespace for global instruction function signatures (i.e. functions
* that aren't namespaced by the state or any of its trait implementations).
*/
export const SIGHASH_GLOBAL_NAMESPACE = "global";
/**
* Encodes and decodes program instructions.
*/
export class BorshInstructionCoder implements InstructionCoder {
// Instruction args layout. Maps namespaced method
private ixLayout: Map<string, Layout>;
// Base58 encoded sighash to instruction layout.
private sighashLayouts: Map<string, { layout: Layout; name: string }>;
public constructor(private idl: Idl) {
this.ixLayout = BorshInstructionCoder.parseIxLayout(idl);
const sighashLayouts = new Map();
idl.instructions.forEach((ix) => {
const sh = sighash(SIGHASH_GLOBAL_NAMESPACE, ix.name);
sighashLayouts.set(bs58.encode(sh), {
layout: this.ixLayout.get(ix.name),
name: ix.name,
});
});
this.sighashLayouts = sighashLayouts;
}
/**
* Encodes a program instruction.
*/
public encode(ixName: string, ix: any): Buffer {
return this._encode(SIGHASH_GLOBAL_NAMESPACE, ixName, ix);
}
private _encode(nameSpace: string, ixName: string, ix: any): Buffer {
const buffer = Buffer.alloc(1000); // TODO: use a tighter buffer.
const methodName = camelCase(ixName);
const layout = this.ixLayout.get(methodName);
if (!layout) {
throw new Error(`Unknown method: ${methodName}`);
}
const len = layout.encode(ix, buffer);
const data = buffer.slice(0, len);
return Buffer.concat([sighash(nameSpace, ixName), data]);
}
private static parseIxLayout(idl: Idl): Map<string, Layout> {
const ixLayouts = idl.instructions.map((ix): [string, Layout<unknown>] => {
let fieldLayouts = ix.args.map((arg: IdlField) =>
IdlCoder.fieldLayout(
arg,
Array.from([...(idl.accounts ?? []), ...(idl.types ?? [])])
)
);
const name = camelCase(ix.name);
return [name, borsh.struct(fieldLayouts, name)];
});
return new Map(ixLayouts);
}
/**
* Decodes a program instruction.
*/
public decode(
ix: Buffer | string,
encoding: "hex" | "base58" = "hex"
): Instruction | null {
if (typeof ix === "string") {
ix = encoding === "hex" ? Buffer.from(ix, "hex") : bs58.decode(ix);
}
let sighash = bs58.encode(ix.slice(0, 8));
let data = ix.slice(8);
const decoder = this.sighashLayouts.get(sighash);
if (!decoder) {
return null;
}
return {
data: decoder.layout.decode(data),
name: decoder.name,
};
}
/**
* Returns a formatted table of all the fields in the given instruction data.
*/
public format(
ix: Instruction,
accountMetas: AccountMeta[]
): InstructionDisplay | null {
return InstructionFormatter.format(ix, accountMetas, this.idl);
}
}
export type Instruction = {
name: string;
data: Object;
};
export type InstructionDisplay = {
args: { name: string; type: string; data: string }[];
accounts: {
name?: string;
pubkey: PublicKey;
isSigner: boolean;
isWritable: boolean;
}[];
};
class InstructionFormatter {
public static format(
ix: Instruction,
accountMetas: AccountMeta[],
idl: Idl
): InstructionDisplay | null {
const idlIx = idl.instructions.filter((i) => ix.name === i.name)[0];
if (idlIx === undefined) {
console.error("Invalid instruction given");
return null;
}
const args = idlIx.args.map((idlField) => {
return {
name: idlField.name,
type: InstructionFormatter.formatIdlType(idlField.type),
data: InstructionFormatter.formatIdlData(
idlField,
ix.data[idlField.name],
idl.types
),
};
});
const flatIdlAccounts = InstructionFormatter.flattenIdlAccounts(
idlIx.accounts
);
const accounts = accountMetas.map((meta, idx) => {
if (idx < flatIdlAccounts.length) {
return {
name: flatIdlAccounts[idx].name,
...meta,
};
}
// "Remaining accounts" are unnamed in Anchor.
else {
return {
name: undefined,
...meta,
};
}
});
return {
args,
accounts,
};
}
private static formatIdlType(idlType: IdlType): string {
if (typeof idlType === "string") {
return idlType as string;
}
if ("vec" in idlType) {
return `Vec<${this.formatIdlType(idlType.vec)}>`;
}
if ("option" in idlType) {
return `Option<${this.formatIdlType(idlType.option)}>`;
}
if ("defined" in idlType) {
return idlType.defined;
}
if ("array" in idlType) {
return `Array<${idlType.array[0]}; ${idlType.array[1]}>`;
}
throw new Error(`Unknown IDL type: ${idlType}`);
}
private static formatIdlData(
idlField: IdlField,
data: Object,
types?: IdlTypeDef[]
): string {
if (typeof idlField.type === "string") {
return data.toString();
}
if (idlField.type.hasOwnProperty("vec")) {
return (
"[" +
(<Array<IdlField>>data)
.map((d: IdlField) =>
this.formatIdlData(
{ name: "", type: (<IdlTypeVec>idlField.type).vec },
d
)
)
.join(", ") +
"]"
);
}
if (idlField.type.hasOwnProperty("option")) {
return data === null
? "null"
: this.formatIdlData(
{ name: "", type: (<IdlTypeOption>idlField.type).option },
data,
types
);
}
if (idlField.type.hasOwnProperty("defined")) {
if (types === undefined) {
throw new Error("User defined types not provided");
}
const filtered = types.filter(
(t) => t.name === (<IdlTypeDefined>idlField.type).defined
);
if (filtered.length !== 1) {
throw new Error(
`Type not found: ${(<IdlTypeDefined>idlField.type).defined}`
);
}
return InstructionFormatter.formatIdlDataDefined(
filtered[0],
data,
types
);
}
return "unknown";
}
private static formatIdlDataDefined(
typeDef: IdlTypeDef,
data: Object,
types: IdlTypeDef[]
): string {
if (typeDef.type.kind === "struct") {
const struct: IdlTypeDefTyStruct = typeDef.type;
const fields = Object.keys(data)
.map((k) => {
const f = struct.fields.filter((f) => f.name === k)[0];
if (f === undefined) {
throw new Error("Unable to find type");
}
return (
k + ": " + InstructionFormatter.formatIdlData(f, data[k], types)
);
})
.join(", ");
return "{ " + fields + " }";
} else {
if (typeDef.type.variants.length === 0) {
return "{}";
}
// Struct enum.
if (typeDef.type.variants[0].name) {
const variants = typeDef.type.variants;
const variant = Object.keys(data)[0];
const enumType = data[variant];
const namedFields = Object.keys(enumType)
.map((f) => {
const fieldData = enumType[f];
const idlField = variants[variant]?.filter(
(v: IdlField) => v.name === f
)[0];
if (idlField === undefined) {
throw new Error("Unable to find variant");
}
return (
f +
": " +
InstructionFormatter.formatIdlData(idlField, fieldData, types)
);
})
.join(", ");
const variantName = camelCase(variant, { pascalCase: true });
if (namedFields.length === 0) {
return variantName;
}
return `${variantName} { ${namedFields} }`;
}
// Tuple enum.
else {
// TODO.
return "Tuple formatting not yet implemented";
}
}
}
private static flattenIdlAccounts(
accounts: IdlAccountItem[],
prefix?: string
): IdlAccount[] {
return accounts
.map((account) => {
const accName = sentenceCase(account.name);
if (account.hasOwnProperty("accounts")) {
const newPrefix = prefix ? `${prefix} > ${accName}` : accName;
return InstructionFormatter.flattenIdlAccounts(
(<IdlAccounts>account).accounts,
newPrefix
);
} else {
return {
...(<IdlAccount>account),
name: prefix ? `${prefix} > ${accName}` : accName,
};
}
})
.flat();
}
}
function sentenceCase(field: string): string {
const result = field.replace(/([A-Z])/g, " $1");
return result.charAt(0).toUpperCase() + result.slice(1);
}
// Not technically sighash, since we don't include the arguments, as Rust
// doesn't allow function overloading.
function sighash(nameSpace: string, ixName: string): Buffer {
let name = snakeCase(ixName);
let preimage = `${nameSpace}:${name}`;
return Buffer.from(sha256.digest(preimage)).slice(0, 8);
}