forked from miguelmota/ethereum-input-data-decoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
267 lines (221 loc) · 6.31 KB
/
index.js
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
const fs = require('fs')
const ethabi = require('ethereumjs-abi')
const ethers = require('ethers')
const Buffer = require('buffer/').Buffer
const isBuffer = require('is-buffer')
class InputDataDecoder {
constructor (prop) {
this.abi = []
if (typeof prop === `string`) {
this.abi = JSON.parse(fs.readFileSync(prop))
} else if (prop instanceof Object) {
this.abi = prop
} else {
throw new TypeError(`Must pass ABI array object or file path to constructor`)
}
}
decodeConstructor (data) {
if (isBuffer(data)) {
data = data.toString('utf8')
}
if (typeof data !== 'string') {
data = ''
}
data = data.trim()
for (var i = 0; i < this.abi.length; i++) {
const obj = this.abi[i]
if (obj.type !== 'constructor') {
continue
}
const method = obj.name || null
const types = obj.inputs ? obj.inputs.map(x => x.type) : []
const names = obj.inputs ? obj.inputs.map(x => x.name) : []
// take last 32 bytes
data = data.slice(-256)
if (data.length !== 256) {
throw new Error('fail')
}
if (data.indexOf('0x') !== 0) {
data = `0x${data}`
}
const inputs = ethers.utils.defaultAbiCoder.decode(types, data)
return {
method,
types,
inputs,
names
}
}
throw new Error('not found')
}
decodeData (data) {
if (isBuffer(data)) {
data = data.toString('utf8')
}
if (typeof data !== 'string') {
data = ''
}
data = data.trim()
const dataBuf = Buffer.from(data.replace(/^0x/, ''), 'hex')
const methodId = toHexString(dataBuf.subarray(0, 4))
var inputsBuf = dataBuf.subarray(4)
const result = this.abi.reduce((acc, obj) => {
if (obj.type === 'constructor') return acc
if (obj.type === 'event') return acc
const method = obj.name || null
let types = obj.inputs ? obj.inputs.map(x => {
if (x.type.includes('tuple')) {
return x
} else {
return x.type
}
}) : []
let names = obj.inputs ? obj.inputs.map(x => {
if (x.type.includes('tuple')) {
return [x.name, x.components.map(a => a.name)]
} else {
return x.name
}
}) : []
const hash = genMethodId(method, types)
if (hash === methodId) {
let inputs = []
try {
inputsBuf = normalizeAddresses(types, inputsBuf)
inputs = ethabi.rawDecode(types, inputsBuf)
} catch (err) {
inputs = ethers.utils.defaultAbiCoder.decode(types, inputsBuf)
// defaultAbiCoder attaches some unwanted properties to the list object
inputs = deepRemoveUnwantedArrayProperties(inputs)
// TODO: do this normalization into normalizeAddresses
inputs = inputs.map((input, i) => {
if (types[i].components) {
const tupleTypes = types[i].components
return deepStripTupleAddresses(input, tupleTypes)
}
if (types[i] === 'address') {
return input.split('0x')[1]
}
if (types[i] === 'address[]') {
return input.map(address => address.split('0x')[1])
}
return input
})
}
// Map any tuple types into arrays
const typesToReturn = types.map(t => {
if (t.components) {
const arr = t.components.reduce((acc, cur) => [...acc, cur.type], [])
const tupleStr = `(${arr.join(',')})`
if (t.type === 'tuple[]') return tupleStr + '[]'
return tupleStr
}
return t
})
return {
method,
types: typesToReturn,
inputs,
names
}
}
return acc
}, { method: null, types: [], inputs: [], names: [] })
if (!result.method) {
try {
const decoded = this.decodeConstructor(data)
if (decoded) {
return decoded
}
} catch (err) { }
}
return result
}
}
// remove 0x from addresses
function deepStripTupleAddresses (input, tupleTypes) {
return input.map((item, i) => {
const type = tupleTypes[i].type
if (type === 'address' && typeof item === 'string') {
return item.split('0x')[1]
}
if (type === 'address[]' || Array.isArray()) {
return item.map(a => a.split('0x')[1])
}
return item
})
}
function deepRemoveUnwantedArrayProperties (arr) {
return [...arr.map(item => {
if (Array.isArray(item)) return deepRemoveUnwantedArrayProperties(item)
return item
})]
}
function normalizeAddresses (types, input) {
let offset = 0
for (let i = 0; i < types.length; i++) {
const type = types[i]
if (type === 'address') {
input.set(Buffer.alloc(12), offset)
}
if (isArray(type)) {
const size = parseTypeArray(type)
if (size && size !== 'dynamic') {
offset += 32 * size
} else {
offset += 32
}
} else {
offset += 32
}
}
return input
}
function parseTypeArray (type) {
const tmp = type.match(/(.*)\[(.*?)\]$/)
if (tmp) {
return tmp[2] === '' ? 'dynamic' : parseInt(tmp[2], 10)
}
return null
}
function isArray (type) {
return type.lastIndexOf(']') === type.length - 1
}
function handleInputs (input, tupleArray) {
if (input instanceof Object && input.components) {
input = input.components
}
if (!Array.isArray(input)) {
if (input instanceof Object && input.type) {
return input.type
}
return input
}
let ret = '(' + input.reduce((acc, x) => {
if (x.type === 'tuple') {
acc.push(handleInputs(x.components))
} else if (x.type === 'tuple[]') {
acc.push(handleInputs(x.components) + '[]')
} else {
acc.push(x.type)
}
return acc
}, []).join(',') + ')'
if (tupleArray) {
return ret + '[]'
}
return ret
}
function genMethodId (methodName, types) {
const input = methodName + '(' + (types.reduce((acc, x) => {
acc.push(handleInputs(x, x.type === 'tuple[]'))
return acc
}, []).join(',')) + ')'
return ethers.utils.keccak256(Buffer.from(input)).slice(2, 10)
}
function toHexString (byteArray) {
return Array.from(byteArray, function (byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2)
}).join('')
}
module.exports = InputDataDecoder