-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
728 lines (616 loc) · 26.6 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
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
require('dotenv').config()
const fsPromises = require('node:fs/promises');
const { randomBytes } = require('crypto');
const { ethers } = require('./utils/get-ethers.js');
const { NonceManager } = require("@ethersproject/experimental");
const express = require('express')
const app = express()
const cors = require('cors')
const axios = require('axios')
const Mutex = require('async-mutex').Mutex;
const tryAcquire = require('async-mutex').tryAcquire;
const withTimeout = require('async-mutex').withTimeout;
const { cloneDeep } = require('lodash')
const { CreateXChainContract, callContractWithNonceManager } = require('./xccontract')
const { IncrementalMerkleTree } = require("@zk-kit/incremental-merkle-tree");
const { poseidon } = require('circomlibjs-old');
const { backupTreePath, whitelistedIssuers, nftAddresses } = require('./constants/misc');
const nftABIData = require('./constants/abis/nft.json');
const { initAddresses, getAddresses } = require("./utils/contract-addresses");
const { poseidonHashQuinary } = require('./utils/utils');
const { verifyProofCircom } = require('./utils/proofs');
const { mint } = require('./utils/nft');
const dynamodb = require('./dynamodb');
const corsOpts = {
origin: ["https://holonym.io", "https://holonym.id","https://app.holonym.io","https://app.holonym.id", "https://staging.holonym.io", "https://metrics.holonym-internal.net", "http://localhost:3000", "http://localhost:3001", "http://localhost:3002", "http://localhost:8080", "http://localhost:8081"],
optionsSuccessStatus: 200 // For legacy browser support
}
app.use(cors(corsOpts));
app.use(express.json());
const port = process.env.PORT || 3000;
// const { contracts } = require('./constants')
// const provider = ethers.getDefaultProvider(process.env.ALCHEMY_RPCURL, {
// // etherscan: YOUR_ETHERSCAN_API_KEY,
// // infura: YOUR_INFURA_PROJECT_ID,
// // // Or if using a project secret:
// // // infura: {
// // // projectId: YOUR_INFURA_PROJECT_ID,
// // // projectSecret: YOUR_INFURA_PROJECT_SECRET,
// // // },
// alchemy: process.env.ALCHEMY_APIKEY,
// // pocket: {
// // applicationId: process.env.POCKET_RELAYER_APPID,
// // applicationSecretKey: process.env.POCKET_RELAYER_SECRET
// // },
// // ankr: YOUR_ANKR_API_KEY
// });
let xcontracts = {}
// mutexes are used to prevent race conditions from occuring during tree updates
const mutexes = {};
// let treeHasBeenInitialized = false;
const trees = {} //new IncrementalMerkleTree(poseidonHashQuinary, 14, "0", 5);
// let leafCountAtLastBackup = 0;
let addresses
const init = async (networkNames) => {
await initAddresses();
addresses = getAddresses();
for (const contractName of Object.keys(addresses)) {
xcontracts[contractName] = await CreateXChainContract(contractName);
}
for (const networkName of networkNames) {
await initTree(networkName);
mutexes[networkName] = new Mutex();
}
};
const addLeaf = async (args) => {
const { issuer, signature, proof } = args;
const { v, r, s } = ethers.utils.splitSignature(signature);
const txs = await xcontracts["Hub"].addLeaf(
issuer,
v,
r,
s,
Object.keys(proof.proof).map(k=>proof.proof[k]), // Convert proof object to ethers format to be serialized into a Solidity struct
proof.inputs
);
for (const networkName of Object.keys(txs)) {
if (txs[networkName]?.wait) txs[networkName] = await txs[networkName].wait();
}
return txs;
}
const writeProof = async (proofContractName, networkName, callParams) => {
const { proof, inputs } = callParams;
// const tx = await xcontracts[proofContractName].contracts[networkName].prove(
// Object.keys(proof).map(k=>proof[k]), // Convert struct to ethers format
// inputs
// );
const contract = xcontracts[proofContractName].contracts[networkName];
const nonceManager = xcontracts[proofContractName].nonceManagers[networkName];
const args = [
Object.keys(proof).map(k=>proof[k]), // Convert struct to ethers format
inputs
]
const tx = await callContractWithNonceManager(contract, "prove", nonceManager, args);
const result = {...tx};
if (tx?.wait) {
const txReceipt = await tx.wait();
result.blockNumber = txReceipt.blockNumber;
result.transactionHash = txReceipt.transactionHash;
}
return result;
}
async function backupTree(tree, networkName) {
try {
await fsPromises.writeFile(`${backupTreePath}/${networkName}.json`, JSON.stringify(tree));
leafCountAtLastBackup = tree.leaves.length;
} catch (err) {
console.error(err)
}
}
async function updateTree(network) {
try {
await tryAcquire(mutexes[network]).runExclusive(async () => {
const contract = xcontracts["Hub"].contracts[network];
const index = trees[network].leaves.length;
const newLeaves = (await contract.getLeavesFrom(index)).map(leaf => leaf.toString());
for (const leaf of newLeaves) {
trees[network].insert(leaf);
}
if (trees[network].leaves) {
await backupTree(trees[network], network);
}
});
} catch (err) {
console.log('Error updating tree on network', network);
console.log(err);
}
}
app.post('/addLeaf', async (req, res, next) => {
console.log(new Date().toISOString());
console.log('addLeaf called with args ', JSON.stringify(req.body, null, 2));
try {
// Ensure leaf was signed by whitelisted issuer
if (process.env.HARDHAT_TESTING !== 'true') {
const { issuer, signature, proof } = req.body;
if (!whitelistedIssuers.includes(issuer.toLowerCase())) {
return res.status(400).send("Issuer is not whitelisted");
}
const msg = ethers.utils.arrayify(proof.inputs[0]); // leaf
const leafSigner = ethers.utils.verifyMessage(msg, signature.compact)
if (leafSigner.toLowerCase() !== issuer.toLowerCase()) {
return res.status(400).send("Signature is not from issuer");
}
}
const txReceipts = await addLeaf(req.body);
// if addLeaf doesn't throw, we assume tx was successful
for (const networkName of Object.keys(trees)) {
await updateTree(networkName);
}
res.status(200).json(txReceipts);
} catch(e) {
console.error(e);
res.status(400).send(e);
return;
}
})
// proofContractName: "IsUSResident" or "SybilResistance"
// network: "optimism-goerli", "hardhat", ...
// writeProofArgs
app.post('/writeProof/:proofContractName/:network', async (req, res) => {
console.log(new Date().toISOString());
console.log(`writeProof/${req.params.proofContractName}/${req.params.network} endpoint called with args `, JSON.stringify(req.body, null, 2));
try {
const txReceipt = await writeProof(req.params.proofContractName, req.params.network, req.body.writeProofArgs);
if (process.env.NODE_ENV !== "development") {
const sender = '0x' + req.body.writeProofArgs.inputs[1].slice(-40)
mint(req.params.proofContractName, sender)
.then((tx) => console.log("minted NFT. tx:", tx))
.catch((err) => console.error("mint error:", err));
}
res.status(200).json(txReceipt);
} catch(e) {
console.error(e);
res.status(400).send(e);
return;
}
})
app.get('/getLeaves/:network', async (req, res) => {
const contract = xcontracts["Hub"]?.contracts[req.params.network];
if (!contract) return res.send([]);
const leaves = await contract.getLeaves();
res.send(leaves.map(leaf=>leaf.toString()));
})
app.get('/getTree/:network', async (req, res) => {
if (!(req.params.network in trees)) {
return res.status(500).json({ error: "Merkle tree has not been initialized" });
}
// Trigger tree update. Tree is updated asynchronously so that request can be served immediately
updateTree(req.params.network);
// Wait 400ms for tree updates (we aren't awaiting udpateTree because of the exclusive mutex; we don't want to wait forever if the queue for updating the tree is long)
await new Promise(resolve => setTimeout(resolve, 400));
let tree = trees[req.params.network];
return res.status(200).json(tree);
})
app.get('/', (req, res) => {
res.send('For this endpoint, POST your addLeaf parameters to /addLeaf and it will submit an addLeaf() transaction to Hub')
})
async function initTree(networkName) {
let tree = new IncrementalMerkleTree(poseidonHashQuinary, 14, "0", 5);
if(networkName === "hardhat") { console.error("WARNING: not initializing hardhat tree from backup, as hardhat network's state is not persistent and this would load a deleted tree"); trees["hardhat"] = tree; return }
if(!(networkName in xcontracts["Hub"].contracts)) return; // If it doesn't support the network, abort and return an empty Merkle Tree
console.log("Initializing in-memory merkle tree for", networkName)
console.time(`tree-initialization-${networkName}`)
// Initialize tree from backup. This step ensures that we can respond to getTree
// requests immediately after this Node.js process restarts. It might take hours to
// reconstruct the tree from leaves in the smart contract.
try {
const backupTreeStr = await fsPromises.readFile(`${backupTreePath}/${networkName}.json`, 'utf8');
const backupTree = JSON.parse(backupTreeStr);
tree._nodes = backupTree._nodes;
tree._root = backupTree._root;
tree._zeroes = backupTree._zeroes;
} catch (err) {
console.error("initTree: ", err);
}
// Initialize tree from contract
const numLeaves = tree._nodes[0].length;
const newLeaves = (await xcontracts["Hub"].contracts[networkName].getLeavesFrom(numLeaves)).map(leaf => leaf.toString());
for (const leaf of newLeaves) {
tree.insert(leaf);
}
// treeHasBeenInitialized = true;
console.log("Merkle tree in memory has been initialized for", networkName)
console.timeEnd(`tree-initialization-${networkName}`)
trees[networkName] = tree;
await backupTree(tree, networkName);
}
// --------------------------------------------------
// START v2 stuff
// --------------------------------------------------
const mutexWithTimeout = withTimeout(new Mutex(), 30 * 1000);
const tree = new IncrementalMerkleTree(poseidonHashQuinary, 14, "0", 5);
let treeV2HasBeenInitialized = false;
async function initTreeV2() {
console.log("Initializing in-memory merkle tree for v2")
console.time(`tree-initialization-v2`)
// Initialize tree from DynamoDB backup
await dynamodb.createLeavesTableIfNotExists();
// level is level in tree (where 0 is level of leaves).
// 14 is tree depth. 5 is tree arity. 14^5 is number of leaves.
for (let index = 0; index < 14 ** 5; index++) {
await new Promise(r => setTimeout(r, 20));
if (process.env.NODE_ENV === 'development') await new Promise(r => setTimeout(r, 200));
const data = await dynamodb.getLeafAtIndex(index);
const leaf = data.Item?.LeafValue?.S;
if (!leaf) break;
tree.insert(leaf);
}
treeV2HasBeenInitialized = true;
console.log("Merkle tree in memory has been initialized for v2")
console.timeEnd(`tree-initialization-v2`)
}
/**
* Insert the leaf into the cached tree and the tree in the database, and update the on-chain roots.
*/
async function insertLeaf(newLeaf, signedLeaf) {
if (!treeV2HasBeenInitialized) throw new Error("Tree has not been initialized yet");
const txs = {};
// The mutex here is crucial. Without it, there is no way to guarantee that node updates are
// happening in the correct order.
await mutexWithTimeout.runExclusive(async () => {
// Add the leaf to the database. We update the database first so that if an error occurs during,
// the request, neither the tree in the database nor the tree in memory is updated. All errors
// are bubbled to the caller of this function.
await dynamodb.putLeaf(newLeaf, signedLeaf, tree.leaves.length);
// Update local tree object
tree.insert(newLeaf);
// Update on-chain roots
for (const network of Object.keys(xcontracts["Roots"].contracts)) {
const root = tree.root;
const contract = xcontracts["Roots"].contracts[network];
const nonceManager = xcontracts["Roots"].nonceManagers[network];
const tx = await callContractWithNonceManager(contract, "addRoot", nonceManager, [root]);
if (tx?.wait) await tx.wait();
txs[network] = tx;
}
});
return txs;
}
app.post('/v2/addLeaf', async (req, res) => {
return res.status(308).header('Location', '/v3/addLeaf').send();
if (process.env.HARDHAT_TESTING !== 'true') {
console.log(new Date().toISOString());
console.log('v2 addLeaf called with args ', JSON.stringify(req.body, null, 2));
}
try {
const signedLeaf = req.body?.publicSignals?.[0];
const newLeaf = req.body?.publicSignals?.[1];
if (!signedLeaf || !newLeaf) throw new Error('Leaf not found in request body');
// Check that the new leaf was not created with a signed leaf that has already been used
const data = await dynamodb.getLeavesBySignedLeaf(signedLeaf)
if (data?.Items.length > 0) throw new Error('Cannot create more than one new leaf from a single signed leaf');
// Verify onAddLeaf proof
const result = verifyProofCircom('onAddLeaf', req.body);
if (!result) throw new Error('Invalid proof');
// Update tree in memory and database, and update on-chain roots
const txs = await insertLeaf(newLeaf, signedLeaf);
res.status(200).json(txs);
} catch(e) {
console.error(e);
res.status(400).send(e);
return;
}
})
app.get('/v2/getLeaves/', async (req, res) => {
return res.status(308).header('Location', '/v3/getLeaves').send();
if (!treeV2HasBeenInitialized) {
return res.status(500).json({ error: "Tree has not been initialized yet" });
}
res.send(tree.leaves);
})
app.get('/v2/getTree/', async (req, res) => {
return res.status(308).header('Location', '/v3/getTree').send();
if (!treeV2HasBeenInitialized) {
return res.status(500).json({ error: "Tree has not been initialized yet" });
}
res.status(200).json(tree);
})
app.get('/v2/leafExists/:leaf', async (req, res) => {
return res.status(308).header('Location', `/v3/leafExists/${req.params.leaf}`).send();
if (!treeV2HasBeenInitialized) {
return res.status(500).json({ error: "Tree has not been initialized yet" });
}
const leaf = req.params.leaf;
const exists = tree.leaves.includes(leaf);
res.status(200).json({ exists });
});
app.get('/v2/rootIsRecent/:root', async (req, res) => {
return res.status(308).header('Location', `/v3/rootIsRecent/${req.params.root}`).send();
if (!treeV2HasBeenInitialized) {
return res.status(500).json({ error: "Tree has not been initialized yet" });
}
const root = req.params.root;
let isRecent = false;
for (const network of Object.keys(xcontracts["Roots"].contracts)) {
const contract = xcontracts["Roots"].contracts[network];
isRecent = await contract.rootIsRecent(root);
if (isRecent) break;
}
res.status(200).json({ isRecent });
});
// --------------------------------------------------
// END v2 stuff
// --------------------------------------------------
// --------------------------------------------------
// START v3 stuff
//
// BIG NOTE: v2 and v3 cannot be used simultaneously because they have
// different in-memory merkle trees. v2 will be sunsetted once v3 is
// fully tested and deployed.
// --------------------------------------------------
const addLeafMutexV3 = withTimeout(new Mutex(), 30 * 1000);
// softFinalizedTreeV3 includes all the added leaves but its root is not in the
// recentRoots mapping on chain
let softFinalizedTreeV3 = new IncrementalMerkleTree(poseidonHashQuinary, 14, "0", 5);
// finalizedTreeV3 does not include all the added leaves but its root is in the
// recentRoots mapping on chain
let finalizedTreeV3 = new IncrementalMerkleTree(poseidonHashQuinary, 14, "0", 5);
// rootAtLastBackupV3 allows us to ensure that we only write the tree to the backup
// file if the tree as changed since the last backup. This in turn allows us to
// avoid unnecessary write costs.
let rootAtLastBackupV3 = '';
let treeV3HasBeenInitialized = false;
async function initTreeV3FromBackupFile() {
try {
const backupTreeStr = await fsPromises.readFile(`${backupTreePath}/tree.json`, 'utf8');
const backupTree = JSON.parse(backupTreeStr);
softFinalizedTreeV3._nodes = backupTree._nodes;
softFinalizedTreeV3._root = backupTree._root;
softFinalizedTreeV3._zeroes = backupTree._zeroes;
finalizedTreeV3._nodes = backupTree._nodes;
finalizedTreeV3._root = backupTree._root;
finalizedTreeV3._zeroes = backupTree._zeroes;
return true
} catch (err) {
console.error("initTreeV3 error:", err);
return false
}
}
async function initTreeV3FromDatabase() {
// level is level in tree (where 0 is level of leaves).
// 14 is tree depth. 5 is tree arity. 14^5 is number of leaves.
for (let index = 0; index < 14 ** 5; index++) {
await new Promise(r => setTimeout(r, 20));
if (process.env.NODE_ENV === 'development') await new Promise(r => setTimeout(r, 200));
const data = await dynamodb.getLeafAtIndex(index);
const leaf = data.Item?.LeafValue?.S;
if (!leaf) break;
softFinalizedTreeV3.insert(leaf);
finalizedTreeV3.insert(leaf);
}
}
async function initTreeV3() {
console.log("Initializing in-memory merkle tree for v3")
console.time(`tree-initialization-v3`)
await dynamodb.createLeavesTableIfNotExists();
// NOTE: Backing up to a file is commented out for now because it is not necessary
// for performance reasons yet. In the future, once the tree includes 100,000+
// leaves, we might want to revisit this. However, we probably won't need file
// backups until the leaf count is in the millions.
// const initializedFromBackup = await initTreeV3FromBackupFile();
// if (!initializedFromBackup) {
// await initTreeV3FromDatabase()
// }
await initTreeV3FromDatabase()
treeV3HasBeenInitialized = true;
console.log("Merkle tree in memory has been initialized for v3")
console.timeEnd(`tree-initialization-v3`)
}
/**
* Insert the leaf into the cached tree and the tree in the database, and update the on-chain roots.
*/
async function insertLeafV3(newLeaf, signedLeaf) {
if (!treeV3HasBeenInitialized) throw new Error("Tree has not been initialized yet");
// The mutex here is crucial. Without it, there is no way to guarantee that node updates are
// happening in the correct order.
await addLeafMutexV3.runExclusive(async () => {
// Add the leaf to the database. We update the database first so that if an error occurs during
// the request, neither the tree in the database nor the tree in memory is updated. All errors
// are bubbled to the caller of this function.
await dynamodb.putLeaf(newLeaf, signedLeaf, softFinalizedTreeV3.leaves.length);
// Update local tree object
softFinalizedTreeV3.insert(newLeaf);
});
}
app.post('/v3/addLeaf', async (req, res) => {
// return res.status(501).json({ error: "Not implemented" });
if (process.env.HARDHAT_TESTING !== 'true') {
console.log(new Date().toISOString());
console.log('v3 addLeaf called with args ', JSON.stringify(req.body, null, 2));
}
try {
const signedLeaf = req.body?.publicSignals?.[0];
const newLeaf = req.body?.publicSignals?.[1];
if (!signedLeaf || !newLeaf) throw new Error('Leaf not found in request body');
// Check that the new leaf was not created with a signed leaf that has already been used
const data = await dynamodb.getLeavesBySignedLeaf(signedLeaf)
if (data?.Items.length > 0) throw new Error('Cannot create more than one new leaf from a single signed leaf');
// Verify onAddLeaf proof
const result = verifyProofCircom('onAddLeaf', req.body);
if (!result) throw new Error('Invalid proof');
// Update tree in memory and database
await insertLeafV3(newLeaf, signedLeaf);
res.status(200).json({ success: true });
} catch(e) {
console.error(e);
res.status(400).send(e);
}
})
/**
* /finalize-pending-tree sets the finalized tree to the soft finalized tree, writes the soft
* finalized tree to a file, and updates the on-chain root to reflect the new finalized tree.
*/
app.post('/v3/finalize-pending-tree', async (req, res) => {
// return res.status(501).json({ error: "Not implemented" });
try {
// Only allow requests with the admin API key
if (req.headers['x-api-key'] !== process.env.ADMIN_API_KEY) {
return res.status(401).json({ error: "Unauthorized" });
}
if (!treeV3HasBeenInitialized) throw new Error("Tree has not been initialized yet");
// TODO: Question: Is it possible for softFinalizedTreeV3 to be in the process
// of updating (due to a call to /v3/addLeaf) at the same time that this cloneDeep
// call is executing? If so, we should keep the mutex to prevent this case. If not,
// we should remove the mutex to improve performance.
let finalizedTree;
await addLeafMutexV3.runExclusive(() => {
finalizedTree = cloneDeep(softFinalizedTreeV3)
});
// NOTE: Backing up to a file is commented out for now because it is not necessary
// for performance reasons yet. In the future, once the tree includes 100,000+
// leaves, we might want to revisit this. However, we probably won't need file
// backups until the leaf count is in the millions.
// try {
// if (finalizedTree.root !== rootAtLastBackupV3) {
// await fsPromises.writeFile(
// `${backupTreePath}/tree.json`,
// JSON.stringify(finalizedTree)
// );
// rootAtLastBackupV3 = finalizedTree.root;
// }
// } catch (err) {
// console.error('/v3/finalize-pending-tree error:', err)
// return res.status(500).json({ error: "Failed to write tree to file" });
// }
const rootOnNetworkIsRecent = {};
for (const network of Object.keys(xcontracts["Roots"].contracts)) {
const contract = xcontracts["Roots"].contracts[network];
isRecent = await contract.rootIsRecent(finalizedTree.root);
rootOnNetworkIsRecent[network] = isRecent;
}
// Update on-chain roots if root is not recent
const txs = {};
const networksWithOutdatedRoots = Object.keys(rootOnNetworkIsRecent).filter(
(network) => !rootOnNetworkIsRecent[network]
)
for (const network of networksWithOutdatedRoots) {
const contract = xcontracts["Roots"].contracts[network];
const nonceManager = xcontracts["Roots"].nonceManagers[network];
const tx = await callContractWithNonceManager(contract, "addRoot", nonceManager, [finalizedTree.root]);
if (tx?.wait) await tx.wait();
txs[network] = tx;
}
finalizedTreeV3 = finalizedTree
return res.status(200).json({ success: true, txs });
} catch (err) {
console.error(err);
res.status(400).send(err)
}
})
app.get('/v3/getLeaves/', async (req, res) => {
// return res.status(501).json({ error: "Not implemented" });
if (!treeV3HasBeenInitialized) {
return res.status(500).json({ error: "Tree has not been initialized yet" });
}
res.send(finalizedTreeV3.leaves);
})
app.get('/v3/getTree/', async (req, res) => {
// return res.status(501).json({ error: "Not implemented" });
if (!treeV3HasBeenInitialized) {
return res.status(500).json({ error: "Tree has not been initialized yet" });
}
res.status(200).json(finalizedTreeV3);
})
app.get('/v3/leafExists/:leaf', async (req, res) => {
// return res.status(501).json({ error: "Not implemented" });
if (!treeV3HasBeenInitialized) {
return res.status(500).json({ error: "Tree has not been initialized yet" });
}
const leaf = req.params.leaf;
const exists = finalizedTreeV3.leaves.includes(leaf);
res.status(200).json({ exists });
})
app.get('/v3/rootIsRecent/:root', async (req, res) => {
// return res.status(501).json({ error: "Not implemented" });
if (!treeV3HasBeenInitialized) {
return res.status(500).json({ error: "Tree has not been initialized yet" });
}
const root = req.params.root;
let isRecent = false;
for (const network of Object.keys(xcontracts["Roots"].contracts)) {
const contract = xcontracts["Roots"].contracts[network];
isRecent = await contract.rootIsRecent(root);
if (isRecent) break;
}
res.status(200).json({ isRecent });
});
// --------------------------------------------------
// END v3 stuff
// --------------------------------------------------
/**
* This endpoint is only intended to be used temporarily. In the migration
* back to using this relayer to submit proofs, some users did not receive
* NFTs. This endpoint allows us to manually mint NFTs to those users.
*/
app.post('/mint/:proofContractName/:recipient', async (req, res) => {
try {
const proofContractName = req.params.proofContractName;
const recipient = req.params.recipient;
// Get proof contract
const proofContract = xcontracts[proofContractName].contracts["optimism"];
if (!proofContract) return res.status(400).json({ error: "Invalid proofContractName" });
// Get nftContract
const optimismProvider = new ethers.providers.AlchemyProvider(
"optimism",
process.env.ALCHEMY_APIKEY
)
const nftWallet = new ethers.Wallet(process.env.MINTER_PRIVATE_KEY, optimismProvider);
const nftNonceManager = new NonceManager(nftWallet);
const nftAddr = nftAddresses[proofContractName];
const nftABI = nftABIData.abi;
const nftContract = new ethers.Contract(nftAddr, nftABI, nftWallet);
const nftBalance = await nftContract.balanceOf(recipient);
// Make sure user doesn't already have the NFT
if (nftBalance.gt(0)) {
return res.status(400).json({ error: "User already has NFT" });
}
// Make sure user has proven uniqueness or US residency
if (proofContractName.includes("Sybil")) {
const defaultActionId = "123456789"
const isUniqueForAction = await proofContract.isUniqueForAction(recipient, defaultActionId);
if (!isUniqueForAction) {
return res.status(400).json({ error: "User has not proven uniqueness" });
}
} else if (proofContractName.includes("USResident")) {
const isUSResident = await proofContract.usResidency(recipient)
if (!isUSResident) {
return res.status(400).json({ error: "User is not a US resident" });
}
}
// User has passed checks. Mint their NFT.
const tokenid = '0x' + randomBytes(32).toString('hex');
const tx = await callContractWithNonceManager(
nftContract,
"safeMint",
nftNonceManager,
[recipient, tokenid]
)
return res.status(200).json(tx);
} catch (err) {
console.error(err);
res.status(500).json({ error: "An unexpected error occurred" })
}
})
app.listen(port, () => {
console.log('Started server on port', port);
})
module.exports.appPromise = new Promise(
function(resolve, reject) {
const networks = ["optimism-goerli", "optimism"];
if (process.env.NODE_ENV === 'development') networks.push('hardhat')
init(networks)
.then(initTreeV2)
.then(initTreeV3)
.then(resolve(app))
}
); // For testing app with Chai