aozhiwei bef75d006f 1
2023-06-17 15:35:13 +08:00

114 lines
2.7 KiB
JavaScript

const util = require('util');
const Web3 = require('web3');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const event = require('j7/event');
const sync = require("j7/sync");
const log = require("j7/log");
const contract = require('common/contract');
const metaFactory = require('./metadata/factory');
class BlockChain {
constructor(netId) {
this.netId = netId;
}
async initInstance(user, address, jsonUrl) {
const json = utils.readJsonFromFile(jsonUrl);
return new this.web3.eth.Contract(
json.abi,
address,
{ from: user }
);
}
async init() {
this.web3Conf = metaFactory.getWeb3Conf(this.netId);
this.contractsConf = metaFactory.getContractsConf(this.netId);
this.netDir = metaFactory.getNetDir(this.netId);
this.web3 = new Web3(this.getRpcUrl());
this.web3.eth.handleRevert = true;
this.web3.eth.accounts.wallet.add(this.getPrivateKey());
for (const data of this.contractsConf) {
this[`${data.name}Instance`] = await this.initInstance
(this.getUserAddress(), data.address, this.netDir + data.json);
}
const chainId = await this.web3.eth.getChainId();
if (chainId != this.netId) {
log.warning(util.format('net id error %s %s',
chainId,
this.netId
));
}
log.info(util.format('local.net_id:%s remote_net_id:%s',
this.netId,
chainId
));
}
getNetId() {
return this.netId;
}
getRpcUrl() {
return this.web3Conf['block_server'];
}
getUserAddress() {
return this.web3Conf['user_address'];
}
getPrivateKey() {
return this.web3Conf['private_key'];
}
getContractByName(name) {
let contract = null;
this.contractsConf.forEach((item) => {
if (item['name'] == name) {
contract = item;
}
});
return contract;
}
getNftAddress(tokenType) {
switch (Number(tokenType)) {
case bcutils.HERO_TYPE:
{
return this.getContractByName('HERO')['address'];
}
break;
case bcutils.EQUIP_TYPE:
{
return this.getContractByName('WEAPON')['address'];
}
break;
case bcutils.CHIP_TYPE:
{
return this.getContractByName('CHIP')['address'];
}
break;
case bcutils.FRAGMENT_TYPE:
{
return this.getContractByName('shard')['address'];
}
break;
case bcutils.CLAIM_BOX_TYPE:
{
return this.getContractByName('Gacha')['address'];
}
break;
default:
{
return '';
}
}
}
}
module.exports = BlockChain;