-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopy-leaves.js
82 lines (75 loc) · 2.67 KB
/
copy-leaves.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
/**
* One-off script to copy leaves from old on-chain
* Merkle tree into new off-chain Merkle tree.
*/
const { ethers } = require("ethers");
require('dotenv').config();
const { IncrementalMerkleTree } = require("@zk-kit/incremental-merkle-tree");
const { GetItemCommand, PutItemCommand } = require("@aws-sdk/client-dynamodb");
const ABIs = require('./constants/abis');
const addresses = require('./constants/contract-addresses.json');
const { ddbClient } = require('./dynamodb');
const { poseidonHashQuinary } = require('./utils/utils');
async function main() {
console.log('Getting on-chain leaves')
// Get current on-chain leaves
const provider = new ethers.providers.AlchemyProvider('optimism', process.env.ALCHEMY_APIKEY);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
const hubContract = new ethers.Contract(addresses.Hub.mainnet['optimism'], ABIs.Hub, provider);
const onChainLeaves = await hubContract.getLeaves();
// Get current off-chain leaves
console.log('Getting off-chain leaves')
const leaves = []
const LeavesTableName = "Leaves"; // name for table used in production
for (let index = 0; index < 14 ** 5; index++) {
await new Promise(resolve => setTimeout(resolve, 500));
const data = await ddbClient.send(new GetItemCommand({
TableName: LeavesTableName,
Key: {
"LeafIndex": {
N: index.toString()
}
}
}));
const leaf = data.Item?.LeafValue?.S;
if (!leaf) break;
leaves.push(leaf);
}
console.log('leaves.length', leaves.length)
// Diff on-chain leaves with off-chain leaves
const leavesToCopy =
onChainLeaves
.filter(leaf => !leaves.includes(leaf))
.map(leaf => leaf.toString());
console.log('leavesToCopy.length', leavesToCopy.length)
// Copy leaves to off-chain Merkle tree
let index = leaves.length;
for (const leaf of leavesToCopy) {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('Copying leaf', leaf)
await ddbClient.send(new PutItemCommand({
TableName: LeavesTableName,
Item: {
'LeafIndex': {
N: index.toString()
},
'LeafValue': {
S: leaf
},
// "SignedLeaf": {
// S: signedLeaf
// }
}
}));
index++;
}
// Update on-chain Merkle root
console.log('Updating on-chain Merkle root')
const tree = new IncrementalMerkleTree(poseidonHashQuinary, 14, "0", 5);
for (const leaf of leaves.concat(leavesToCopy)) {
tree.insert(leaf);
}
const rootsContract = new ethers.Contract(addresses.Roots.mainnet['optimism'], ABIs.Roots, wallet);
await rootsContract.addRoot(tree.root);
}
main().then(() => console.log('done'))