aozhiwei 355083fd2f 1
2022-01-26 16:40:34 +08:00

94 lines
2.7 KiB
JavaScript

const util = require('util');
const Web3 = require('web3');
const metamgr = require('./metamgr');
const utils = require('./utils');
const sync = require("./sync");
const log = require("./log");
const C = require("./C");
class BlockChain {
constructor() {
this.currBlockNumber = 0;
this.refreshBlockNumberCond = new sync.Cond();
this.lastRefreshBlockNumberTime = utils.getUtcTime();
this.deltaNumber = BigInt(0);
}
async initInstance(user, address, jsonUrl) {
const json = utils.readJsonFromFile(jsonUrl);
return new this.web3.eth.Contract(
json.abi,
address,
{ from: user }
);
}
async init() {
this.web3 = new Web3(metamgr.getServerConf()['block_server']);
const userAddress = metamgr.getServerConf()['user_address'];
const userBuyAddress = metamgr.getServerConf()['user_buy_address'];
for (const data of metamgr.getContracts()) {
this[`${data.name}Instance`] = await this.initInstance(userAddress, data.address, data.json);
}
for (const data of metamgr.getContracts()) {
this[`${data.name}InstanceBuy`] = await this.initInstance(userBuyAddress, data.address, data.json);
}
setTimeout(this.refreshBlockNumber.bind(this), 1000 * 0.01);
setInterval(this.outputCurrBlockNumber.bind(this), 1000 * 10);
utils.emitEvent(C.BC_INITIALIZED_EVENT);
}
async refreshBlockNumber() {
const logClass = 'refreshBlockNumber';
while (true) {
try {
this.currBlockNumber = await this.web3.eth.getBlockNumber();
if (!utils.isOnlineEnv()) {
this.deltaNumber += BigInt(3);
if (this.deltaNumber > 30) {
this.deltaNumber = BigInt(0);
}
this.currBlockNumber = BigInt(this.getCurrBlockNumber()) + this.deltaNumber;
}
this.lastRefreshBlockNumberTime = utils.getUtcTime();
} catch (e) {
log.warning(util.format('%s err:%s', {
logClass,
e
}));
}
await this.refreshBlockNumberCond.wait(1000 * 3);
}
}
isComfirmed(blockNumber) {
const logClass = 'isComfirmed';
try {
return BigInt(blockNumber) + BigInt(6) < BigInt(this.getCurrBlockNumber());
} catch (e) {
log.warning(util.format('%s err:%s',
logClass,
e
));
}
return false;
}
getCurrBlockNumber() {
return this.currBlockNumber;
}
outputCurrBlockNumber() {
const logClass = 'outputCurrBlockNumber';
log.info(util.format('%s currBlockNumber:%s',
logClass,
this.getCurrBlockNumber()
));
}
}
module.exports = new BlockChain();