-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
350 lines (322 loc) · 9.58 KB
/
index.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
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
import * as Sentry from '@sentry/node'
import getRawBody from 'raw-body'
import httpAssert from 'http-assert'
import * as ethers from 'ethers'
import { json, status } from 'http-responders'
import assert from 'node:assert'
import Cursor from 'pg-cursor'
const maxScore = BigInt(1e15)
// https://github.com/filecoin-station/spark-impact-evaluator/blob/fd64313a96957fcb3d5fda0d334245601676bb73/test/Spark.t.sol#L11C39-L11C65
const roundReward = 456621004566210048n
const handler = async (req, res, pgPool, signerAddresses, logger) => {
if (req.method === 'POST' && req.url === '/scores') {
await handleIncreaseScores(req, res, pgPool, signerAddresses, logger)
} else if (req.method === 'POST' && req.url === '/paid') {
await handlePaidScheduledRewards(req, res, pgPool, signerAddresses, logger)
} else if (req.method === 'GET' && req.url === '/scheduled-rewards') {
await handleGetAllScheduledRewards(res, pgPool)
} else if (req.method === 'GET' && req.url.startsWith('/scheduled-rewards/')) {
await handleGetSingleScheduledRewards(req, res, pgPool)
} else if (req.method === 'GET' && req.url === '/log') {
await handleGetLog(res, pgPool)
} else {
status(res, 404)
}
}
const validateSignature = (signature, addresses, values, signerAddresses) => {
httpAssert(
typeof signature === 'object' && signature !== null,
400,
'.signature should be an object'
)
httpAssert.deepEqual(
Object.keys(signature).sort(),
['r', 's', 'v'],
400,
'.signature should have keys .r, .s and .v'
)
const digest = ethers.solidityPackedKeccak256(
['address[]', 'int256[]'],
[addresses, values]
)
const reqSigner = ethers.verifyMessage(
digest,
ethers.Signature.from(signature)
)
httpAssert(signerAddresses.includes(reqSigner), 403, 'Invalid signature')
}
async function handleIncreaseScores (req, res, pgPool, signerAddresses, logger) {
const body = JSON.parse(await getRawBody(req, { limit: '1mb' }))
httpAssert(
typeof body === 'object' && body !== null,
400,
'Request body should be an object'
)
httpAssert(
Array.isArray(body.participants),
400,
'.participants should be an array'
)
httpAssert(
Array.isArray(body.scores),
400,
'.scores should be an array'
)
httpAssert.strictEqual(
body.participants.length,
body.scores.length,
400,
'.participants and .scores should have the same size'
)
httpAssert(
body.participants.every(ethers.isAddress),
400,
'All .participants should be 0x addresses'
)
httpAssert(
body.scores.every(score => {
try {
return BigInt(score) > 0n
} catch {
return false
}
}),
400,
'All .scores should be positive numbers encoded as string'
)
validateSignature(
body.signature,
body.participants,
body.scores,
signerAddresses
)
if (body.participants.includes('0x000000000000000000000000000000000000dEaD')) {
const index = body.participants.indexOf(
'0x000000000000000000000000000000000000dEaD'
)
body.participants.splice(index, 1)
body.scores.splice(index, 1)
}
if (body.participants.length === 0) {
return json(res, {})
}
logger.info(`Increasing scheduled rewards of ${body.participants.length} participants`)
const scheduledRewardsDeltas = body.scores.map(score => {
return (BigInt(score) * roundReward) / maxScore
})
const pgClient = await pgPool.connect()
try {
await pgClient.query('BEGIN')
await pgClient.query(`
INSERT INTO scheduled_rewards (address, amount)
VALUES (UNNEST($1::TEXT[]), UNNEST($2::NUMERIC[]))
ON CONFLICT (address) DO UPDATE
SET amount = scheduled_rewards.amount + EXCLUDED.amount
`, [body.participants, scheduledRewardsDeltas])
await pgClient.query(`
INSERT INTO logs (address, score, scheduled_rewards_delta)
VALUES (UNNEST($1::TEXT[]), UNNEST($2::NUMERIC[]), UNNEST($3::NUMERIC[]))
`, [body.participants, body.scores, scheduledRewardsDeltas])
await pgClient.query(`
DELETE FROM logs WHERE timestamp < NOW() - INTERVAL '30 days'
`)
await pgClient.query('COMMIT')
} catch (err) {
await pgClient.query('ROLLBACK')
throw err
} finally {
pgClient.release()
}
logger.info(`Increased scheduled rewards of ${body.participants.length} participants`)
const { rows } = await pgPool.query(`
SELECT address, amount
FROM scheduled_rewards
WHERE address = ANY($1)
`, [body.participants])
json(
res,
Object.fromEntries(rows.map(({ address, amount }) => [address, String(amount)]))
)
}
async function handlePaidScheduledRewards (req, res, pgPool, signerAddresses, logger) {
const body = JSON.parse(await getRawBody(req, { limit: '1mb' }))
httpAssert(
typeof body === 'object' && body !== null,
400,
'Request body should be an object'
)
httpAssert(
Array.isArray(body.participants),
400,
'.participants should be an array'
)
httpAssert(
Array.isArray(body.rewards),
400,
'.rewards should be an array'
)
httpAssert.strictEqual(
body.participants.length,
body.rewards.length,
400,
'.participants and .rewards should have the same size'
)
httpAssert(
body.participants.every(ethers.isAddress),
400,
'All .participants should be 0x addresses'
)
httpAssert(
body.rewards.every(amount => {
try {
return BigInt(amount) > 0n
} catch {
return false
}
}),
400,
'All .rewards should be positive numbers encoded as string'
)
validateSignature(
body.signature,
body.participants,
body.rewards,
signerAddresses
)
if (body.participants.length === 0) {
return json(res, {})
}
logger.info(`Marking scheduled rewards of ${body.participants.length} participants as paid`)
const scheduledRewardsDeltas = body.rewards.map(r => BigInt(r) * -1n)
const pgClient = await pgPool.connect()
try {
await pgClient.query('BEGIN')
await pgClient.query(`
UPDATE scheduled_rewards
SET
amount = scheduled_rewards.amount + bulk.amount
FROM (
SELECT *
FROM
UNNEST($1::TEXT[], $2::NUMERIC[])
AS t(address, amount)
) AS bulk
WHERE scheduled_rewards.address = bulk.address
`, [body.participants, scheduledRewardsDeltas])
await pgClient.query(`
INSERT INTO logs (address, scheduled_rewards_delta)
VALUES (UNNEST($1::TEXT[]), UNNEST($2::NUMERIC[]))
`, [body.participants, scheduledRewardsDeltas])
await pgClient.query(`
DELETE FROM logs WHERE timestamp < NOW() - INTERVAL '30 days'
`)
await pgClient.query('COMMIT')
} catch (err) {
await pgClient.query('ROLLBACK')
if (err.constraint === 'amount_not_negative') {
httpAssert.fail(400, `Scheduled rewards would become negative: ${err.detail}`)
}
throw err
} finally {
pgClient.release()
}
logger.info(`Marked scheduled rewards of ${body.participants.length} participants as paid`)
const { rows } = await pgPool.query(`
SELECT address, amount
FROM scheduled_rewards
WHERE address = ANY($1)
`, [body.participants])
json(
res,
Object.fromEntries(rows.map(({ address, amount }) => [address, String(amount)]))
)
}
async function handleGetAllScheduledRewards (res, pgPool) {
const { rows } = await pgPool.query(`
SELECT address, amount
FROM scheduled_rewards
`)
json(
res,
Object.fromEntries(rows.map(({ address, amount }) => [address, String(amount)]))
)
}
async function handleGetSingleScheduledRewards (req, res, pgPool) {
const address = req.url.split('/').pop()
const { rows } = await pgPool.query(`
SELECT amount
FROM scheduled_rewards
WHERE address = $1
`, [address])
json(
res,
String(rows[0]?.amount || '0')
)
}
async function handleGetLog (res, pgPool) {
const client = await pgPool.connect()
try {
res.setHeader('Content-Type', 'application/json')
res.write('[\n')
const cursor = client.query(new Cursor(`
SELECT timestamp, address, score, scheduled_rewards_delta
FROM logs
`, []))
let firstLine = true
while (true) {
const rows = await cursor.read(100)
for (const row of rows) {
if (!firstLine) {
res.write(',\n')
} else {
firstLine = false
}
res.write(JSON.stringify({
timestamp: row.timestamp,
address: row.address,
score: row.score ? String(row.score) : undefined,
scheduledRewardsDelta: String(row.scheduled_rewards_delta)
}))
}
if (rows.length < 100) {
await cursor.close()
break
}
}
res.end('\n]')
} finally {
client.release()
}
}
const errorHandler = (res, err, logger) => {
if (err instanceof SyntaxError) {
res.statusCode = 400
res.end('Invalid JSON Body')
} else if (err.statusCode) {
res.statusCode = err.statusCode
res.end(err.message)
} else {
logger.error(err)
res.statusCode = 500
res.end('Internal Server Error')
}
if (res.statusCode >= 500) {
Sentry.captureException(err)
}
}
export const createHandler = async ({ logger, pgPool, signerAddresses }) => {
assert(logger, '.logger required')
assert(pgPool, '.pgPool required')
assert(signerAddresses, '.signerAddresses required')
return (req, res) => {
const start = new Date()
logger.request(`${req.method} ${req.url} ...`)
handler(req, res, pgPool, signerAddresses, logger)
.catch(err => errorHandler(res, err, logger))
.then(() => {
logger.request(
`${req.method} ${req.url} ${res.statusCode} (${new Date() - start}ms)`
)
})
}
}