71 lines
1.8 KiB
JavaScript
71 lines
1.8 KiB
JavaScript
const util = require('util');
|
|
const Web3 = require('web3');
|
|
const utils = require('j7/utils');
|
|
const event = require('j7/event');
|
|
const sync = require("j7/sync");
|
|
const log = require("j7/log");
|
|
const metaFactory = require('./metadata/factory');
|
|
const constant = require("./constant");
|
|
|
|
class BlockChain {
|
|
|
|
constructor() {
|
|
this.currBlockNumber = 0;
|
|
this.refreshCond = new sync.Cond();
|
|
this.lastRefreshTime = utils.getUtcTime();
|
|
this.actived = false;
|
|
}
|
|
|
|
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(metaFactory.getWeb3Conf()['block_server']);
|
|
this.web3.eth.accounts.wallet.add(metaFactory.getPrivateKey());
|
|
for (const data of metaFactory.getContracts()) {
|
|
this[`${data.name}Instance`] = await this.initInstance
|
|
(metaFactory.getUserAddress(), data.address, data.json);
|
|
}
|
|
setTimeout(this.refreshBlockNumber.bind(this), 1000 * 0.01);
|
|
await this.mustBeActive();
|
|
event.emitEvent(constant.BC_INITIALIZED_EVENT);
|
|
}
|
|
|
|
async mustBeActive() {
|
|
while (!this.actived) {
|
|
await utils.sleep(1000);
|
|
}
|
|
}
|
|
|
|
async refreshBlockNumber() {
|
|
const logClass = 'refreshBlockNumber';
|
|
while (true) {
|
|
try {
|
|
this.currBlockNumber = await this.web3.eth.getBlockNumber();
|
|
this.actived = true;
|
|
this.lastRefreshTime = utils.getUtcTime();
|
|
} catch (e) {
|
|
this.actived = false;
|
|
log.warning(util.format('%s err:%s',
|
|
logClass,
|
|
e
|
|
));
|
|
}
|
|
await this.refreshCond.wait(1000 * 3);
|
|
}
|
|
}
|
|
|
|
getCurrBlockNumber() {
|
|
return this.currBlockNumber;
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = new BlockChain();
|