-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog-extractor.js
312 lines (280 loc) Β· 9.7 KB
/
log-extractor.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
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
const axios = require('axios')
const fs = require('fs')
require('dotenv').config()
const { ethers } = require('ethers')
const rateLimit = require('axios-rate-limit')
const { Client } = require('@elastic/elasticsearch')
const elasticClient = new Client({
cloud: {
id: process.env.ELASTIC_CLOUD_ID,
},
auth: {
username: process.env.ELASTIC_USER,
password: process.env.ELASTIC_PASSWORD,
},
})
elasticClient
.info()
.then((response) =>
console.log(
`started elastic client:\n ${JSON.stringify(response, null, 2)}`,
),
)
.catch((error) => console.error(`β ${error}`))
const http = rateLimit(axios.create(), {
maxRequests: 1,
perMilliseconds: 2000,
maxRPS: 1,
})
const tatumHeaders = {
'x-api-key': process.env.TATUM_API_KEY_2,
}
const provider = new ethers.providers.AlchemyProvider(
'homestead',
process.env.ALCHEMY_API_KEY,
)
const isContract = async (address) => {
let addressCode = await provider.getCode(address)
return addressCode !== '0x'
}
const fetchContractABI = async (contractAddress) => {
http.getMaxRPS()
console.log(`fethcing abi for ${contractAddress}`)
try {
const abiResponse = await http.get(
`https://api.etherscan.io/api?module=contract&action=getabi&address=${contractAddress}&apikey=${process.env.ETHERSCAN_API_KEY}`,
)
return abiResponse.data.result
} catch (error) {
console.log(`β ${error}`)
}
}
const fetchBlockFromTatum = async (currentBlockNum) => {
try {
const blockRes = await axios.get(
`${process.env.TATUM_URL}/${currentBlockNum}`,
tatumHeaders,
)
return blockRes.data
} catch (error) {
console.log(`β ${error}`)
}
}
const fetchCurrentBlockNum = async () => {
try {
let config = {
url: `${process.env.TATUM_URL}/current`,
headers: tatumHeaders,
}
const currentBlockRes = await http.get(
`${process.env.TATUM_URL}/current`,
tatumHeaders,
)
return currentBlockRes.data
} catch (error) {
console.log(`β ${error}`)
}
}
const ingestDecodedLog = async (rawLog, decodedLog, txs) => {
let indexName = 'decoded-evm-logs'
await ingestEthEventLog(rawLog, decodedLog, txs, indexName, ['decoded'])
}
const ingestNotParsedLog = async (log, txs) => {
let indexName = 'not-parsed-evm-logs'
await ingestEthEventLog(log, {}, txs, indexName, ['not-decoded', 'not-parsed'])
}
const ingestNotDecodedLog = async (log, txs) => {
let indexName = 'not-decoded-evm-logs'
await ingestEthEventLog(log, {}, txs, indexName, [
'not-decoded',
'abi-not-available',
])
}
const ingestEmptyLog = async (log, txs) => {
let indexName = 'empty-evm-logs'
let logId = Math.floor(Math.random() * 100)
await ingestEthEventLog(log, log, txs, indexName, ['empty-log'])
}
const ingestEthEventLog = async (rawlog, decodedLog, txs, indexName, additionalTags) => {
let tags = [process.env.CHAIN, ...additionalTags]
const document = {
index: indexName,
body: {
type: "event",
// TODO: needs to be fetched from etherscan
contract: "unknown",
from: txs.from,
// abi is needed to decode the event name
name: !decodedLog || Object.keys(decodedLog).length === 0 ? "unknown" : decodedLog.eventFragment.name,
status: txs.status === true ? "success" : "fail",
chain: process.env.CHAIN,
tags: tags,
blockNumber: txs.blockNumber,
// TODO: propagate block timestamp
timestamp: new Date(),
metadata: decodedLog,
rawData: rawlog,
address: txs.to
},
}
try {
console.log(`π ingesting event log to index: ${indexName}`)
console.log(`π± Ingesting event log: ${JSON.stringify(document, null, 2)}`)
await elasticClient.index(document)
await elasticClient.indices.refresh({ index: indexName })
} catch (error) {
console.log(
`β error ingesting eth event log: ${error} in index ${indexName} and log: ${rawlog}`,
)
}
}
const ingestEthTransaction = async (parsedTxs, rawTxs, additionalTags) => {
let tags = [process.env.CHAIN, ...additionalTags]
const decodedTransactionIndex = !parsedTxs || Object.keys(parsedTxs).length === 0 ? 'not-decoded-evm-transactions' : 'decoded-evm-transactions'
const document = {
index: decodedTransactionIndex,
body: {
type: "function",
// TODO: needs to be fetched from etherscan
contract: "unknown",
from: rawTxs.from,
// abi is needed to decode the event name
name: !parsedTxs || Object.keys(parsedTxs).length === 0 ? "unknown" : parsedTxs.name,
status: rawTxs.status === true ? "success" : "fail",
chain: process.env.CHAIN,
tags: tags,
blockNumber: rawTxs.blockNumber,
// TODO: propagate block timestamp
timestamp: new Date(),
metadata: parsedTxs,
rawData: rawTxs,
address: rawTxs.to
}
}
try {
console.log(`π Ingesting transaction to index: ${decodedTransactionIndex}`)
console.log(`π Ingesting transaction: ${JSON.stringify(document, null, 2)}`)
await elasticClient.index(document)
await elasticClient.indices.refresh({ index: decodedTransactionIndex })
} catch (error) {
console.log(
`β could't index a transaction in index ${decodedTransactionIndex}. error: ${error}. transaction: ${rawTxs}`,
)
}
}
const transformAndLoad = async (block, contractAddresses, abis) => {
await Promise.all(
block.transactions.map(async (txs) => {
// check if address is a contract address
const isContractAddress = await isContract(txs.to)
// console.log(`${txs.to} is a contracts? ${isContractAddress}`)
if (isContractAddress) {
contractAddresses.push(txs.to)
try {
// get abis
if (txs.logs && txs.logs.length > 0) {
const abiRes = await fetchContractABI(txs.to).catch(console.log)
abis[txs.to] = abiRes
if (abiRes.length > 0) {
const iface = new ethers.utils.Interface(abiRes)
// try parsing transaction
const parsedTransaction = iface.parseTransaction({data: txs.input, value: txs.value}) || {}
await ingestEthTransaction(parsedTransaction, txs,["parsed-transaction"]).catch(console.log)
// TODO: missing rate limit handling
// try to decode and ingest logs
await Promise.all(
txs.logs.map(async (log) => {
try {
if (abiRes === 'Contract source code not verified') {
await ingestNotDecodedLog(log, txs).catch(console.log)
console.log(
`β
ingested not decoded txs: ${JSON.stringify(log)}`,
)
} else {
let parsedLog = iface.parseLog(log)
await ingestDecodedLog(log, parsedLog, txs).catch(console.log)
console.log(
`β
ingested decoded txs: ${JSON.stringify(parsedLog)}`,
)
}
} catch (error) {
if (abiRes === 'Contract source code not verified') {
console.log(
`β [couldn't ingest not decoded log] error: ${error} // log: ${JSON.stringify(
log,
)}`,
)
} else {
console.log(
`β οΈ proceeding with ingestion without parsing because parsing/ingesting didn't work for the following log: ${JSON.stringify(
log,
)}`,
)
await ingestNotParsedLog(log, txs).catch(console.log)
}
}
}),
)
} else {
// ABI not available ingest raw transaction data
console.log(`------> ${abiRes.length}`)
console.log(
`β οΈ (type: ${typeof abiRes}) missed ${
txs.to
} // etherscan abi API responded: ${abiRes}`,
)
}
} else {
// transaction has no logs
await ingestEmptyLog({}, txs).catch(console.log)
console.log(
`β
ingested txs without logs: ${JSON.stringify(txs.logs)}`,
)
}
} catch (error) {
console.log(`β Ingestion failed with error ${error} || failed at transaction ${txs}`)
}
}
}),
)
}
class LogExtractor {
async run() {
try {
const currentBlockNum = await fetchCurrentBlockNum()
let block = await fetchBlockFromTatum(currentBlockNum)
console.log(
`current block is ${JSON.stringify(currentBlockNum, null, 2)}`,
)
let contractAddresses = []
let abis = {}
await transformAndLoad(block, contractAddresses, abis)
} catch (error) {
console.log(`β ${error}`)
}
}
async watch() {
try {
const provider = new ethers.providers.AlchemyWebSocketProvider(
process.env.RPC_NETWORK,
process.env.ALCHEMY_API_KEY,
)
provider.on('block', async (blockNum) => {
console.log(`π block ${blockNum} is mined`)
setTimeout(async () => {
let block = await fetchBlockFromTatum(blockNum)
console.log(`β
Fetched block ${block.transactions[0].blockNumber}`)
let contractAddresses = []
let abis = {}
await transformAndLoad(block, contractAddresses, abis)
}, process.env.TIMEOUT)
})
provider.on('error', async (error) => {
console.log(`β stream emitted tge following error: ${error}`)
})
} catch (error) {
console.log(`β ${error}`)
}
}
}
module.exports = LogExtractor