Best JavaScript code snippet using wpt
rescan.test.js
Source:rescan.test.js
1const request = require('supertest');2const Joi = require('@hapi/joi');3const config = require('../../src/config');4const rescanAsyncWorker = require('../../src/rescanAsyncWorker');5const app = require('../../app');6const Rescan = require('../../models/rescan.model');7const token = require('../../src/token');8let db = null;9let adminToken = null;10const rescanValidator = Joi.object().keys({11 _id: Joi.string().hex().length(24).required(),12 currency: Joi.string().regex(/[a-zA-Z0-9]{1,5}/).required(),13 currentBlock: Joi.number().integer().min(0).required(),14 firstBlock: Joi.number().integer().min(0).required(),15 blocksLeft: Joi.number().integer().required(),16 status: Joi.string().valid('created', 'running', 'stopped', 'finished', 'failed').required(),17 error: Joi.array().items(Joi.string()).required(),18 createdAt: Joi.date().required(),19 doneAt: Joi.date()20});21beforeAll(done => {22 require('../../src/database')('_test_rescans')(conn => {23 db = conn;24 // Prepare DB25 const Client = require('../../models/client.model');26 const testClient = new Client.model({27 username: 'test',28 password: 'test123',29 createdBy: "f".repeat(24) // Dummy id30 });31 testClient.save().then(() => {32 const Coin = require('../../models/coin.model');33 const testCoin = new Coin.model({34 name: 'Oculor',35 symbol: 'ocul',36 adapter: 'rpc',37 adapterProps: {38 rpc: {39 host: '127.0.0.1',40 port: 48844,41 user: 'oculor',42 password: 'oculor-dev'43 }44 },45 createdBy: testClient._id46 });47 testCoin.save().then(coin => {48 const Admin = require('../../models/admin.model');49 const testAdmin = new Admin.model({50 username: "admin",51 password: "admin123",52 createdBy: "f".repeat(24) // Dummy id53 });54 testAdmin.save()55 .then(() => token(testAdmin.id, 'admin', '127.0.0.1'))56 .then(token => adminToken = token)57 .finally(() => done())58 .catch(console.error);59 }).catch(console.error);60 }).catch(console.error);61 });62});63describe('Tests the "start rescan" endpoint', () => {64 it('Starts a rescan by block hash', () => {65 return request(app)66 .post('/transactions/rescan')67 .set('Authorization', `Bearer ${adminToken}`)68 .set('Content-Type', 'application/json')69 .send({ block: "3a88f95980bf53945b90aa6503e27b7be4ce1cd92e5c587ddff08732200e0fbe", currency: "OCUL" })70 .expect(200)71 .expect(({ body }) => {72 const { error } = Joi.validate(body, rescanValidator);73 if(error) throw error;74 expect(body.status).toBe('running');75 });76 });77 it('Starts a rescan by block height', () => {78 return request(app)79 .post('/transactions/rescan')80 .set('Authorization', `Bearer ${adminToken}`)81 .set('Content-Type', 'application/json')82 .send({ block: 118675, currency: "OCUL" })83 .expect(200)84 .expect(({ body }) => {85 const { error } = Joi.validate(body, rescanValidator);86 if(error) throw error;87 expect(body.status).toBe('running');88 });89 });90 it('Triggers a rescan conflict', async () => {91 const rescan = new Rescan.model({92 currency: "OCUL",93 firstBlock: 118675,94 status: 'running'95 });96 97 await rescan.save();98 await request(app)99 .post('/transactions/rescan')100 .set('Authorization', `Bearer ${adminToken}`)101 .set('Content-Type', 'application/json')102 .send({ block: 118675, currency: "OCUL" })103 .expect(409);104 });105 it('Fails to start a rescan for an unknown coin', () => {106 return request(app)107 .post('/transactions/rescan')108 .set('Authorization', `Bearer ${adminToken}`)109 .set('Content-Type', 'application/json')110 .send({ block: 118675, currency: "BTC" })111 .expect(404);112 });113});114describe('Tests the "stop rescan" endpoint', () => {115 it('Stops a rescan', async () => {116 const rescan = new Rescan.model({117 currency: "OCUL",118 firstBlock: 118675119 });120 121 await rescan.save();122 rescanAsyncWorker(rescan);123 return request(app)124 .post(`/transactions/rescan/${rescan._id}/stop`)125 .set('Authorization', `Bearer ${adminToken}`)126 .expect(200)127 .expect(({ body }) => {128 const { error } = Joi.validate(body, rescanValidator);129 if(error) throw error;130 expect(body.status).toBe('stopped');131 });132 });133 it('Fails to stop a rescan with an invalid ID', () => {134 return request(app)135 .post('/transactions/rescan/invalidId/stop')136 .set('Authorization', `Bearer ${adminToken}`)137 .expect(400)138 .expect(({ body }) => {139 expect(body).toHaveProperty('error');140 })141 });142 it('Fails to stop a non-existent rescan', () => {143 return request(app)144 .post('/transactions/rescan/ffffffffffffffffffffffff/stop')145 .set('Authorization', `Bearer ${adminToken}`)146 .expect(404)147 .expect(({ text }) => {148 expect(text).toBe('Not Found');149 })150 });151 it('Fails to stop a non-running rescan', async () => {152 const rescan = new Rescan.model({153 currency: "OCUL",154 firstBlock: 118675155 });156 157 await rescan.save();158 return request(app)159 .post(`/transactions/rescan/${rescan._id}/stop`)160 .set('Authorization', `Bearer ${adminToken}`)161 .expect(400)162 .expect(({ body }) => {163 expect(body).toHaveProperty('error');164 })165 });166 it('Fails to stop a rescan without a running worker', async () => {167 const rescan = new Rescan.model({168 currency: "OCUL",169 firstBlock: 118675,170 status: "running"171 });172 173 await rescan.save();174 return request(app)175 .post(`/transactions/rescan/${rescan._id}/stop`)176 .set('Authorization', `Bearer ${adminToken}`)177 .expect(400)178 .expect(({ body }) => {179 expect(body).toHaveProperty('error');180 });181 });182});183describe('Tests the "list rescans" endpoint', () => {184 it('Lists all rescans', () => {185 return request(app)186 .get('/transactions/rescan')187 .set('Authorization', `Bearer ${adminToken}`)188 .expect(200)189 .expect(({ body }) => {190 if(!Array.isArray(body)) throw Error("Didn't receive an array of rescans");191 });192 });193});194afterEach(done => {195 Rescan.model.deleteMany().then().finally(() => {196 try197 {198 if(rescanAsyncWorker.isRunning()) rescanAsyncWorker.stop(() => done());199 else done();200 }201 catch(e)202 {203 console.error(e);204 done();205 }206 });207});208afterAll(done => {209 if(db) db.drop().finally(() => db.close().finally(() => done())).catch(console.error);...
rescanAsyncWorker.js
Source:rescanAsyncWorker.js
1const debug = require('debug')('payment-gateway:rescanAsyncWorker');2const _ = require('lodash');3const coinAdapter = require('./coin-adapters');4const config = require('./config');5const Rescan = require('../models/rescan.model');6const Payment = require('../models/payment.model');7const PaymentEvents = require('./events/payment.emitter');8let checkedForActive = false;9let running = false;10let activeRescan = null;11let finallyCallback = null;12(async () => {13 const activeRescan = await Rescan.model.findOne({ status: 'running' });14 checkedForActive = true;15 if(!activeRescan) return;16 await rescanAsyncWorker(activeRescan);17})();18rescanAsyncWorker.stop = cb => {19 if(!running || !activeRescan) throw Error("No active rescan!");20 if(typeof cb === 'function') finallyCallback = cb;21 activeRescan.status = 'stopped';22 running = false;23}24rescanAsyncWorker.isRunning = () => running;25rescanAsyncWorker.updatePayment = updatePayment;26async function rescanAsyncWorker(rescan)27{28 try29 {30 if(running || activeRescan) throw Error("Rescan already running!");31 if(!checkedForActive) throw Error("Trying to start rescan before worker init");32 running = true;33 activeRescan = rescan;34 activeRescan.status = 'running';35 await Rescan.model.updateOne({ _id: activeRescan._id }, activeRescan);36 const coin = await coinAdapter(activeRescan.currency);37 if(!coin) throw Error(`Coin ${activeRescan.currency} for rescan not found`);38 let blockHash = await coin.getBlockHash(activeRescan.currentBlock);39 if(!blockHash) throw Error("Couldn't get the current block hash");40 let block;41 let blockCount = await coin.getBlockCount();42 do43 {44 block = await coin.getBlock(blockHash);45 if(!block) throw Error(`Couldn't get block ${activeRescan.blocksLeft}:${blockHash}`);46 const { tx: blockTransactions } = block;47 for(let transactionHash of blockTransactions)48 {49 try50 {51 const transaction = await coin.getRawTransaction(transactionHash);52 if(!transaction) throw Error(`Couldn't get TX ${transactionHash}`);53 const { vout, confirmations, time } = transaction;54 for(let out of vout)55 {56 try57 {58 await updatePayment(out, confirmations, time);59 }60 catch(e)61 {62 const idx = _.indexOf(vout, out);63 debug(`Failed to process TX ${activeRescan.currency}:${transactionHash} vout ${idx} at block ${activeRescan.blocksLeft}`);64 debug(e);65 activeRescan.error.push(`Failed to process TX ${transactionHash} vout ${idx} Error: ${e.message || "General failure"}`);66 }67 }68 }69 catch(e)70 {71 debug(`Failed to process TX ${activeRescan.currency}:${transactionHash} at block ${activeRescan.blocksLeft}`);72 debug(e);73 activeRescan.error.push(`Failed to process TX ${transactionHash} Error: ${e.message || "General failure"}`);74 }75 }76 // Poll the node for the block count every 100 blocks77 activeRescan.blocksLeft =78 (block.height % 100 === 0 || (blockCount - block.height) < 0) ?79 ((blockCount = await coin.getBlockCount()) - block.height) :80 (blockCount - block.height);81 activeRescan.currentBlock = block.height;82 try83 {84 await activeRescan.save();85 }86 catch(e)87 {88 debug(`Failed to save rescan ${activeRescan._id}`);89 debug(e);90 }91 }92 while((blockHash = block.nextblockhash) && running);93 if(activeRescan.status === 'running') activeRescan.status = 'finished';94 }95 catch(e)96 {97 debug(`Rescan for ${activeRescan.currency} from block ${activeRescan.firstBlock} failed at block ${activeRescan.blocksLeft}`);98 debug(e);99 activeRescan.error.push(e.message || "General failure");100 activeRescan.status = 'failed';101 }102 finally103 {104 try105 {106 activeRescan.doneAt = new Date();107 await Rescan.model.updateOne({ _id: activeRescan._id }, activeRescan);108 }109 catch(e)110 {111 debug(`Failed to save active rescan ${activeRescan.currency}:${activeRescan.firstBlock}`);112 debug(e);113 }114 finally115 {116 running = false;117 if(typeof finallyCallback === 'function') finallyCallback(activeRescan);118 activeRescan = null;119 }120 }121}122async function updatePayment({ value, scriptPubKey }, confirmations, time)123{124 if(!value || !scriptPubKey || !scriptPubKey.addresses || scriptPubKey.addresses.constructor !== Array) return;125 for(let address of scriptPubKey.addresses)126 {127 const payment = await Payment.model.findOne({ address }).exec();128 if(!payment) continue;129 // If the payment has expired, ignore it130 if(payment.expiresAt < new Date(time * 1000))131 {132 debug(`Received TX for expired payment "${payment.id}"!`);133 PaymentEvents.looseFunds(payment, value);134 continue;135 }136 // If the value is too low, ignore it137 if(value < payment.amount)138 {139 debug(`TX for payment "${payment.id}" received, but ${value} ${payment.currency} doesn't fill the required ${payment.amount} ${payment.currency}! Ignoring.`);140 PaymentEvents.looseFunds(payment, value);141 continue;142 }143 // If the payment is already finalized, ignore it144 if(payment.paidAt)145 {146 debug(`TX received for payment "${payment.id}", but payment is already finalized. Ignoring.`);147 PaymentEvents.looseFunds(payment, value);148 continue;149 }150 const eventDispatchOrder = [ 'received', 'confirmation', 'finalized' ]; // Helps us fire queued events in the correct order151 const eventQueue = []; // Track the events we need to fire after we're done152 if(confirmations > payment.confirmations) eventQueue.push('confirmation');153 payment.confirmations = confirmations;154 if(confirmations < config.requiredConfirmations && !payment.receivedAt)155 {156 payment.receivedAt = Date.now();157 eventQueue.push('received');158 }159 else if(confirmations >= config.requiredConfirmations && !payment.paidAt)160 {161 if(!payment.receivedAt)162 {163 payment.receivedAt = Date.now();164 eventQueue.push('received');165 }166 167 payment.paidAt = Date.now();168 eventQueue.push('finalized');169 }170 await payment.save();171 // Fire all queued events in the correct order172 eventDispatchOrder.forEach(e => {173 if(eventQueue.includes(e) && typeof PaymentEvents[e] === 'function') PaymentEvents[e](payment);174 });175 }176}...
RescanProgress.js
Source:RescanProgress.js
...38 <RescanCancelButton {...{rescanRequest, rescanCancel}} />39 </div>40 </div>41);...
Using AI Code Generation
1var wptoolkit = require("wptoolkit");2wptoolkit.rescan();3var wptoolkit = require("wptoolkit");4wptoolkit.rescan();5{6 "themes": {7 "twentyten": {8 },9 "twentyeleven": {
Using AI Code Generation
1var wptoolkit = require('wptoolkit');2wptoolkit.rescan();3var wptoolkit = require('wptoolkit');4wptoolkit.rescan();5var wptoolkit = require('wptoolkit');6wptoolkit.rescan();7var wptoolkit = require('wptoolkit');8wptoolkit.rescan();9var wptoolkit = require('wptoolkit');10wptoolkit.rescan();11var wptoolkit = require('wptoolkit');12wptoolkit.rescan();13var wptoolkit = require('wptoolkit');14wptoolkit.rescan();15var wptoolkit = require('wptoolkit');16wptoolkit.rescan();17var wptoolkit = require('wptoolkit');18wptoolkit.rescan();19var wptoolkit = require('wptoolkit');20wptoolkit.rescan();21var wptoolkit = require('wptoolkit');22wptoolkit.rescan();23var wptoolkit = require('wptoolkit');24wptoolkit.rescan();25var wptoolkit = require('wptoolkit');26wptoolkit.rescan();27var wptoolkit = require('wptoolkit');28wptoolkit.rescan();
Using AI Code Generation
1var wptools = require('wptools');2var page = wptools.page('Barack Obama');3page.get(function(err, resp) {4 console.log(resp);5});6var wptools = require('wptools');7var page = wptools.page('Barack Obama');8page.rescan(function(err, resp) {9 console.log(resp);10});11var wptools = require('wptools');12var page = wptools.page('Barack Obama');13page.rescan('Barack Obama', function(err, resp) {14 console.log(resp);15});16var wptools = require('wptools');17var page = wptools.page('Barack Obama');18page.rescan('Barack Obama', 'en', function(err, resp) {19 console.log(resp);20});21var wptools = require('wptools');22var page = wptools.page('Barack Obama');23page.rescan('Barack Obama', 'en', 'Barack Obama', function(err, resp) {24 console.log(resp);25});26var wptools = require('wptools');27var page = wptools.page('Barack Obama');28page.rescan('Barack Obama', 'en', 'Barack Obama', 'Barack Obama', function(err, resp) {29 console.log(resp);30});31var wptools = require('wptools');32var page = wptools.page('Barack Obama');33page.rescan('Barack Obama', 'en', 'Barack Obama', 'Barack Obama', 'Barack Obama', function(err, resp) {34 console.log(resp);35});36var wptools = require('wptools');37var page = wptools.page('Barack Obama');38page.rescan('Barack Obama', 'en', 'Barack Obama',
Using AI Code Generation
1var wptools = require('wptools');2wptools.rescan('Albert Einstein', function(err, data) {3 console.log(data);4});5var wptools = require('wptools');6wptools.rescan('Albert Einstein', function(err, data) {7 console.log(data);8});9var wptools = require('wptools');10wptools.rescan('Albert Einstein', function(err, data) {11 console.log(data);12});13var wptools = require('wptools');14wptools.rescan('Albert Einstein', function(err, data) {15 console.log(data);16});17var wptools = require('wptools');18wptools.rescan('Albert Einstein', function(err, data) {19 console.log(data);20});21var wptools = require('wptools');22wptools.rescan('Albert Einstein', function(err, data) {23 console.log(data);24});25var wptools = require('wptools');26wptools.rescan('Albert Einstein', function(err, data) {27 console.log(data);28});29var wptools = require('wptools');30wptools.rescan('Albert Einstein', function(err, data) {31 console.log(data);32});33var wptools = require('wptools');34wptools.rescan('Albert Einstein', function(err, data) {35 console.log(data);36});37var wptools = require('wptools');38wptools.rescan('Albert Einstein', function(err, data) {39 console.log(data);40});
Using AI Code Generation
1var wpToolkit = require('wptoolkit');2wpToolkit.rescan(function(err, data){3 if(err){4 console.log(err);5 }else{6 console.log(data);7 }8});9var wpToolkit = require('wptoolkit');10wpToolkit.rescan(function(err, data){11 if(err){12 console.log(err);13 }else{14 console.log(data);15 }16});17var wpToolkit = require('wptoolkit');18wpToolkit.rescan(function(err, data){19 if(err){20 console.log(err);21 }else{22 console.log(data);23 }24});25var wpToolkit = require('wptoolkit');26wpToolkit.rescan(function(err, data){27 if(err){28 console.log(err);29 }else{30 console.log(data);31 }32});33var wpToolkit = require('wptoolkit');34wpToolkit.rescan(function(err, data){35 if(err){36 console.log(err);37 }else{38 console.log(data);39 }40});41var wpToolkit = require('wptoolkit');42wpToolkit.rescan(function(err, data){43 if(err){44 console.log(err);45 }else{46 console.log(data);47 }48});49var wpToolkit = require('wptoolkit');50wpToolkit.rescan(function(err, data){51 if(err){52 console.log(err);53 }else{54 console.log(data);55 }56});57var wpToolkit = require('wptoolkit');58wpToolkit.rescan(function(err, data){59 if(err){60 console.log(err);61 }else{62 console.log(data);63 }64});65var wpToolkit = require('wptoolkit');66wpToolkit.rescan(function
Using AI Code Generation
1var wptools = require('wptools');2var wp = wptools.page('Albert Einstein');3wp.rescan(function(err, resp) {4 console.log(resp);5});6var wptools = require('wptools');7var wp = wptools.page('Albert Einstein');8wp.get(function(err, resp) {9 console.log(resp);10});
Using AI Code Generation
1var wptoolkit = require('wptoolkit');2var rescan = wptoolkit.rescan;3rescan('wp', function (err, result) {4 if (err) {5 console.log(err);6 }7 else {8 console.log(result);9 }10});11The callback function will be called with two arguments, the first will be an error object (null if there was no error) and the second will be the result object. If there was an error, the result object will be null. If there was no error, the result object will be an object containing the following properties:12var wptoolkit = require('wptoolkit');13var rescan = wptoolkit.rescan;14rescan('wp', function (err, result) {15 if (err) {16 console.log(err);17 }18 else {19 console.log(result);20 }21});22The callback function will be called with two arguments, the first will be an error object (null if there was no error) and the second will be the result object. If there was an error, the result object will be null. If there was no error, the result object will be an object containing the following properties:
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!!