const utils = require("./utils"); const db = require("./db"); const sync = require("./sync"); const metamgr = require("./metamgr"); const log = require("./log"); const C = require("./C"); class TransferMgr { constructor() { this.pendingWithdrawalHash = {}; this.historyWithdrawalCond = new sync.Cond(); this.newWithdrawalCond = new sync.Cond(); utils.registerEventHandler( C.REMOVE_PENDING_ORDER_EVENT, (idx) => { this.removePendingWithdrawal(idx); } ); } init() { setTimeout(this.start.bind(this), 1000 * 0.1); } async start() { const {err, row} = await db.execQueryOne( 'SELECT max(idx) max_idx FROM t_withdrawal', []); if (err) { throw err; } const hisMaxIdx = Math.max(0, utils.emptyReplace(row['max_idx'], 0)); setTimeout(this.historyWithdrawal.bind(this, hisMaxIdx), 1000 * 0.1); setTimeout(this.newWithdrawal.bind(this, hisMaxIdx), 1000 * 0.1); } async historyWithdrawal(hisMaxIdx) { let lastSyncIdx = hisMaxIdx; while (lastSyncIdx > 0) { const startIdx = Math.max(0, lastSyncIdx - 1000); const {err, rows} = await db.execQuery( 'SELECT * FROM t_withdrawal WHERE idx > ? AND idx <= ? AND state = 0 LIMIT 1000', [startIdx, lastSyncIdx]); if (!err) { this.procHisWithdrawalList(rows); lastSyncIdx = startIdx; if (rows.length <= 0) { continue; } } await this.historyWithdrawalCond.wait(1000 * 1); } log.info('history withdrawal loaded done hisMaxIdx:' + hisMaxIdx); } async newWithdrawal(hisMaxIdx) { let lastSyncIdx = hisMaxIdx; while (true) { const {err, rows} = await db.execQuery( 'SELECT * FROM t_withdrawal WHERE idx > ? AND state = 0 LIMIT 100', [lastSyncIdx]); if (!err) { const maxIdx = this.procNewWithdrawalList(rows); if (maxIdx > lastSyncIdx) { lastSyncIdx = maxIdx; } } await this.newWithdrawalCond.wait(1000 * 3); } } procHisWithdrawalList(rows) { return this.internalProcWithdrawalList(rows, false); } procNewWithdrawalList(rows) { return this.internalProcWithdrawalList(rows, true); } internalProcWithdrawalList(rows, isNewWithdrawal) { let maxIdx = 0; rows.forEach(function (withdrawalDb) { this.addPendingWithdrawal(withdrawalDb, isNewWithdrawal); if (withdrawalDb['idx'] > maxIdx) { maxIdx = withdrawalDb['idx']; } }.bind(this)); return maxIdx; } addPendingWithdrawal(withdrawalDb, isNewWithdrawal) { if (withdrawalDb['idx'] in this.pendingWithdrawalHash) { utils.throwError('idx exists ' + withdrawalDb['idx']); } const a = require("./withdrawal"); const withdrawal = new a.Withdrawal(withdrawalDb, isNewWithdrawal); this.pendingWithdrawalHash[withdrawalDb['idx']] = withdrawal; withdrawal.init(); } removePendingWithdrawal(withdrawalId) { delete this.pendingWithdrawalHash[withdrawalId]; } } module.exports = new TransferMgr();