forked from hicommonwealth/commonwealth
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver-test.ts
365 lines (338 loc) · 11.1 KB
/
server-test.ts
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
/* eslint-disable dot-notation */
import http from 'http';
import favicon from 'serve-favicon';
import logger from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import passport from 'passport';
import session from 'express-session';
import express from 'express';
import SessionSequelizeStore from 'connect-session-sequelize';
import BN from 'bn.js';
import { SESSION_SECRET } from './server/config';
import setupAPI from './server/router'; // performance note: this takes 15 seconds
import setupPassport from './server/passport';
import models from './server/database';
import {
ChainBase,
ChainNetwork,
NotificationCategories,
ChainType,
} from './shared/types';
import ViewCountCache from './server/util/viewCountCache';
import IdentityFetchCache from './server/util/identityFetchCache';
import TokenBalanceCache, { TokenBalanceProvider } from './server/util/tokenBalanceCache';
import setupErrorHandlers from './server/scripts/setupErrorHandlers';
require('express-async-errors');
const app = express();
const SequelizeStore = SessionSequelizeStore(session.Store);
// set cache TTL to 1 second to test invalidation
const viewCountCache = new ViewCountCache(1, 10 * 60);
const identityFetchCache = new IdentityFetchCache(10 * 60);
// always prune both token and non-token holders asap
class MockTokenBalanceProvider extends TokenBalanceProvider {
public balanceFn: (tokenAddress: string, userAddress: string) => Promise<BN>;
public async getEthTokenBalance(
tokenAddress: string,
userAddress: string
): Promise<BN> {
if (this.balanceFn) {
return this.balanceFn(tokenAddress, userAddress);
} else {
throw new Error('unable to fetch token balance');
}
}
}
const mockTokenBalanceProvider = new MockTokenBalanceProvider();
const tokenBalanceCache = new TokenBalanceCache(
models,
0,
0,
mockTokenBalanceProvider
);
let server;
const sessionStore = new SequelizeStore({
db: models.sequelize,
tableName: 'Sessions',
checkExpirationInterval: 15 * 60 * 1000, // Clean up expired sessions every 15 minutes
expiration: 7 * 24 * 60 * 60 * 1000, // Set session expiration to 7 days
});
sessionStore.sync();
const sessionParser = session({
secret: SESSION_SECRET,
store: sessionStore,
resave: false,
saveUninitialized: true,
});
// serve static files
app.use(favicon(`${__dirname}/favicon.ico`));
app.use('/static', express.static('static'));
// add other middlewares
// app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(sessionParser);
app.use(passport.initialize());
app.use(passport.session());
const resetServer = (debug = false): Promise<void> => {
if (debug) console.log('Resetting database...');
return new Promise(async (resolve) => {
try {
await models.sequelize.sync({ force: true });
console.log('done syncing.');
if (debug) console.log('Initializing default models...');
const drew = await models.User.create({
email: '[email protected]',
emailVerified: true,
isAdmin: true,
lastVisited: '{}',
});
// For all smart contract support chains
await models.ContractCategory.create({
name: 'Tokens',
description: 'Token related contracts',
color: '#4a90e2',
});
await models.ContractCategory.create({
name: 'DAOs',
description: 'DAO related contracts',
color: '#9013fe',
});
// Initialize different chain + node URLs
const edgMain = await models.Chain.create({
id: 'edgeware',
network: ChainNetwork.Edgeware,
symbol: 'EDG',
name: 'Edgeware',
icon_url: '/static/img/protocols/edg.png',
active: true,
type: ChainType.Chain,
base: ChainBase.Substrate,
ss58_prefix: 7,
has_chain_events_listener: false,
});
const eth = await models.Chain.create({
id: 'ethereum',
network: ChainNetwork.Ethereum,
symbol: 'ETH',
name: 'Ethereum',
icon_url: '/static/img/protocols/eth.png',
active: true,
type: ChainType.Chain,
base: ChainBase.Ethereum,
has_chain_events_listener: false,
});
const alex = await models.Chain.create({
id: 'alex',
network: ChainNetwork.ERC20,
symbol: 'ALEX',
name: 'Alex',
icon_url: '/static/img/protocols/eth.png',
active: true,
type: ChainType.Token,
base: ChainBase.Ethereum,
has_chain_events_listener: false,
});
const yearn = await models.Chain.create({
id: 'yearn',
network: ChainNetwork.ERC20,
symbol: 'YFI',
name: 'yearn.finance',
icon_url: '/static/img/protocols/eth.png',
active: true,
type: ChainType.Token,
base: ChainBase.Ethereum,
has_chain_events_listener: false,
});
const sushi = await models.Chain.create({
id: 'sushi',
network: ChainNetwork.ERC20,
symbol: 'SUSHI',
name: 'Sushi',
icon_url: '/static/img/protocols/eth.png',
active: true,
type: ChainType.Token,
base: ChainBase.Ethereum,
has_chain_events_listener: false,
});
// Admin roles for specific communities
await Promise.all([
models.Address.create({
user_id: 1,
address: '0x34C3A5ea06a3A67229fb21a7043243B0eB3e853f',
chain: 'ethereum',
// selected: true,
verification_token: 'PLACEHOLDER',
verification_token_expires: null,
verified: new Date(),
}),
models.Address.create({
address: '5DJA5ZCobDS3GVn8D2E5YRiotDqGkR2FN1bg6LtfNUmuadwX',
chain: 'edgeware',
verification_token: 'PLACEHOLDER',
verification_token_expires: null,
verified: new Date(),
keytype: 'sr25519',
}),
models.Address.create({
address: 'ik52qFh92pboSctWPSFKtQwGEpypzz2m6D5ZRP8AYxqjHpM',
chain: 'edgeware',
verification_token: 'PLACEHOLDER',
verification_token_expires: null,
verified: new Date(),
keytype: 'sr25519',
}),
models.Address.create({
address: 'js4NB7G3bqEsSYq4ruj9Lq24QHcoKaqauw6YDPD7hMr1Roj',
chain: 'edgeware',
verification_token: 'PLACEHOLDER',
verification_token_expires: null,
verified: new Date(),
keytype: 'sr25519',
}),
]);
// Notification Categories
await models.NotificationCategory.create({
name: NotificationCategories.NewCommunity,
description: 'someone makes a new community',
});
await models.NotificationCategory.create({
name: NotificationCategories.NewThread,
description: 'someone makes a new thread',
});
await models.NotificationCategory.create({
name: NotificationCategories.NewComment,
description: 'someone makes a new comment',
});
await models.NotificationCategory.create({
name: NotificationCategories.NewMention,
description: 'someone @ mentions a user',
});
await models.NotificationCategory.create({
name: NotificationCategories.NewCollaboration,
description: 'someone collaborates with a user',
});
await models.NotificationCategory.create({
name: NotificationCategories.ChainEvent,
description: 'a chain event occurs',
});
await models.NotificationCategory.create({
name: NotificationCategories.NewReaction,
description: 'someone reacts to a post',
});
await models.NotificationCategory.create({
name: NotificationCategories.ThreadEdit,
description: 'someone edited a thread'
})
await models.NotificationCategory.create({
name: NotificationCategories.CommentEdit,
description: 'someoned edited a comment'
})
await models.NotificationCategory.create({
name: NotificationCategories.NewRoleCreation,
description: 'someone created a role'
})
await models.NotificationCategory.create({
name: NotificationCategories.EntityEvent,
description: 'an entity-event as occurred'
})
// Admins need to be subscribed to mentions and collaborations
await models.Subscription.create({
subscriber_id: drew.id,
category_id: NotificationCategories.NewMention,
object_id: `user-${drew.id}`,
is_active: true,
});
await models.Subscription.create({
subscriber_id: drew.id,
category_id: NotificationCategories.NewCollaboration,
object_id: `user-${drew.id}`,
is_active: true,
});
const nodes = [
['mainnet1.edgewa.re', 'edgeware', null, '0'],
[
'wss://eth-mainnet.alchemyapi.io/v2/cNC4XfxR7biwO2bfIO5aKcs9EMPxTQfr',
'ethereum',
null,
'1',
],
[
'wss://eth-ropsten.alchemyapi.io/v2/2xXT2xx5AvA3GFTev3j_nB9LzWdmxPk7',
'alex',
'0xFab46E002BbF0b4509813474841E0716E6730136',
'3',
],
[
'wss://eth-mainnet.alchemyapi.io/v2/cNC4XfxR7biwO2bfIO5aKcs9EMPxTQfr',
'yearn',
'0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e',
'1',
],
[
'wss://eth-mainnet.alchemyapi.io/v2/cNC4XfxR7biwO2bfIO5aKcs9EMPxTQfr',
'sushi',
'0x6b3595068778dd592e39a122f4f5a5cf09c90fe2',
'1',
],
];
await Promise.all(
nodes.map(([url, chain, address, eth_chain_id]) =>
models.ChainNode.create({
chain,
url,
address,
eth_chain_id: +eth_chain_id || null,
})
)
);
if (debug) console.log('Database reset!');
} catch (error) {
console.log('error', error);
}
resolve();
});
};
const setupServer = () => {
const port = 8081;
app.set('port', port);
server = http.createServer(app);
const onError = (error) => {
if (error.syscall !== 'listen') {
throw error;
}
switch (error.code) {
case 'EACCES':
console.error('Port requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`Port ${port} already in use`);
process.exit(1);
break;
default:
throw error;
}
};
const onListen = () => {
const addr = server.address();
if (typeof addr === 'string') {
console.log(`Listening on ${addr}`);
} else {
console.log(`Listening on port ${addr.port}`);
}
};
server.listen(port);
server.on('error', onError);
server.on('listening', onListen);
};
setupPassport(models);
setupAPI(app, models, viewCountCache, identityFetchCache, tokenBalanceCache);
setupErrorHandlers(app);
setupServer();
export const resetDatabase = () => resetServer();
export const getIdentityFetchCache = () => identityFetchCache;
export const getTokenBalanceCache = () => tokenBalanceCache;
export const getMockBalanceProvider = () => mockTokenBalanceProvider;
export default app;