Skip to content

Commit

Permalink
refactor: set vercel cron job
Browse files Browse the repository at this point in the history
  • Loading branch information
cedoor committed Apr 28, 2023
1 parent 1b39f8b commit 9861519
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"scripts": {
"start": "npm-run-all -p tasks next:start",
"start": "npm-run-all -p next:start",
"dev": "yarn db:reset && npm-run-all -p tasks next:dev",
"build": "yarn lint && NODE_OPTIONS='--max-old-space-size=1536' next build --debug",
"analyze": "ANALYZE=true yarn build",
Expand Down
50 changes: 50 additions & 0 deletions src/pages/api/cron/publish-merkle-roots.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { MerkleTreeNode, MerkleTreeRootBatch, MerkleTreeRootBatchDocument } from "@interep/db"
import { NextApiRequest, NextApiResponse } from "next"
import { retrieveEvents, updateGroups } from "src/core/contracts/Interep"
import { GroupName, Provider } from "src/types/groups"
import { logger } from "src/utils/backend"

export default async function handler(_req: NextApiRequest, res: NextApiResponse) {
try {
const events = await retrieveEvents("GroupUpdated")

// Get all the new db root nodes not yet published onchain.
const merkleRoots = await MerkleTreeNode.find({
siblingHash: undefined,
hash: { $nin: events.map((e) => e.root.toString()) }
})

// If there are new db root hashes, publish them.
if (merkleRoots && merkleRoots.length > 0) {
const groupProviders = merkleRoots.map((e) => e.group.provider) as Provider[]
const groupNames = merkleRoots.map((e) => e.group.name) as GroupName[]
const roots = merkleRoots.map((e) => e.hash)

const transaction = await updateGroups(groupProviders, groupNames, roots)

for (let i = 0; i < merkleRoots.length; i++) {
const rootBatch = (await MerkleTreeRootBatch.findOne({
group: { provider: groupProviders[i], name: groupNames[i] },
transaction: undefined
})) as MerkleTreeRootBatchDocument

rootBatch.transaction = {
hash: transaction.transactionHash,
blockNumber: transaction.blockNumber
}

await rootBatch.save()
}

logger.info(`The Merkle roots have been published on-chain (${merkleRoots.length})`)
}

res.send({
status: 200
})
} catch (error: any) {
res.status(500).end()

logger.error(error)
}
}
8 changes: 8 additions & 0 deletions vercel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"crons": [
{
"path": "/api/cron/publish-merkle-roots",
"schedule": "*/1 * * * *"
}
]
}

0 comments on commit 9861519

Please sign in to comment.