-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
250 lines (225 loc) · 11.3 KB
/
app.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
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Web3 = require("web3");
const factoryAbi = require("./contracts/PersonalEconomyFactory.json");
const economyAbi = require("./contracts/PersonalEconomy.json");
const ipfsApi = require('ipfs-api');
const getMultihashFromBytes32 = require('./utils/utils');
const Economy = require('./models/economy');
const economyRoutes = require('./routes/economies');
app = express();
app.use(bodyParser.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
app.use(economyRoutes)
mongoose.connect('mongodb+srv://achill:w8BG6xR351pqX6DC@cluster0-xfiey.mongodb.net/tokens')
.then(res => {
app.listen(3000);
})
.catch(err => {
console.log(err);
})
// SETUP IPFS AND WEB3 CONNECTION FOR FETCHING USER'S PERSONAL ECONOMY DATA
const factoryAddress = "0xD3f6603fEc53a3175803F5ac99363aA6D3c528Df";
const ipfs = ipfsApi('ipfs.infura.io', '5001', { protocol: 'https' });
// need websocket provider for event listening:
const web3socket = new Web3(new Web3.providers.WebsocketProvider("wss://rinkeby.infura.io/ws"));
const factoryContractWss = new web3socket.eth.Contract(factoryAbi, factoryAddress);
// and regular provider for regular contract calls:
const web3 = new Web3(Web3.givenProvider || "https://rinkeby.infura.io/v3/1169d54f24964d03bbe5264bd501e47f");
const factoryContract = new web3.eth.Contract(factoryAbi, factoryAddress);
// LISTEN TO FACTORY CONTRACT FOR NEW "CREATED" EVENTS AND STORE NEW ECONOMY'S DATA IN MONGODB
factoryContractWss.events.Created((err, createdEvent) => {
const tokenAddress = createdEvent.returnValues.token_address;
// get IPFS hash and data
// instantiate personal economy contract in order to get IPFS hash
const economyContract = new web3.eth.Contract(economyAbi, tokenAddress)
economyContract.methods.mhash().call().then(hash => {
// retrieve IPFS data
const multihash = getMultihashFromBytes32({
digest: hash,
hashFunction: 18,
size: 32,
});
ipfs.get(multihash, (err, files) => {
const dataJson = JSON.parse(files[0].content.toString());
const { description, image, name, symbol, services, tags } = dataJson;
const newEconomy = new Economy({
tokenAddress: tokenAddress,
ipfsHash: multihash,
data: {
name: name,
symbol: symbol,
description: description,
services: services,
tags: tags
}
});
newEconomy.save()
.then(result => {
console.log('New economy saved.')
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
// next(err);
});
});
})
})
// LISTEN TO EACH ECONOMY CONTRACT FOR "UPDATED" EVENTS AND STORE NEW ECONOMY'S DATA IN MONGODB
// NOTE: "UPDATED" EVENT DOES NOT EXIST CURRENTLY - FOR TESTING, THIS IS REPLACED WITH "REQUESTED" EVENT
// Steps:
// 1. get token addresses from factory contract
// 2. for each token address instantiate websocket connection, to be able to listen to "updated" event // THIS EVENT HAS TO BE CREATED ON SMART CONTRACTS!
// 3. on updated event, fetch new ipfs as above, find existing economy in database and save
factoryContract.getPastEvents('Created', { fromBlock: 0, toBlock: "latest" })
.then(eventArray => {
eventArray.forEach(createdEvent => {
const tokenAddress = createdEvent.returnValues.token_address;
// instantiate personal economy contract in order to listen to 'Updated' event for each
const economyContractWss = new web3socket.eth.Contract(economyAbi, tokenAddress);
economyContractWss.events.Requested((err, createdEvent) => { // THIS SHOULD BE CHANGED TO UPDATED, ONCE THAT EVENT EXISTS
// get new IPFS hash and data
economyContractWss.methods.mhash().call().then(hash => {
// retrieve IPFS data
const multihash = getMultihashFromBytes32({
digest: hash,
hashFunction: 18,
size: 32,
});
ipfs.get(multihash, (err, files) => {
const dataJson = JSON.parse(files[0].content.toString());
const { description, image, name, symbol, services, tags } = dataJson;
Economy.findOne({ tokenAddress: tokenAddress })
.then(economy => {
// If the economy is not yet in the database (for some weird reason), create a new one
if (!economy) {
const newEconomy = new Economy({
tokenAddress: tokenAddress,
ipfsHash: multihash,
data: {
name: name,
symbol: symbol,
description: description,
services: services,
tags: tags
}
});
return newEconomy.save()
.then(result => {
console.log('New economy saved.')
})
.catch(err => {
console.log(err);
});
}
economy.ipfsHash = multihash;
economy.data.description = description;
economy.data.services = services;
economy.data.tags = tags;
economy.save()
.then(result => {
console.log('Existing economy updated.')
// res.status(201).json({
// message: 'Existing economy updated!',
// economy: result
// });
}).catch(err => {
console.log(err);
});
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
// next(err);
});
});
})
})
})
})
// GO THROUGH ALL EXISTING ECONOMIES AND MAKE SURE THAT CURRENT DATA IS STORED
factoryContract.getPastEvents('Created', { fromBlock: 0, toBlock: "latest" })
.then(eventArray => {
eventArray.forEach(createdEvent => {
const tokenAddress = createdEvent.returnValues.token_address;
// instantiate personal economy contract in order to get IPFS hash
const economyContract = new web3.eth.Contract(economyAbi, tokenAddress)
economyContract.methods.mhash().call().then(hash => {
// retrieve IPFS data
const multihash = getMultihashFromBytes32({
digest: hash,
hashFunction: 18,
size: 32,
});
ipfs.get(multihash, (err, files) => {
// FOR SOME LOOPS / SOME TOKENS THE IPFS REQUEST FAILS (!)
// THERE SEEMS TO BE A RATE LIMITATION BY IPFS-INFURA
// WILL HAVE TO IMPLEMENT POLLING/RETRYING INSTEAD OF JUST PULLING ALL DATA IN ONE GO.
if (!files) {
// TO SEE WHICH ECONOMIES WHERE NOT FETCHED:
// console.log('token: ', tokenAddress, ' ipfsHash: ', multihash)
return
}
const dataJson = JSON.parse(files[0].content.toString());
const { description, image, name, symbol, services, tags } = dataJson;
Economy.findOne({ tokenAddress: tokenAddress })
.then(economy => {
// If the economy is not yet in the database, create a new one
if (!economy) {
const newEconomy = new Economy({
tokenAddress: tokenAddress,
ipfsHash: multihash,
data: {
name: name,
symbol: symbol,
description: description,
services: services,
tags: tags
}
});
return newEconomy.save()
.then(result => {
console.log('New economy saved.')
});
}
// Only update if the ipfs file has changed
if (economy.ipfsHash === multihash) {
return
}
economy.ipfsHash = multihash;
economy.data.description = description;
economy.data.services = services;
economy.data.tags = tags;
economy.save()
.then(result => {
console.log('Existing economy updated.')
// res.status(201).json({
// message: 'Existing economy updated!',
// economy: result
// });
}).catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
// next(err);
});
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
// next(err);
});
});
})
})
});