-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
abiParser.ts
311 lines (283 loc) · 7.61 KB
/
abiParser.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
/* eslint-disable no-param-reassign */
/* eslint-disable @typescript-eslint/no-use-before-define */
import type { Dictionary } from 'ts-essentials';
import type {
EnumType,
SvmOutputType,
SvmType,
TupleType,
StructType,
DatumType,
} from './parseSvmTypes';
import { parseSvmType, normalizeName } from './parseSvmTypes';
export interface AbiParameter {
name: string;
type: SvmType;
}
export interface AbiOutputParameter {
name: string;
type: SvmOutputType;
components?: AbiOutputParameter[];
}
export declare type Named<T> = {
name: string;
values: T;
};
export interface FunctionDocumentation {
author?: string;
details?: string;
notice?: string;
params?: { [paramName: string]: string };
return?: string;
}
export interface FunctionDeclaration {
name: string;
inputs: AbiParameter[];
outputs: AbiOutputParameter[];
documentation?: FunctionDocumentation;
}
export interface FunctionWithoutOutputDeclaration extends FunctionDeclaration {
outputs: [];
}
export interface FunctionWithoutInputDeclaration extends FunctionDeclaration {
inputs: [];
}
export interface Contract {
name: string;
rawName: string;
functions: Dictionary<FunctionDeclaration[]>;
structs: Dictionary<StructType[]>;
tuples: Dictionary<TupleType[]>;
enums: Dictionary<EnumType[]>;
documentation?: {
author?: string;
details?: string;
notice?: string;
};
}
export interface RawAbiParameter {
name: string;
type: string;
components?: RawAbiParameter[];
}
export interface RawAbiDefinition {
name: string;
inputs: RawAbiParameter[];
outputs: RawAbiParameter[];
type: string;
}
export interface DocumentationResult {
author?: string;
details?: string;
notice?: string;
title?: string;
methods?: { [methodName: string]: FunctionDocumentation };
}
/**
* Parses the ABI function declaration
*/
function parseFunctionDeclaration(
abiPiece: RawAbiDefinition,
registerStruct: (datum: DatumType) => void,
documentation?: DocumentationResult
): FunctionDeclaration {
return {
name: abiPiece.name,
inputs: parseInputs(registerStruct, abiPiece.inputs),
outputs: parseOutputs(registerStruct, abiPiece.outputs),
documentation: getFunctionDocumentation(abiPiece, documentation),
};
}
/**
* Parses the ABI parameters
*/
function parseRawAbiParameter(
rawAbiParameter: RawAbiParameter,
registerStruct: (datum: DatumType) => void
): AbiParameter {
return {
name: rawAbiParameter.name,
type: parseRawAbiParameterType(rawAbiParameter, registerStruct),
};
}
/**
* Parses the ABI parameter types
*/
function parseRawAbiParameterType(
rawAbiParameter: RawAbiParameter,
registerStruct: (datum: DatumType) => void
): SvmType {
const components =
rawAbiParameter.components &&
rawAbiParameter.components.map((component) => ({
name: component.name,
type: parseRawAbiParameterType(component, registerStruct),
}));
const parsed = parseSvmType(rawAbiParameter.type, components, rawAbiParameter.name);
switch (parsed.type) {
case 'struct':
registerStruct(parsed as StructType);
break;
case 'tuple':
registerStruct(parsed as TupleType);
break;
case 'enum':
registerStruct(parsed as EnumType);
break;
default:
break;
}
return parsed;
}
/**
* Parses the ABI function inputs
*/
function parseInputs(
registerStruct: (datum: DatumType) => void,
inputs?: Array<RawAbiParameter>
): AbiParameter[] {
return (inputs || [])
.filter((i) => i.type !== '()')
.map((e) => parseRawAbiParameter(e, registerStruct));
}
/**
* Parses the ABI function outputs
*/
function parseOutputs(
registerStruct: (datum: DatumType) => void,
outputs?: Array<RawAbiParameter>
): AbiOutputParameter[] {
if (!outputs || outputs.length === 0) {
return [{ name: '', type: { type: 'void' } }];
}
return outputs.filter((i) => i.type !== '()').map((e) => parseRawAbiParameter(e, registerStruct));
}
/**
* Parses the JSON abi
*/
export function parse(
abi: RawAbiDefinition[],
rawName: string,
documentation?: DocumentationResult
): Contract {
const functions: FunctionDeclaration[] = [];
const outputs: { struct: StructType[]; enum: EnumType[]; tuple: TupleType[] } = {
struct: [],
enum: [],
tuple: [],
};
/**
* Registers Structs used in the abi
*/
function registerComplexType(datum: DatumType): void {
if (
['struct', 'enum', 'tuple'].includes(datum.type) &&
outputs[datum.type].findIndex((s) => s.structName === datum.structName) === -1
) {
(outputs[datum.type] as Array<typeof datum>).push(datum);
}
}
abi.forEach((abiPiece) => {
if (abiPiece.type === 'function') {
functions.push(parseFunctionDeclaration(abiPiece, registerComplexType, documentation));
}
});
const functionGroup = functions.reduce((memo, value) => {
if (Array.isArray(memo[value.name])) {
memo[value.name].push(value);
} else {
memo[value.name] = [value];
}
return memo;
}, {} as Dictionary<FunctionDeclaration[]>);
const structGroup = outputs.struct.reduce((memo, value) => {
if (memo[value.structName]) {
memo[value.structName].push(value);
} else {
memo[value.structName] = [value];
}
return memo;
}, {} as Dictionary<StructType[]>);
const tupleGroup = outputs.tuple.reduce((memo, value) => {
if (memo[value.structName]) {
memo[value.structName].push(value);
} else {
memo[value.structName] = [value];
}
return memo;
}, {} as Dictionary<TupleType[]>);
const enumGroup = outputs.enum.reduce((memo, value) => {
if (memo[value.structName]) {
memo[value.structName].push(value);
} else {
memo[value.structName] = [value];
}
return memo;
}, {} as Dictionary<EnumType[]>);
return {
name: normalizeName(rawName),
rawName,
functions: functionGroup,
structs: structGroup,
tuples: tupleGroup,
enums: enumGroup,
};
}
/**
* Parses the ABI function documentation
*/
export function getFunctionDocumentation(
abiPiece: RawAbiDefinition,
documentation?: DocumentationResult
): FunctionDocumentation | undefined {
const docKey = `${abiPiece.name}(${(abiPiece.inputs || []).map(({ type }) => type).join(',')})`;
return documentation && documentation.methods && documentation.methods[docKey];
}
class MalformedAbiError extends Error {}
/**
* Extract JSON abi from raw json strings
*/
export function extractAbi(rawJson: string): RawAbiDefinition[] {
let json;
try {
json = JSON.parse(rawJson);
} catch {
throw new MalformedAbiError('Not a json');
}
if (!json) {
throw new MalformedAbiError('Not a json');
}
if (Array.isArray(json)) {
return json;
}
if (Array.isArray(json.abi)) {
return json.abi;
}
if (json.compilerOutput && Array.isArray(json.compilerOutput.abi)) {
return json.compilerOutput.abi;
}
throw new MalformedAbiError('Not a valid ABI');
}
/**
* Parses the ABI function function documentation to user docs
*/
export function extractDocumentation(rawContents: string): DocumentationResult | undefined {
let json;
try {
json = JSON.parse(rawContents);
} catch {
return undefined;
}
if (!json || (!json.devdoc && !json.userdoc)) return undefined;
const result: DocumentationResult = json.devdoc || {};
// Merge devdoc and userdoc objects
if (json.userdoc) {
result.notice = json.userdoc.notice;
if (!json.userdoc.methods) return result;
result.methods = result.methods || {};
Object.entries<{ notice: string }>(json.userdoc.methods).forEach(([key, { notice }]) => {
if (result.methods) result.methods[key] = { ...result.methods[key], notice };
});
}
return result;
}