Search…
Complete Executable Code
Putting all of the pieces together, this is the full executable
/*
* Import statements
*/
const cron = require('node-cron');
const fs = require('fs');
const NODE_MODE_SERVICE = 'service';
const axios = require('axios');
// Using Web3Storage to make uploading to IPFS easier
const { Web3Storage, getFilesFromPath } = require('web3.storage');
const storageClient = new Web3Storage({ token: process.env.WEB3_STORAGE_KEY });
​
/**
* @description Setup function is the first
* function that is called in executable to setup the node
*/
async function setup() {
console.log('Running setup function');
// Run default setup
await namespace.defaultTaskSetup();
}
​
/**
* @description Using to validate an individual node. Returns true if node is valid
*/
async function validateNode(node) {
console.log("Validating Node", node);
const cid = node.submission_value;
const res = await client.get(cid);
const { data, error } = await namespace.verifySignedData(res, node.submitterPubkey);
const quoteOfTheDay = getQuoteOfTheDay();
// If
// CID does not point to hosted data
// Or data is signed incorrectly
// Or if that data does not match the quote of the day
// -> Then the node is invalid
if (!res.ok || error || data != quoteOfTheDay) {
return false;
} else {
return true;
}
}
​
async function getQuoteOfTheDay() {
axios({
method: 'get',
url: 'https://favqs.com/api/qotd'
}).then(async (response) => {
if (response.data) {
return response.data;
}
}).catch(err => {
console.log("Failed to get Quote of the day", err.message);
})
​
}
​
async function task() {
const quoteOfTheDay = getQuoteOfTheDay();
// TODO sign data uploaded to IPFS to prove node uploaded it
const qodJSON = JSON.stringify(quoteOfTheDay);
const signedJSON = await namespace.signData(qodJSON);
fs.writeFileSync("qod.json", signedJSON);
if (storageClient) {
// Storing on IPFS through web3 storage as example
const file = await getFilesFromPath('./qod.json');
const cid = await storageClient.put(file);
console.log("CID of Uploaded Data: ", cid);
await namespace.redisSet('cid', cid);
await namespace.checkSubmissionAndUpdateRound(cid);
} else {
console.error("No web3 storage API key provided");
}
}
​
/**
* @description Execute function is called just after the setup function to run Submit, Vote API in cron job
* @returns return all cron schedule from execute function for graceful termination
*/
async function execute() {
let cronArray = [];
if (process.env.NODE_MODE == NODE_MODE_SERVICE) {
cronArray.push(
cron.schedule('*/1 * * * *', task),
);
}
cronArray.push(cron.schedule('*/1 * * * *', () => { namespace.validateAndVoteOnNodes(validateNode) }));
return cronArray;
}
Copy link