-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcache.js
More file actions
387 lines (341 loc) · 10.9 KB
/
cache.js
File metadata and controls
387 lines (341 loc) · 10.9 KB
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
const {getRedisItem, putRedisItem} = require('./redis.js');
const {getChainNft, getChainAccount, getAllWithdrawsDeposits} = require('./tokens.js');
const {nftKeys, nftPropertiesKeys, ids, redisPrefixes} = require('./constants.js');
const {getBlockchain, getEventsRated, getPastEvents, makeWeb3WebsocketContract} = require('./blockchain.js');
const {connect, getRedisAllItems} = require('./redis.js');
const config = require("./config")["networks"]["rinkeby"];
const cronJobs = require('./cron');
async function initNftCache({chainName}) {
const {
web3,
contracts,
// wsContracts,
} = await getBlockchain();
await connect();
const currentBlockNumber = await web3[chainName].eth.getBlockNumber();
// Watch for new events.
const _recurse = currentBlockNumber => {
const wsContract = makeWeb3WebsocketContract(chainName, 'NFT');
wsContract.events.allEvents({fromBlock: currentBlockNumber})
.on('data', async function(event){
console.log('nft event', chainName, event);
currentBlockNumber = Math.max(currentBlockNumber, event.blockNumber);
await processEventNft({
event,
chainName,
});
})
/* .on('changed', async function(event){
console.log('changed nft', chainName, event);
})
.on('error', async err => {
console.warn('error nft', chainName, err);
}); */
wsContract.listener.on('error', async err => {
console.warn('error nft listener', chainName, err);
});
wsContract.listener.on('end', async () => {
console.log('reconnect nft listener', chainName);
wsContract.listener.disconnect();
// const currentBlockNumber = await web3[chainName].eth.getBlockNumber();
_recurse(currentBlockNumber);
});
};
_recurse(currentBlockNumber);
let o = await getRedisItem(
ids.lastCachedBlockNft,
redisPrefixes[chainName + 'Nft']
);
const lastBlockNumber = o?.Item?.number || 0;
// Catch up on missing blocks.
if (currentBlockNumber !== lastBlockNumber) {
const events = chainName === 'polygon'
? await getEventsRated({
chainName,
contractName: 'NFT',
eventName: 'allEvents',
fromBlock: lastBlockNumber,
})
: await getPastEvents({
chainName,
contractName: 'NFT',
eventName: 'allEvents',
fromBlock: lastBlockNumber,
});
if (events.length > 0) {
await processEventsNft({
events,
currentBlockNumber,
chainName,
});
}
}
}
async function initAccountCache({chainName}) {
const {
web3,
contracts,
// wsContracts,
} = await getBlockchain();
const currentBlockNumber = await web3[chainName].eth.getBlockNumber();
// Watch for new events.
const _recurse = currentBlockNumber => {
const wsContract = makeWeb3WebsocketContract(chainName, 'Account');
wsContract.events.allEvents({fromBlock: currentBlockNumber})
.on('data', async function(event){
console.log('account event', chainName, event);
currentBlockNumber = Math.max(currentBlockNumber, event.blockNumber);
await processEventAccount({
event,
chainName,
});
})
/* .on('changed', async function(event){
console.log('changed account', chainName, event);
})
.on('error', async err => {
console.warn('error account', chainName, err);
const currentBlockNumber = await web3[chainName].eth.getBlockNumber();
_recurse(currentBlockNumber);
}); */
wsContract.listener.on('error', err => {
console.warn('error account listener', chainName, err);
});
wsContract.listener.on('end', async () => {
console.log('reconnect account listener', chainName);
wsContract.listener.disconnect();
// const currentBlockNumber = await web3[chainName].eth.getBlockNumber();
_recurse(currentBlockNumber);
});
};
_recurse(currentBlockNumber);
const o = await getRedisItem(
ids.lastCachedBlockAccount,
redisPrefixes[chainName + 'Account']
);
const lastBlockNumber = o?.Item?.number || 0;
// Catch up on missing blocks.
if (currentBlockNumber !== lastBlockNumber) {
const events = chainName === 'polygon'
? await getEventsRated({
chainName,
contractName: 'Account',
eventName: 'allEvents',
fromBlock: lastBlockNumber,
})
: await getPastEvents({
chainName,
contractName: 'Account',
eventName: 'allEvents',
fromBlock: lastBlockNumber,
});
if (events.length > 0) {
await processEventsAccount({
events,
currentBlockNumber,
chainName,
});
}
}
}
async function initCaches() {
const _logCache = async (name, p) => {
console.log('started init cache', name);
try {
return await p;
} catch(err) {
console.warn('errored init cache', err);
throw err;
}
console.log('finished init cache', name);
};
cronJobs.init();
await Promise.all([
'mainnet',
'mainnetsidechain',
// 'polygon',
].map(chainName => {
return Promise.all([
_logCache(chainName + ' NFT', initNftCache({chainName})),
_logCache(chainName + ' Account', initAccountCache({chainName})),
]);
}));
}
async function processEventNft({event, chainName}) {
let {tokenId, hash, key, value} = event.returnValues;
if (tokenId) {
try {
const storeEntries = [];
const {
mainnetDepositedEntries,
mainnetWithdrewEntries,
sidechainDepositedEntries,
sidechainWithdrewEntries,
polygonDepositedEntries,
polygonWithdrewEntries,
} = await getAllWithdrawsDeposits('NFT')(chainName);
const token = await getChainNft('NFT')(chainName)(
tokenId,
storeEntries,
mainnetDepositedEntries,
mainnetWithdrewEntries,
sidechainDepositedEntries,
sidechainWithdrewEntries,
polygonDepositedEntries,
polygonWithdrewEntries,
);
if (token.owner.address !== '0x0000000000000000000000000000000000000000') {
const tokenIdNum = parseInt(tokenId, 10);
await putRedisItem(tokenIdNum, token, redisPrefixes.mainnetsidechainNft);
}
} catch (e) {
console.error(e);
}
} else if (hash && key && value) {
console.log('updating hash 1', {hash, key, value}, event.returnValues);
const tokens = await getRedisAllItems(redisPrefixes[chainName + 'Nft']);
const token = tokens.find(token => token.hash === hash);
console.log('updating hash 2', token);
if (token) {
let updated = false;
if (nftKeys.includes(key)) {
token[key] = value;
updated = true;
/* // XXX fix this
const params = {
FilterExpression: "#hash = :hash",
ExpressionAttributeNames: {
"#hash": "hash",
},
ExpressionAttributeValues: {
':hash': hash,
},
TableName: redisPrefixes.mainnetsidechainNft,
IndexName: 'hash-index',
};
const o = await ddbd.scan(params).promise();
// console.log('got o', o);
let tokens = o.Items;
// console.log('updating hash 2', tokens);
for (const token of tokens) {
token[key] = value;
}
// console.log('updating hash 3', tokens);
await Promise.all(tokens.map(token => {
return putRedisItem(parseInt(token.id, 10), token, redisPrefixes.mainnetsidechainNft);
}));
// console.log('updating hash 4'); */
}
if (nftPropertiesKeys.includes(key)) {
token.properties[key] = value;
updated = true;
}
if (updated) {
await putRedisItem(token.id, token, redisPrefixes.mainnetsidechainNft);
}
} else {
console.warn('could not find hash to update', token);
}
}
const {blockNumber} = event;
await putRedisItem(ids.lastCachedBlockNft, {
id: ids.lastCachedBlockNft,
number: blockNumber,
}, redisPrefixes.mainnetsidechainNft);
}
async function processEventsNft({events, currentBlockNumber, chainName}) {
const seenTokenIds = {};
const tokenIds = events.map(event => {
let {tokenId} = event.returnValues;
if (typeof tokenId === 'string') {
tokenId = parseInt(tokenId, 10);
if (!seenTokenIds[tokenId]) {
seenTokenIds[tokenId] = true;
return tokenId;
} else {
return null;
}
} else {
return null;
}
}).filter(tokenId => tokenId !== null);
console.log('process events', chainName, tokenIds.length);
const storeEntries = [];
const {
mainnetDepositedEntries,
mainnetWithdrewEntries,
sidechainDepositedEntries,
sidechainWithdrewEntries,
polygonDepositedEntries,
polygonWithdrewEntries,
} = await getAllWithdrawsDeposits('NFT')(chainName);
for (const tokenId of tokenIds) {
const token = await getChainNft('NFT')(chainName)(
tokenId,
storeEntries,
mainnetDepositedEntries,
mainnetWithdrewEntries,
sidechainDepositedEntries,
sidechainWithdrewEntries,
polygonDepositedEntries,
polygonWithdrewEntries,
);
if (token.owner.address !== '0x0000000000000000000000000000000000000000') {
await putRedisItem(tokenId, token, redisPrefixes.mainnetsidechainNft);
}
}
await putRedisItem(ids.lastCachedBlockNft, {
id: ids.lastCachedBlockNft,
number: currentBlockNumber,
}, redisPrefixes.mainnetsidechainNft);
}
async function processEventAccount({contract, event, chainName}) {
// console.log('got account event', event);
let {owner} = event.returnValues;
if (owner) {
owner = owner.toLowerCase();
try {
const account = await getChainAccount({
address: owner,
chainName,
});
// console.log('load account into cache', owner, account);
// if (token.properties.hash) {
await putRedisItem(owner, account, redisPrefixes.mainnetsidechainAccount);
// }
} catch (e) {
console.error(e);
}
}
const {blockNumber} = event;
await putRedisItem(ids.lastCachedBlockAccount, {number: blockNumber}, redisPrefixes.mainnetsidechainAccount);
}
const _uniquify = (a, pred = (a, b) => a === b) => {
return a.filter((e, i) => {
for (let j = 0; j < i; j++) {
if (pred(a[j], e)) {
return false;
}
}
return true;
});
};
async function processEventsAccount({contract, events, currentBlockNumber, chainName}) {
let owners = events.map(e => {
let {owner} = e.returnValues;
owner = owner.toLowerCase();
return owner;
});
owners = _uniquify(owners);
for (const owner of owners) {
const account = await getChainAccount({
address: owner,
chainName,
});
await putRedisItem(owner, account, redisPrefixes.mainnetsidechainAccount);
}
await putRedisItem(ids.lastCachedBlockAccount, {number: currentBlockNumber}, redisPrefixes.mainnetsidechainAccount);
}
module.exports = {
initCaches,
};