Best JavaScript code snippet using mountebank
reward.js
Source:reward.js
1const axios = require('axios')2const { tomoValidator, blockSigner } = require('./tomo')3const config = require('config')4const db = require('../models')5const logger = require('./logger')6const BigNumber = require('bignumber.js')7const Web3Util = require('./web3')8const BlockHelper = require('./block')9const contractAddress = require('../contracts/contractAddress')10const urlJoin = require('url-join')11const elastic = require('../helpers/elastic')12const RewardHelper = {13 updateVoteHistory: async (epoch) => {14 const endBlock = parseInt(epoch) * config.get('BLOCK_PER_EPOCH')15 let startBlock = endBlock - config.get('BLOCK_PER_EPOCH') + 116 if (parseInt(epoch) === 2) {17 startBlock = endBlock - (config.get('BLOCK_PER_EPOCH') * 2) + 118 }19 logger.info('Get vote history from block %s to block %s', startBlock, endBlock)20 await db.VoteHistory.deleteOne({ blockNumber: { $gte: startBlock, $lte: endBlock } })21 if (parseInt(epoch) === 2) {22 const defaultCandidate = config.get('defaultCandidate')23 const candidates = []24 const map = defaultCandidate.map(candidate => {25 candidates.push({26 txHash: null,27 blockNumber: 1,28 event: 'Propose',29 blockHash: null,30 voter: candidate.owner,31 owner: candidate.owner,32 candidate: candidate.candidate,33 cap: candidate.cap34 })35 })36 await Promise.all(map)37 await db.VoteHistory.insertMany(candidates)38 }39 const contract = await tomoValidator.getValidatorContractWs()40 await contract.getPastEvents('allEvents', { fromBlock: startBlock, toBlock: endBlock })41 .then(async (events) => {42 const map = events.map(async function (event) {43 const voter = String(event.returnValues._voter || '').toLowerCase()44 const owner = String(event.returnValues._owner || '').toLowerCase()45 const candidate = String(event.returnValues._candidate || '').toLowerCase()46 const cap = new BigNumber(event.returnValues._cap || 0)47 const capTomo = cap.dividedBy(10 ** 18)48 BigNumber.config({ EXPONENTIAL_AT: [-100, 100] })49 return {50 txHash: event.transactionHash,51 blockNumber: event.blockNumber,52 event: event.event,53 blockHash: event.blockHash,54 voter: voter,55 owner: owner,56 candidate: candidate,57 cap: capTomo.toNumber()58 }59 })60 return Promise.all(map)61 })62 .then(async data => {63 if (data.length > 0) {64 await db.VoteHistory.insertMany(data)65 }66 return true67 }).catch(async (e) => {68 logger.warn('Cannot get vote history from block %s to %s. Sleep 2 seconds and try more. Error %s',69 startBlock, endBlock, e)70 const sleep = (time) => new Promise((resolve) => setTimeout(resolve, time))71 await sleep(2000)72 await Web3Util.reconnectWeb3Socket()73 return RewardHelper.updateVoteHistory(epoch)74 })75 return true76 },77 rewardProcess: async (epoch) => {78 epoch = parseInt(epoch)79 const startBlock = (epoch - 1) * config.get('BLOCK_PER_EPOCH') + 180 const endBlock = (epoch) * config.get('BLOCK_PER_EPOCH')81 const maxBlockNum = await BlockHelper.getLastBlockNumber()82 if (maxBlockNum - config.get('BLOCK_PER_EPOCH') < endBlock) {83 logger.warn('Epoch %s is waiting for calculate', epoch)84 return85 }86 logger.info('Calculate reward from block %s to block %s', startBlock, endBlock)87 // Delete old reward88 logger.info('Remove old reward of epoch %s', epoch)89 await db.Reward.deleteOne({ epoch: epoch })90 const totalReward = new BigNumber(config.get('REWARD'))91 const validatorRewardPercent = new BigNumber(config.get('MASTER_NODE_REWARD_PERCENT'))92 const foundationRewardPercent = new BigNumber(config.get('FOUNDATION_REWARD_PERCENT'))93 const voterRewardPercent = new BigNumber(config.get('VOTER_REWARD_PERCENT'))94 // Update block signer95 for (let i = startBlock; i <= endBlock; i = i + 50) {96 const its = []97 for (let j = i; j < i + 50; j++) {98 its.push(j)99 }100 logger.info('Update block signer from block %s to block %s', i, i + 49)101 const map = its.map(async (b) => {102 const block = await BlockHelper.getBlock(b)103 const ss = await blockSigner.getSigners(block.hash)104 await db.BlockSigner.updateOne({105 blockHash: block.hash,106 blockNumber: b107 }, {108 $set: {109 blockHash: block.hash,110 blockNumber: b,111 signers: ss.map(it => (it || '').toLowerCase())112 }113 }, {114 upsert: true115 })116 })117 await Promise.all(map)118 }119 // Get list event in range start - end block120 await RewardHelper.updateVoteHistory(epoch + 1)121 // Vote history process122 await RewardHelper.voteHistoryProcess(epoch)123 logger.info('Duplicate vote amount from prev to epoch %s', epoch)124 // Find in history and duplicate to this epoch if not found125 const voteInEpoch = await db.UserVoteAmount.find({ epoch: epoch - 1 })126 const data = []127 for (let j = 0; j < voteInEpoch.length; j++) {128 const nextEpoch = await db.UserVoteAmount.findOne({129 voter: voteInEpoch[j].voter,130 epoch: epoch,131 candidate: voteInEpoch[j].candidate132 })133 if (!nextEpoch) {134 data.push({135 voter: voteInEpoch[j].voter,136 epoch: voteInEpoch[j].epoch + 1,137 voteAmount: voteInEpoch[j].voteAmount,138 candidate: voteInEpoch[j].candidate139 })140 }141 }142 if (data.length > 0) {143 await db.UserVoteAmount.insertMany(data)144 }145 let totalSignNumber = 0146 const validators = []147 const voteHistory = await db.UserVoteAmount.find({ epoch: epoch })148 for (let i = 0; i < voteHistory.length; i++) {149 if (validators.indexOf(voteHistory[i].candidate) < 0) {150 validators.push(voteHistory[i].candidate)151 }152 }153 const rewardValidator = []154 const validatorSigners = []155 const validatorMap = validators.map(async (validator) => {156 validator = validator.toString().toLowerCase()157 const validatorSignNumber = await db.BlockSigner158 .countDocuments({159 blockNumber: { $gte: startBlock, $lte: endBlock },160 signers: validator161 })162 if (validatorSignNumber > 0) {163 totalSignNumber += validatorSignNumber164 validatorSigners.push({165 address: validator,166 signNumber: validatorSignNumber167 })168 }169 })170 await Promise.all(validatorMap)171 logger.info('calculate reward for list validator at epoch %s', epoch)172 const validatorFinal = validatorSigners.map(async (validator) => {173 const reward4group = totalReward.multipliedBy(validator.signNumber).dividedBy(totalSignNumber)174 const reward4validator = reward4group.multipliedBy(validatorRewardPercent).dividedBy(100)175 const reward4foundation = reward4group.multipliedBy(foundationRewardPercent).dividedBy(100)176 const reward4voter = reward4group.multipliedBy(voterRewardPercent).dividedBy(100)177 const blockRewardCalculate = (epoch + 1) * config.get('BLOCK_PER_EPOCH')178 const block = await db.Block.findOne({ number: blockRewardCalculate })179 let timestamp = new Date()180 if (!block) {181 const _block = await BlockHelper.getBlock(blockRewardCalculate)182 if (_block) {183 timestamp = _block.timestamp * 1000184 }185 } else {186 timestamp = block.timestamp187 }188 await RewardHelper.rewardVoterProcess(189 epoch,190 validator.address,191 validator.signNumber,192 reward4voter.toString(),193 timestamp194 )195 let ownerValidator = await tomoValidator.getCandidateOwner(validator.address)196 ownerValidator = ownerValidator.toString().toLowerCase()197 const userVoteAmount = await db.UserVoteAmount.findOne({198 candidate: validator.address,199 voter: ownerValidator,200 epoch: epoch201 })202 const lockBalance = (userVoteAmount || { voteAmount: 0 }).voteAmount203 await rewardValidator.push({204 epoch: epoch,205 startBlock: startBlock,206 endBlock: endBlock,207 address: ownerValidator,208 validator: validator.address,209 reason: 'MasterNode',210 lockBalance: lockBalance.toString(),211 reward: reward4validator.toString(),212 rewardTime: timestamp,213 signNumber: validator.signNumber214 })215 // Reward for foundation216 await rewardValidator.push({217 epoch: epoch,218 startBlock: startBlock,219 endBlock: endBlock,220 address: contractAddress.TomoFoundation,221 validator: validator.address,222 reason: 'Foundation',223 lockBalance: 0,224 reward: reward4foundation.toString(),225 rewardTime: timestamp,226 signNumber: validator.signNumber227 })228 })229 await Promise.all(validatorFinal)230 if (rewardValidator.length > 0) {231 await db.Reward.insertMany(rewardValidator)232 }233 },234 voteHistoryProcess: async (epoch) => {235 logger.info('Remove old user vote amount for epoch %s', epoch)236 await db.UserVoteAmount.deleteOne({ epoch: epoch })237 if (epoch === 1) {238 await db.UserVoteAmount.deleteOne({ epoch: 0 })239 }240 const endBlock = (parseInt(epoch) + 1) * config.get('BLOCK_PER_EPOCH')241 let startBlock = endBlock - config.get('BLOCK_PER_EPOCH') + 1242 if (parseInt(epoch) === 1) {243 startBlock = endBlock - config.get('BLOCK_PER_EPOCH') * 2 + 1244 }245 // Calculate user vote for validator246 const histories = await db.VoteHistory.find({247 blockNumber: { $gte: startBlock, $lte: endBlock }248 }).sort({ blockNumber: 1 })249 logger.info('There are %s histories in epoch %s', histories.length, epoch)250 for (let i = 0; i < histories.length; i++) {251 const history = histories[i]252 if (history.event === 'Propose') {253 const data = {254 voter: history.owner,255 candidate: history.candidate,256 epoch: Math.floor(history.blockNumber / config.get('BLOCK_PER_EPOCH')),257 voteAmount: history.cap258 }259 await db.UserVoteAmount.create(data)260 } else if (history.event === 'Vote') {261 const h = await db.UserVoteAmount.findOne({262 voter: history.voter,263 candidate: history.candidate,264 epoch: { $lte: epoch }265 }).sort({ epoch: -1 })266 await db.UserVoteAmount.updateOne({267 voter: history.voter,268 candidate: history.candidate,269 // epoch: Math.floor(history.blockNumber / config.get('BLOCK_PER_EPOCH'))270 epoch: epoch271 }, {272 voteAmount: (h || { voteAmount: 0 }).voteAmount + history.cap273 }, { upsert: true, new: true })274 } else if (history.event === 'Unvote') {275 const h = await db.UserVoteAmount.findOne({276 voter: history.voter,277 candidate: history.candidate,278 epoch: { $lte: epoch }279 }).sort({ epoch: -1 })280 await db.UserVoteAmount.updateOne({281 voter: history.voter,282 candidate: history.candidate,283 // epoch: Math.floor(history.blockNumber / config.get('BLOCK_PER_EPOCH'))284 epoch: epoch285 }, {286 voteAmount: (h ? h.voteAmount : 0) - history.cap287 }, { upsert: true, new: true })288 } else if (history.event === 'Resign') {289 const h = await db.UserVoteAmount.findOne({290 voter: history.voter,291 candidate: history.candidate,292 epoch: { $lt: epoch }293 }).sort({ epoch: -1 })294 await db.UserVoteAmount.updateOne({295 voter: history.voter,296 candidate: history.candidate,297 epoch: Math.ceil(history.blockNumber / config.get('BLOCK_PER_EPOCH'))298 }, {299 voteAmount: (h ? h.voteAmount : 0) - history.cap300 }, { upsert: true, new: true })301 }302 }303 },304 rewardVoterProcess: async (epoch, validator, validatorSignNumber, totalReward, rewardTime) => {305 logger.info('Process reward for voter of validator %s', validator)306 totalReward = new BigNumber(totalReward)307 const endBlock = parseInt(epoch) * config.get('BLOCK_PER_EPOCH')308 const startBlock = endBlock - config.get('BLOCK_PER_EPOCH') + 1309 const voteEpoch = await db.UserVoteAmount.find({ epoch: epoch, candidate: validator })310 let totalVoterCap = 0311 for (let i = 0; i < voteEpoch.length; i++) {312 totalVoterCap += voteEpoch[i].voteAmount313 }314 totalVoterCap = new BigNumber(totalVoterCap)315 let rewardVoter = []316 for (let i = 0; i < voteEpoch.length; i++) {317 const voterAddress = voteEpoch[i].voter318 const voterAmount = new BigNumber(voteEpoch[i].voteAmount)319 if (String(voterAmount) !== '0') {320 const reward = totalReward.multipliedBy(voterAmount).dividedBy(totalVoterCap)321 await rewardVoter.push({322 epoch: epoch,323 startBlock: startBlock,324 endBlock: endBlock,325 address: voterAddress,326 validator: validator,327 reason: 'Voter',328 lockBalance: voterAmount.toString(),329 reward: reward.toString(),330 rewardTime: rewardTime,331 signNumber: validatorSignNumber332 })333 if (rewardVoter.length === 5000) {334 await db.Reward.insertMany(rewardVoter)335 rewardVoter = []336 }337 }338 }339 if (rewardVoter.length > 0) {340 await db.Reward.insertMany(rewardVoter)341 }342 },343 rewardOnChain: async (epoch, calculateTime = 0) => {344 const block = await BlockHelper.getBlock((parseInt(epoch) + 1) * config.get('BLOCK_PER_EPOCH'))345 const endBlock = parseInt(epoch) * config.get('BLOCK_PER_EPOCH')346 const startBlock = endBlock - config.get('BLOCK_PER_EPOCH')347 const data = {348 jsonrpc: '2.0',349 method: 'eth_getRewardByHash',350 params: [block.hash],351 id: 88352 }353 try {354 await db.Reward.deleteMany({ epoch: epoch })355 await db.EpochSign.deleteMany({ epoch: epoch })356 try {357 await elastic.deleteByQuery('rewards', {358 query: {359 term: { epoch: epoch }360 }361 })362 } catch (e) {363 logger.warn('there are no reward at epoch %s to delete', epoch)364 }365 // const response = await axios.post('http://128.199.228.202:8545/', data)366 const response = await axios.post(config.get('WEB3_URI'), data)367 const result = response.data368 let haveReward = false369 if (!result.error) {370 const signNumber = result.result.signers371 const rewards = result.result.rewards372 const url = urlJoin(config.get('TOMOMASTER_API_URL'), '/api/candidates')373 const c = await axios.get(url)374 const canR = c.data.items375 const canName = {}376 if (canR) {377 for (let i = 0; i < canR.length; i++) {378 canName[canR[i].candidate] = canR[i].name379 }380 }381 let rdata = []382 let mnNumber = 0383 for (const m in rewards) {384 mnNumber += 1385 for (const v in rewards[m]) {386 if (!haveReward) {387 haveReward = true388 }389 let r = new BigNumber(rewards[m][v])390 r = r.dividedBy(10 ** 18).toString()391 const item = {392 epoch: epoch,393 startBlock: startBlock,394 endBlock: endBlock,395 address: v.toLowerCase(),396 validator: m.toLowerCase(),397 validatorName: canName[m.toLowerCase()] ? canName[m.toLowerCase()] : 'Anonymous',398 reason: v.toLowerCase() === contractAddress.TomoFoundation ? 'Foundation' : 'Voter',399 lockBalance: 0,400 reward: r,401 rewardTime: block.timestamp * 1000,402 signNumber: signNumber[m].sign403 }404 await elastic.indexWithoutId('rewards', item)405 rdata.push(item)406 if (rdata.length === 100) {407 logger.info('insert %s _rewards_ item at epoch %s', rdata.length, epoch)408 await db.Reward.insertMany(rdata)409 rdata = []410 }411 }412 }413 if (rdata.length > 0) {414 logger.info('insert %s _rewards_ item at epoch %s', rdata.length, epoch)415 await db.Reward.insertMany(rdata)416 }417 let sdata = []418 for (const m in signNumber) {419 sdata.push({420 epoch: epoch,421 validator: m.toLowerCase(),422 signNumber: signNumber[m].sign423 })424 if (sdata.length === 100) {425 await db.EpochSign.insertMany(sdata)426 sdata = []427 }428 }429 if (sdata.length > 0) {430 await db.EpochSign.insertMany(sdata)431 }432 const sBlock = await BlockHelper.getBlockDetail(startBlock)433 const eBlock = await BlockHelper.getBlockDetail(endBlock)434 if (!haveReward) {435 logger.info('There is no _rewards_ found. Wait 10 seconds and retry')436 const sleep = (time) => new Promise((resolve) => setTimeout(resolve, time))437 await sleep(10000)438 calculateTime += 1439 if (calculateTime === 5) {440 logger.error('Cannot find _rewards_ for epoch %s at block %s', epoch, block)441 return false442 }443 return RewardHelper.rewardOnChain(epoch, calculateTime)444 }445 const vNumber = await db.Reward.distinct('address', { epoch: epoch })446 await db.Epoch.updateOne({ epoch: epoch }, {447 epoch: epoch,448 startBlock: startBlock,449 endBlock: endBlock,450 startTime: sBlock.timestamp,451 endTime: eBlock.timestamp,452 duration: (new Date(eBlock.timestamp) - new Date(sBlock.timestamp)) / 1000,453 masterNodeNumber: mnNumber,454 voterNumber: vNumber.length,455 isActive: true456 }, { upsert: true, new: true })457 return true458 } else {459 logger.warn('There are some error get _rewards_ of epoch %s. Error %s', epoch,460 JSON.stringify(result.error))461 return false462 }463 } catch (e) {464 logger.warn('There are something error of epoch %s. Error %s', epoch, e)465 return false466 }467 }468}...
RewardController.js
Source:RewardController.js
1const { Router } = require('express')2const { paginate } = require('../helpers/utils')3const db = require('../models')4const BigNumber = require('bignumber.js')5const logger = require('../helpers/logger')6const { check, validationResult } = require('express-validator/check')7const config = require('config')8const Web3Util = require('../helpers/web3')9const RewardController = Router()10RewardController.get('/rewards/:slug', [11 check('limit').optional().isInt({ max: 100 }).withMessage('Limit is less than 100 items per page'),12 check('page').optional().isInt({ max: 500 }).withMessage('Page is less than or equal 500'),13 check('slug').exists().isLength({ min: 42, max: 42 }).withMessage('Account address is incorrect.')14], async (req, res) => {15 const errors = validationResult(req)16 if (!errors.isEmpty()) {17 return res.status(400).json({ errors: errors.array() })18 }19 let address = req.params.slug20 address = address.toLowerCase()21 try {22 const params = {}23 if (address) {24 params.query = { address: address }25 }26 const acc = await db.Account.findOne({ hash: address })27 let total = null28 if (acc) {29 total = acc.rewardCount30 }31 params.sort = { epoch: -1 }32 const data = await paginate(req, 'Reward', params, total)33 if (data.pages > 500) {34 data.pages = 50035 }36 return res.json(data)37 } catch (e) {38 logger.warn('Cannot find reward of address %s. Error %s', address, e)39 return res.status(500).json({ errors: { message: 'Something error!' } })40 }41})42RewardController.get('/rewards/alerts/status', [], async (req, res) => {43 const web3 = await Web3Util.getWeb3()44 const lastBlock = await web3.eth.getBlockNumber()45 const currentEpoch = Math.floor(lastBlock / config.get('BLOCK_PER_EPOCH'))46 const lastEpochReward = currentEpoch - 147 const checkExistOnDb = await db.Reward.find({ epoch: lastEpochReward }).limit(1)48 let slow = false49 if (checkExistOnDb.length === 0 && (lastBlock - currentEpoch * config.get('BLOCK_PER_EPOCH')) >= 150) {50 slow = true51 }52 return res.json({53 lastBlock: lastBlock,54 currentEpoch: Math.ceil(lastBlock / config.get('BLOCK_PER_EPOCH')),55 lastEpochReward: lastEpochReward,56 isSlow: slow57 })58})59RewardController.get('/rewards/epoch/:epochNumber', [60 check('limit').optional().isInt({ max: 100 }).withMessage('Limit is less than 100 items per page'),61 check('page').optional().isInt({ max: 500 }).withMessage('Page is less than or equal 500'),62 check('epochNumber').isInt().exists().withMessage('Epoch number is require')63], async (req, res) => {64 const errors = validationResult(req)65 if (!errors.isEmpty()) {66 return res.status(400).json({ errors: errors.array() })67 }68 const epochNumber = req.params.epochNumber || 069 try {70 const params = {}71 params.query = { epoch: epochNumber }72 const reason = req.query.reason73 if (reason === 'voter') {74 params.query = Object.assign({}, params.query,75 { reason: { $ne: 'Foundation' } })76 } else if (reason === 'foundation') {77 params.query = Object.assign({}, params.query,78 { reason: 'Foundation' })79 }80 const data = await paginate(req, 'Reward', params)81 if (data.pages > 500) {82 data.pages = 50083 }84 return res.json(data)85 } catch (e) {86 logger.warn('Cannot find reward of epoch %s. Error %s', epochNumber, e)87 return res.status(500).json({ errors: { message: 'Something error!' } })88 }89})90RewardController.get('/rewards/total/:slug/:fromEpoch/:toEpoch', [91 check('slug').exists().isLength({ min: 42, max: 42 }).withMessage('Account address is incorrect.'),92 check('fromEpoch').exists().isInt().withMessage('From epoch is require'),93 check('toEpoch').exists().isInt().withMessage('To epoch is require')94], async (req, res) => {95 const errors = validationResult(req)96 if (!errors.isEmpty()) {97 return res.status(400).json({ errors: errors.array() })98 }99 try {100 let address = req.params.slug101 const fromEpoch = req.params.fromEpoch102 const toEpoch = req.params.toEpoch103 address = address.toLowerCase()104 const acc = await db.Account.findOne({ hash: address })105 if (!acc) {106 return res.json({ address: address, totalReward: 0 })107 }108 const rewards = await db.Reward.find({109 address: address,110 epoch: { $gte: fromEpoch, $lte: toEpoch }111 })112 let total = new BigNumber(0)113 for (let i = 0; i < rewards.length; i++) {114 let rw = new BigNumber(rewards[i].reward)115 rw = rw.dividedBy(10 ** 18)116 total = total.plus(rw)117 }118 return res.json({ address: address, totalReward: total.toNumber() })119 } catch (e) {120 logger.warn(e)121 return res.status(400).send()122 }123})124RewardController.post('/expose/rewards', async (req, res) => {125 try {126 const address = req.body.address || null127 const owner = req.body.owner || null128 const reason = req.body.reason || null129 let limit = !isNaN(req.body.limit) ? parseInt(req.body.limit) : 200130 if (limit > 200) {131 limit = 200132 }133 const page = !isNaN(req.body.page) ? parseInt(req.body.page) : 1134 const skip = limit * (page - 1)135 let params = {}136 if (owner) {137 params = {138 validator: address.toLowerCase(),139 address: owner.toLowerCase()140 }141 } else {142 params = {143 address: address.toLowerCase()144 }145 }146 if (reason) {147 params = Object.assign(params, { reason: reason })148 }149 const totalReward = db.Reward.countDocuments(params)150 const reward = await db.Reward.find(params).sort({ epoch: -1 }).limit(limit).skip(skip).exec()151 res.send({152 items: reward,153 total: await totalReward154 })155 } catch (e) {156 logger.warn(e)157 return res.status(400).send()158 }159})160RewardController.post('/expose/MNRewardsByEpochs', [161 check('address').exists().withMessage('Account address is required.'),162 check('owner').exists().withMessage('owner is required'),163 check('reason').exists().withMessage('reason is required'),164 check('epoch').exists().withMessage('epoch is required')165], async (req, res) => {166 try {167 const address = req.body.address || null168 const owner = req.body.owner || null169 const reason = req.body.reason || null170 const epoch = req.body.epoch || []171 let params = {}172 if (reason) {173 params = Object.assign(params, { reason: reason })174 }175 const map = epoch.map(async (e) => {176 params = {177 validator: address.toLowerCase(),178 address: owner.toLowerCase(),179 reason: reason,180 epoch: e181 }182 const totalReward = new BigNumber(config.get('REWARD'))183 let result = await db.Reward.findOne(params).exec()184 if (result) {185 result = result.toObject()186 const signNumbers = await db.EpochSign.find({ epoch: e })187 let totalSign = 0188 const map = signNumbers.map(function (signNumber) {189 totalSign += signNumber.signNumber190 })191 await Promise.all(map)192 if (totalSign > 0) {193 result.masternodeReward = totalReward.multipliedBy(result.signNumber)194 .dividedBy(totalSign).multipliedBy(0.4) // 40% for masternode195 } else result.masternodeReward = result.reward196 return result197 } else {198 return {199 epoch: e200 }201 }202 })203 const r = await Promise.all(map)204 res.json(r)205 } catch (e) {206 logger.warn(e)207 return res.status(400).send()208 }209})210RewardController.post('/expose/signNumber/:epochNumber', [211 check('epochNumber').exists().isInt().withMessage('Epoch number is require & need a number')212], async (req, res) => {213 const errors = validationResult(req)214 if (!errors.isEmpty()) {215 return res.status(400).json({ errors: errors.array() })216 }217 try {218 const epoch = req.params.epochNumber || null219 const signNumbers = await db.EpochSign.find({ epoch: epoch })220 return res.json(signNumbers)221 } catch (e) {222 logger.warn(e)223 return res.status(400).send()224 }225})226RewardController.post('/expose/totalSignNumber/:epochNumber', [227 check('epochNumber').exists().isInt().withMessage('Epoch number is require & need a number')228], async (req, res) => {229 const errors = validationResult(req)230 if (!errors.isEmpty()) {231 return res.status(400).json({ errors: errors.array() })232 }233 try {234 const epoch = req.params.epochNumber || null235 const signNumbers = await db.EpochSign.find({ epoch: epoch })236 let totalSign = 0237 const map = signNumbers.map(function (signNumber) {238 totalSign += signNumber.signNumber239 })240 await Promise.all(map)241 return res.json({ epoch: epoch, totalSignNumber: totalSign })242 } catch (e) {243 logger.warn(e)244 return res.status(400).send()245 }246})...
EpochController.js
Source:EpochController.js
1const { Router } = require('express')2const db = require('../models')3const Web3Util = require('../helpers/web3')4const config = require('config')5const logger = require('../helpers/logger')6const { check, validationResult } = require('express-validator/check')7const utils = require('../helpers/utils')8const EpochController = Router()9EpochController.get('/epochs', [10 check('limit').optional().isInt({ max: 50 }).withMessage('Limit is less than 50 items per page'),11 check('page').optional().isInt({ max: 500 }).withMessage('Page is less than or equal 500')12], async (req, res) => {13 const errors = validationResult(req)14 if (!errors.isEmpty()) {15 return res.status(400).json({ errors: errors.array() })16 }17 try {18 const web3 = await Web3Util.getWeb3()19 const lastBlock = await web3.eth.getBlockNumber()20 const lastEpoch = Math.floor(lastBlock / config.get('BLOCK_PER_EPOCH'))21 const params = { sort: { epoch: -1 }, query: { isActive: true } }22 const data = await utils.paginate(req, 'Epoch', params, lastEpoch)23 data.lastBlock = lastBlock24 data.lastEpoch = lastEpoch25 if (data.pages > 500) {26 data.pages = 50027 }28 return res.json(data)29 } catch (e) {30 logger.warn('Error get list epochs %s', e)31 return res.status(500).json({ errors: { message: 'Something error!' } })32 }33})34EpochController.get('/epochs/:slug', [35 check('slug').exists().withMessage('Epoch number is incorrect.')36], async (req, res) => {37 const errors = validationResult(req)38 if (!errors.isEmpty()) {39 return res.status(400).json({ errors: errors.array() })40 }41 const epochNumber = req.params.slug42 const web3 = await Web3Util.getWeb3()43 const lastBlock = await web3.eth.getBlockNumber()44 const lastEpoch = Math.ceil(lastBlock / config.get('BLOCK_PER_EPOCH')) - 145 const epoch = await db.Epoch.findOne({ epoch: epochNumber })46 if (!epoch) {47 return res.status(404).json({ errors: { message: 'Epoch is not found or does not finish!' } })48 }49 const masterNodeNumber = await db.Reward.distinct('validator', { epoch: epochNumber })50 const rewardVoter = await db.Reward.countDocuments({ epoch: epochNumber, reason: { $ne: 'Foundation' } })51 const rewardFoundation = await db.Reward.countDocuments({ epoch: epochNumber, reason: 'Foundation' })52 return res.json({53 epoch: epochNumber,54 startBlock: epoch.startBlock,55 endBlock: epoch.endBlock,56 masterNodeNumber: epoch.masterNodeNumber,57 masterNode: masterNodeNumber,58 slashedNode: epoch.slashedNode,59 voterNumber: epoch.voterNumber,60 rewardVoter: rewardVoter,61 rewardFoundation: rewardFoundation,62 startTime: epoch.startTime,63 endTime: epoch.endTime,64 lastEpoch: lastEpoch65 })66})...
Using AI Code Generation
1var mb = require('mountebank');2 {3 {4 {5 is: {6 }7 }8 }9 }10];11mb.create({ imposters: imposters }, function (error, server) {12 console.log('Mountebank server started on port 2525');13});
Using AI Code Generation
1var mb = require('mountebank'),2 imposter = {3 stubs: [{4 predicates: [{5 equals: {6 headers: {7 }8 }9 }],10 responses: [{11 is: {12 headers: {13 },14 body: JSON.stringify({ status: "OK" })15 }16 }]17 }]18 };19mb.create(imposter, function (error, imposter) {20 console.log('imposter', imposter.port);21});22var mbjs = require('mbjs'),23 imposter = {24 stubs: [{25 predicates: [{26 equals: {27 headers: {28 }29 }30 }],31 responses: [{32 is: {33 headers: {34 },35 body: JSON.stringify({ status: "OK" })36 }37 }]38 }]39 };40mbjs.createImposter(4545, imposter, function (error, imposter) {41 console.log('imposter', imposter.port);42});
Using AI Code Generation
1var mb = require('mountebank'),2 assert = require('assert'),3 Q = require('q'),4 {5 {6 {7 is: {8 headers: {9 },10 }11 }12 }13 }14 ];15mb.start({ port: port, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*'] })16 .then(function () {17 return mb.post('/imposters', imposters);18 })19 .then(function (response) {20 assert.equal(response.statusCode, 201);21 return mb.get('/imposters');22 })23 .then(function (response) {24 assert.equal(response.statusCode, 200);25 return mb.del('/imposters');26 })27 .then(function (response) {28 assert.equal(response.statusCode, 200);29 return mb.stop();30 })31 .then(function () {32 console.log('All done!');33 })34 .done();35var mb = require('mountebank'),36 assert = require('assert'),37 Q = require('q'),38 {39 {40 {41 is: {42 headers: {43 },44 }45 }46 }47 }48 ];49mb.start({ port: port, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*'] })50 .then(function () {51 return mb.post('/imposters', imposters);52 })53 .then(function (response) {54 assert.equal(response.statusCode, 201);55 return mb.get('/imposters');56 })57 .then(function (response) {58 assert.equal(response.statusCode, 200);59 return mb.del('/impost
Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var protocol = 'http';4mb.create(port, protocol, function (error, imposter) {5 imposter.post('/test', function (request, response) {6 response.statusCode = 200;7 response.body = 'Hello world!';8 response.send();9 }, function (error, stub) {10 console.log('Stub created with ID: ' + stub.id);11 });12});
Using AI Code Generation
1var mb = require('mountebank');2var fs = require('fs');3mb.create({4}, function () {5 mb.post('/imposters', {6 {7 {8 equals: {9 }10 }11 {12 is: {13 headers: {14 },15 body: JSON.stringify({ "id": 1, "name": "test" })16 }17 }18 }19 }, function (error, response) {20 console.log(response.body);21 });22});23mb.del('/imposters/3000', function (error, response) {24 console.log(response.body);25});26mb.del('/imposters', function (error, response) {27 console.log(response.body);28});29mb.create({30}, function () {31 mb.post('/imposters', {32 {33 {34 equals: {35 }36 }37 {38 is: {39 headers: {40 },41 body: JSON.stringify({ "id": 1, "name": "test" })42 }43 }44 }45 }, function (error, response) {46 console.log(response.body);47 });48});49mb.del('/imposters/3000', function (error, response) {50 console.log(response.body);51});
Using AI Code Generation
1var mb = require('mountebank');2mb.create().then(function (imposter) {3 var port = imposter.port;4 console.log('Imposter listening on port ' + port);5});6var mb = require('mountebank');7mb.create().then(function (imposter) {8 var port = imposter.port;9 console.log('Imposter listening on port ' + port);10});11var mb = require('mountebank');12mb.create(function (error, imposter) {13 var port = imposter.port;14 console.log('Imposter listening on port ' + port);15});16var mb = require('mountebank');17mb.create().then(function (imposter) {18 var port = imposter.port;19 console.log('Imposter listening on port ' + port);20});21var mb = require('mountebank');22mb.create(function (error, imposter) {23 var port = imposter.port;24 console.log('Imposter listening on port ' + port);25});26var mb = require('mountebank');27mb.create().then(function (imposter) {28 var port = imposter.port;29 console.log('Imposter listening on port ' + port);30});31var mb = require('mountebank');32mb.create(function (error, imposter) {33 var port = imposter.port;34 console.log('Imposter listening on port ' + port);35});36var mb = require('mountebank');37mb.create().then(function (imposter) {38 var port = imposter.port;39 console.log('Imposter listening on port ' + port);40});41var mb = require('mountebank');42mb.create(function (error, imposter) {43 var port = imposter.port;44 console.log('Imposter listening on port ' + port);45});46var mb = require('mountebank');47mb.create().then(function (imposter) {48 var port = imposter.port;
Using AI Code Generation
1var assert = require('assert');2var mb = require('mountebank');3mb.create({4}, function (error, server) {5 assert.ifError(error);6 server.post('/imposters', {7 stubs: [{8 responses: [{9 is: {10 }11 }]12 }]13 }, function (error, response) {14 assert.ifError(error);15 assert.strictEqual(response.statusCode, 201);16 mb.get('/imposters', function (error, response, imposters) {17 assert.ifError(error);18 assert.strictEqual(response.statusCode, 200);19 assert.strictEqual(imposters.length, 1);20 mb.get('/imposters/8080', function (error, response, imposter) {21 assert.ifError(error);22 assert.strictEqual(response.statusCode, 200);23 assert.strictEqual(imposter.port, 8080);24 assert.strictEqual(imposter.protocol, 'http');25 assert.strictEqual(imposter.stubs.length, 1);26 assert.strictEqual(imposter.stubs[0].responses.length, 1);27 assert.strictEqual(imposter.stubs[0].responses[0].is.statusCode, 200);28 assert.strictEqual(imposter.stubs[0].responses[0].is.body, 'Hello, world!');29 assert.ifError(error);30 assert.strictEqual(response.statusCode, 200);31 assert(body.indexOf('localhost') > -1);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!