70 lines
1.9 KiB
JavaScript
70 lines
1.9 KiB
JavaScript
const util = require('util');
|
|
const Web3 = require('web3');
|
|
const utils = require('j7/utils');
|
|
const event = require('j7/event');
|
|
const metaFactory = require('./metadata/factory');
|
|
const constant = require("./constant");
|
|
const { ERC20ABI } = require("./ERC20ABI");
|
|
|
|
class BlockChain {
|
|
|
|
constructor() {
|
|
this.netId = 0;
|
|
this.coinInstanceHash = {};
|
|
}
|
|
|
|
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.handleRevert = true;
|
|
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);
|
|
}
|
|
event.emitEvent(constant.BC_INITIALIZED_EVENT);
|
|
}
|
|
|
|
async getNetId() {
|
|
return await this.web3.eth.getChainId();
|
|
}
|
|
|
|
async getCoinInstance(address) {
|
|
if (this.coinInstanceHash[address]) {
|
|
return this.coinInstanceHash[address];
|
|
}
|
|
const instance = new this.web3.eth.Contract(
|
|
ERC20ABI,
|
|
address,
|
|
{
|
|
from: metaFactory.getUserAddress()
|
|
}
|
|
);
|
|
this.coinInstanceHash[address] = instance;
|
|
return instance;
|
|
}
|
|
|
|
async increaseAllowance(address, price) {
|
|
const coinInstance = await this.getCoinInstance(address);
|
|
const mallAddress = metaFactory.getContractByName('mall')['address'];
|
|
const res = await coinInstance.methods.increaseAllowance(mallAddress, price).send({ gas: 1000000 });
|
|
console.log('increaseAllowance', res);
|
|
}
|
|
|
|
async getBalance(address) {
|
|
const coinInstance = await this.getCoinInstance(address);
|
|
return await coinInstance.methods.balanceOf(metaFactory.getUserAddress()).call();
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = new BlockChain();
|