-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcron.js
More file actions
74 lines (69 loc) · 2.85 KB
/
cron.js
File metadata and controls
74 lines (69 loc) · 2.85 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
const cron = require('node-cron');
const { getPastEvents } = require('./blockchain.js');
const { getRedisItem, putRedisItem } = require('./redis.js');
const { redisPrefixes } = require('./constants');
const fetch = require('node-fetch');
async function syncMetadata() {
console.log(`[CRON] [${new Date().toISOString()}] Syncing all token metadatas from webaverseERC721`);
const chainNames = ['rinkeby'];
for (chainName of chainNames) {
const events = await getPastEvents({
chainName: chainName,
contractName: 'webaverseERC721',
eventName: 'URI'
});
for (event of events) {
const tokenID = event.returnValues.id;
const uri = event.returnValues.uri;
const dbURI = await getRedisItem(tokenID, chainName + redisPrefixes['webaverseERC721'] + 'Metadata');
// If uri in our database does not match the uri on the blockchain, update the database
if (dbURI && dbURI.Item && uri !== dbURI.Item.uri) {
console.log('tokenID: ', tokenID, ' data not changed');
} else {
try {
const metadata = await fetch(uri);
const metadataJSON = await metadata.json();
await putRedisItem(tokenID, { ...metadataJSON, tokenID, uri: uri }, chainName + redisPrefixes['webaverseERC721'] + 'Metadata');
} catch (error) {
console.log(`Error for token ID ${tokenID}: `, error.message);
}
}
}
}
}
async function syncTokenIDOwners() {
console.log(`[CRON] [${new Date().toISOString()}] Syncing owners and their tokenIDs from webaverseERC721`);
const chainNames = ['rinkeby'];
for (chainName of chainNames) {
const events = await getPastEvents({
chainName: chainName,
contractName: 'webaverseERC721',
eventName: 'Transfer'
});
const tokenIdToOwners = {};
for (event of events) {
const tokenID = event.returnValues;
console.log('tokenID: ', tokenID);
tokenIdToOwners[event.returnValues.tokenId] = event.returnValues.to.trim().toLowerCase();
}
const ownersToTokenID = {};
const tokenIDs = Object.keys(tokenIdToOwners);
for (tokenID of tokenIDs) {
const owner = tokenIdToOwners[tokenID];
if (!ownersToTokenID[owner]) {
ownersToTokenID[owner] = [];
}
ownersToTokenID[owner].push(tokenID);
}
for (owner of Object.keys(ownersToTokenID)) {
await putRedisItem(owner, ownersToTokenID[owner], chainName + redisPrefixes['webaverseERC721'] + 'Owners');
}
}
}
function init() {
cron.schedule('* * * * *', syncMetadata);
cron.schedule('* * * * *', syncTokenIDOwners);
}
module.exports = {
init
}