-
Notifications
You must be signed in to change notification settings - Fork 22
/
decode.ts
255 lines (237 loc) · 7.99 KB
/
decode.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
import { AbiCoder } from 'web3-eth-abi';
import { toChecksumAddress } from 'web3-utils';
import { parseBigInt } from '../utils/bn';
import { createModuleDebug, TRACE_ENABLED } from '../utils/debug';
import { DataSize, elementType, getDataSize, intBits, isArrayType } from './datatypes';
import { AbiItemDefinition } from './item';
import { computeSignature } from './signature';
const { trace } = createModuleDebug('abi:decode');
export type ScalarValue = string | number | boolean;
export type Value = ScalarValue | ScalarValue[];
export interface DecodedParameter {
name?: string;
type: string;
value: Value;
}
export interface DecodedFunctionCall {
name: string;
signature: string;
params: DecodedParameter[];
args?: { [name: string]: Value };
}
export interface DecodedLogEvent {
name: string;
signature: string;
params: DecodedParameter[];
args?: { [name: string]: Value };
}
/** Translates decoded value (by abicoder) to the form we want to emit to the output */
export function parseParameterValue(value: string | number | boolean, type: string): ScalarValue {
if (type === 'bool') {
if (typeof value === 'boolean') {
return value;
}
switch (value) {
case '1':
return true;
case '0':
return false;
default:
throw new Error(`Invalid boolean value: ${value}`);
}
}
if (type.startsWith('uint')) {
if (intBits(type, 'uint') <= 53) {
return parseInt(value as string, 10);
} else {
return parseBigInt(value as string);
}
}
if (type.startsWith('int')) {
if (typeof value === 'number') {
return value;
}
if (intBits(type, 'int') <= 53) {
return parseInt(value as string, 10);
} else {
return parseBigInt(value as string);
}
}
if (type === 'address') {
return toChecksumAddress(value as string);
}
return value;
}
export function getInputSize(abi: AbiItemDefinition): DataSize {
try {
return abi.inputs
.map(input => getDataSize(input.type))
.reduce((total, cur) => ({ length: total.length + cur.length, exact: total.exact && cur.exact }), {
length: 0,
exact: true,
});
} catch (e) {
throw new Error(`Failed to determine input size for ${computeSignature(abi)}: ${e.message}`);
}
}
export function decodeFunctionCall(
data: string,
abi: AbiItemDefinition,
signature: string,
abiCoder: AbiCoder,
anonymous: boolean
): DecodedFunctionCall {
const inputs = abi.inputs ?? [];
const decodedParams = abiCoder.decodeParameters(
inputs.map(i => i.type),
data.slice(10)
);
const params: DecodedParameter[] = [];
const args: { [name: string]: string | number | boolean | Array<string | number | boolean> } = {};
for (let i = 0; i < inputs.length; i++) {
const input = inputs[i];
const rawValue = decodedParams[i];
const value = isArrayType(input.type)
? (rawValue as string[]).map(v => parseParameterValue(v, elementType(input.type)))
: parseParameterValue(rawValue, input.type);
args[input.name!] = value;
params.push({
name: anonymous ? undefined : input.name,
type: input.type,
value,
});
}
return {
name: abi.name!,
signature,
params,
args: anonymous ? undefined : args,
};
}
export function decodeBestMatchingFunctionCall(
data: string,
abis: AbiItemDefinition[],
abiCoder: AbiCoder,
anonymous: boolean
): DecodedFunctionCall {
if (abis.length === 1) {
// short-circut most common case
return decodeFunctionCall(data, abis[0], computeSignature(abis[0]), abiCoder, anonymous);
}
const abisWithSize = abis.map(abi => [abi, getInputSize(abi)] as const);
const dataLength = (data.length - 10) / 2;
let lastError: Error | undefined;
// Attempt to find function signature with exact match of input data length
for (const [abi, { length, exact }] of abisWithSize) {
if (dataLength === length && exact) {
try {
return decodeFunctionCall(data, abi, computeSignature(abi), abiCoder, anonymous);
} catch (e) {
lastError = e;
if (TRACE_ENABLED) {
trace(
'Failed to decode function call using signature %s with exact size match of %d bytes',
computeSignature(abi),
length
);
}
}
}
}
// Consider dynamaic data types
for (const [abi, { length, exact }] of abisWithSize) {
if (dataLength >= length && !exact) {
try {
return decodeFunctionCall(data, abi, computeSignature(abi), abiCoder, anonymous);
} catch (e) {
lastError = e;
if (TRACE_ENABLED) {
trace(
'Failed to decode function call using signature %s with size match of %d bytes (min size %d bytes)',
computeSignature(abi),
dataLength,
length
);
}
}
}
}
// Brute-force try all ABI signatures, use the first one that doesn't throw on decode
for (const abi of abis) {
try {
return decodeFunctionCall(data, abi, computeSignature(abi), abiCoder, anonymous);
} catch (e) {
lastError = e;
}
}
throw lastError ?? new Error('Unable to decode');
}
export function decodeLogEvent(
data: string,
topics: string[],
abi: AbiItemDefinition,
signature: string,
abiCoder: AbiCoder,
anonymous: boolean
): DecodedLogEvent {
const nonIndexedTypes = abi.inputs.filter(i => !i.indexed).map(i => i.type);
const decodedData = abiCoder.decodeParameters(nonIndexedTypes, data.slice(2));
let topicIndex = 1;
let dataIndex = 0;
const args: { [k: string]: Value } = {};
const params = abi.inputs.map(input => {
let value;
if (input.indexed) {
if (isArrayType(input.type)) {
topicIndex++;
// we can't decode arrays since there is only a hash the log
value = [] as string[];
} else {
let rawValue = topics[topicIndex++];
if (input.type === 'address') {
rawValue = '0x' + rawValue.slice(-40);
}
value = parseParameterValue(rawValue, input.type);
}
} else {
const rawValue = decodedData[dataIndex++];
value = isArrayType(input.type)
? (rawValue as string[]).map(v => parseParameterValue(v, elementType(input.type)))
: parseParameterValue(rawValue, input.type);
}
args[input.name] = value;
return {
name: anonymous ? undefined : input.name,
type: input.type,
value,
};
});
return {
name: abi.name,
signature,
params,
args: anonymous ? undefined : args,
};
}
export function decodeBestMatchingLogEvent(
data: string,
topics: string[],
abis: AbiItemDefinition[],
abiCoder: AbiCoder,
anonymous: boolean
): DecodedFunctionCall {
// No need to prioritize and check event logs for hash collisions since with the longer hash
// collisions are very unlikely
let lastError: Error | undefined;
for (const abi of abis) {
try {
return decodeLogEvent(data, topics, abi, computeSignature(abi), abiCoder, anonymous);
} catch (e) {
lastError = e;
if (TRACE_ENABLED) {
trace('Failed to decode log event', e);
}
}
}
throw lastError ?? new Error('Unable to decode log event');
}