/
server.js
292 lines (256 loc) · 10.4 KB
/
server.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
console.log('Server-side code running');
const express = require('express');
// XMLHTTPRequest
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
//Web3
var Web3 = require('web3');
node = 'https://mainnet.infura.io/v3/46d1afae8b55464585222887f55eab6a';
const web3 = new Web3(new Web3.providers.HttpProvider(node));
// Uniswap ABI
var uniswapAbi = require("./public/contracts/uniswap_exchange_contract/abi.json");
// Elasticsearch
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
// Current block
// Call the get current block function
getCurrentBlock().then(value => blockNumber = value);
// Get the current block
function getCurrentBlock() {
return new Promise(function(fulfill, reject) {
web3.eth.getBlockNumber(function(error, content) {
if (error) reject(error)
else fulfill(content);
})
})
}
// Pushes a bulk data object into Elasticsearch using the .bulk feature
function bulkIngest(bulkData) {
client.bulk(bulkData, function(error, response) {
if (error) {
console.error(error);
return;
} else {
console.log(response); // I don't recommend this but I like having my console flooded with stuff. It looks cool. Like I'm compiling a kernel really fast.
}
});
}
// Check to see if a single item exists in Elasticsearch
function checkIfItemExists(theUrl) {
request = new XMLHttpRequest();
console.log("Checking URL: " + theUrl);
request.open('GET', theUrl, /* async = */ false);
request.send();
console.log('status code: ' + request.status);
if (request.status === 404) {
return false;
} else {
return true;
}
}
// Call this function like this
// await wait(500);
function wait(ms) {
return new Promise(r => setTimeout(r, ms));
}
// Loads in all of the contract addresses and abi, creates a bulk json object and then calls bulkIngest function
async function loadContracts(uniswapAbi) {
url = "http://localhost:9200/uniswap_exchange_register/_all/";
for (var key in uniswapAbi) {
if (uniswapAbi[key]["type"] === "event") {
var eventName = uniswapAbi[key]["name"];
var eventInputs = uniswapAbi[key]["inputs"];
var uniswapAddresses = require("./public/contracts/uniswap_exchange_contract/addresses.json");
//console.log(JSON.stringify(uniswapAddresses));
var bulkData = {};
var theBodyArray = [];
for (var key in uniswapAddresses) {
if (uniswapAddresses.hasOwnProperty(key)) {
console.log("Processing: " + uniswapAddresses[key]);
theUrlWithKey = url + uniswapAddresses[key];
var contractExists = checkIfItemExists(theUrlWithKey);
if (contractExists == false) {
console.log("Item does not exist, let's add it ...")
theId = {};
actionDescription = {};
theId["_id"] = web3.utils.sha3(uniswapAddresses[key] + eventName);
theId["_type"] = "exchange";
theId["_index"] = 'uniswap_exchange_register';
actionDescription["index"] = theId;
theBodyArray.push(actionDescription);
theDocumentToIndex = {};
theDocumentToIndex["contractName"] = key;
theDocumentToIndex["contractAddress"] = uniswapAddresses[key];
theDocumentToIndex["lastIndexedBlock"] = 6627917;
theDocumentToIndex["eventName"] = eventName;
theDocumentToIndex["eventInputs"] = eventInputs;
theBodyArray.push(theDocumentToIndex);
}
}
}
}
if (theBodyArray.length > 0) {
bulkData["body"] = theBodyArray;
console.log("Adding the following data to the uniswap_exchange_register")
console.log(JSON.stringify(bulkData));
bulkIngest(bulkData);
await wait(1000);
}
}
}
function getRequestWithOnlyUrl(theUrl) {
theRequest = new XMLHttpRequest();
theUrl = theUrl;
console.log("Checking URL: " + theUrl);
theRequest.open('GET', theUrl, /* async = */ false);
theRequest.send();
if (theRequest.status >= 200 && theRequest.status < 300) {
return theRequest.responseText;
} else {
console.log(theRequest.status);
}
}
async function harvestContracts(){
var theGetHitsUrl = "http://localhost:9200/uniswap_exchange_register/_search/?filter_path=hits.total";
var theTotalHits = JSON.parse(getRequestWithOnlyUrl(theGetHitsUrl));
var registerLength = theTotalHits["hits"]["total"];
console.log(registerLength);
for(var i = 0; i < registerLength; i++){
console.log("Processing " + i + " of " + registerLength);
// Fetch every combination of "contract" and "event type" and process one by one
theGetSingleEventUrl = "http://localhost:9200/uniswap_exchange_register/_search/?from=" + i + "&size=1&filter_path=hits.hits._source";
singleEventFromRegister = JSON.parse(getRequestWithOnlyUrl(theGetSingleEventUrl));
// Instantiate variables which hold the key values for the web3 harvesting
lastIndexedBlock = singleEventFromRegister["hits"].hits[0]._source.lastIndexedBlock;
eventName = singleEventFromRegister["hits"].hits[0]._source.eventName;
// Instantiate web3 contract instance
var web3ContractInstance = new web3.eth.Contract(uniswapAbi, singleEventFromRegister["hits"].hits[0]._source.contractAddress);
await wait(1000);
harvestSingleInstanceOfContractEvent(web3ContractInstance, eventName, lastIndexedBlock, blockNumber);
}
}
function getWholePercent(percentFor,percentOf)
{
return Math.floor(percentFor/percentOf*100);
}
async function harvestSingleInstanceOfContractEvent(web3ContractInstance, eventName, lastIndexedBlock, blockNumber) {
console.log("Looking for any " + eventName + " events, between block " + lastIndexedBlock + ", and block " + blockNumber);
var target = lastIndexedBlock;
while(getWholePercent(target, blockNumber) <= 98){
target += 500;
try {
var events = await web3ContractInstance.getPastEvents(eventName, {
filter: {},
fromBlock: lastIndexedBlock,
toBlock: target
});
writetheEventCollectionToElasticsearch(events, eventName);
await wait(1000);
} catch (err) {
console.log("Error running cacheEvents");
console.log("Failed to harvest " + eventName);
console.log(err);
}
}
}
async function writetheEventCollectionToElasticsearch(theEventCollection, eventName) {
console.log("Found theEventCollection = " + theEventCollection.length);
if (theEventCollection.length > 0) {
var bulkData = {};
var theBodyArray = [];
theEventCollection.forEach(function(obj) {
eventHash = web3.utils.sha3(obj.transactionHash, obj.logIndex);
theId = {};
actionDescription = {};
theId["_id"] = eventHash;
theId["_type"] = "event";
theId["_index"] = 'uniswap_exchange_events';
actionDescription["index"] = theId;
theBodyArray.push(actionDescription);
theDocumentToIndex = {};
theDocumentToIndex["name"] = eventName;
theDocumentToIndex["jsonEventObject"] = obj;
theBodyArray.push(theDocumentToIndex);
});
if (theBodyArray.length > 0) {
bulkData["body"] = theBodyArray;
console.log("Adding the following data to the uniswap_exchange_events")
console.log(JSON.stringify(bulkData));
bulkIngest(bulkData);
}
}
}
// Get the current block
function fetchTimestamp(blockNumberToFetch) {
return new Promise(function(fulfill, reject) {
console.log("Fetching timestamp");
web3.eth.getBlock(blockNumberToFetch, function(error, content) {
if (error) reject(error)
else fulfill(content.timestamp);
})
})
}
async function updateTimestamp() {
try {
var theGetHitsUrl = "http://localhost:9200/uniswap_exchange_events/_search/";
var theTotalHits = JSON.parse(getRequestWithOnlyUrl(theGetHitsUrl));
var registerLength = theTotalHits["hits"]["total"];
console.log(registerLength);
for (var i = 0; i < registerLength; i++) {
console.log("Processing " + i + " of " + registerLength);
theGetSingleEventUrl = "http://localhost:9200/uniswap_exchange_events/_search/?from=" + i + "&size=1";
await wait(10);
singleEventFromEvents = JSON.parse(getRequestWithOnlyUrl(theGetSingleEventUrl));
singleEventBlockNumber = singleEventFromEvents["hits"].hits[0]._source.jsonEventObject.blockNumber;
console.log(singleEventBlockNumber);
var timestampToWrite = await fetchTimestamp(singleEventBlockNumber);
await wait(10);
var timestampDate = timestampToWrite * 1000;
console.log(timestampDate);
var idToWrite = singleEventFromEvents["hits"].hits[0]._id;
const response = await client.update({
index: 'uniswap_exchange_events',
type: 'event',
id: idToWrite,
body: {
// put the partial document under the `doc` key
doc: {
blockTimestamp: timestampDate
}
}
})
}
} catch (err) {
console.log(err);
}
}
const app = express();
// serve files from the public directory
app.use(express.static('public'));
// start the express web server listening on 8080
app.listen(8080, () => {
console.log('listening on 8080');
});
// serve the homepage
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
//A button
app.post('/clicked', (req, res) => {
console.log("Loading contracts");
loadContracts(uniswapAbi);
res.sendStatus(201);
});
app.post('/clicked2', (req, res) => {
console.log("Clicked2");
harvestContracts(uniswapAbi)
res.sendStatus(201)
});
app.post('/clicked3', (req, res) => {
console.log("Clicked3");
updateTimestamp()
res.sendStatus(201)
});