m-tronweb
Version:
one node failure will use another node
104 lines (96 loc) • 2.17 kB
JavaScript
const TronWeb=require('tronweb');
let txArg={
feeLimit:1000*1e6
};
/*
* 1.the name of the node
* 2.the config
* 3.the private key's key
*/
function MTronWeb(config,names,pkKey){
this.tronWebMap=this.init(config,names,pkKey);
this.nodeNames=names;
this.nodeInsMap={};
}
/*
* 初始化
*/
MTronWeb.prototype.init=function(config,names,pkKey){
let tWMap={};
if(pkKey=='event'){
pkKey=pkKey+"_pk";
}else{
pkKey="operator"+pkKey+"_pk";
}
for(let i=0;i<names.length;i++){
let name=names[i];
let tronWeb = new TronWeb(
config[name+"_full"],
config[name+"_solidity"],
config[name+"_event"],
config[pkKey],
);
tWMap[names[i]]=tronWeb;
}
return tWMap;
}
/*
* 1.name of node,ins
* 2.using the node from the begining
*/
MTronWeb.prototype.query=async function(contractAddr,funcName,args){
let ins;
let rs;
for(let i=0;i<this.nodeNames.length;i++){
try{
ins=await this.getContractIns(this.nodeNames[i],contractAddr);
rs=await ins.methods[funcName](...args).call();
}catch(e){
console.log(this.nodeNames[i]+" 异常,跳过");
continue;
}
}
return rs;
}
/*
* 只是执行一次,对于比如转钱这种,我们无法接受一直去执行
* 执行完毕,返回交易ID
*/
MTronWeb.prototype.execute=async function(contractAddr,funcName,args){
let ins;
let txId;
for(let i=0;i<this.nodeNames.length;i++){
try{
ins=await this.getContractIns(this.nodeNames[i],contractAddr);
console.log(ins);
console.log(ins.methods[funcName]);
console.log(ins.methods[funcName](...args));
txId=await ins.methods[funcName](...args).send(txArg);
}catch(e){
console.log(e);
console.log(this.nodeNames[i]+" 异常,跳过");
}
}
return txId;
}
/*
* 1.nodeName already install
*/
MTronWeb.prototype.getContractIns=async function(nodeName,contractAddr){
let insMap=this.nodeInsMap[nodeName];
let ins;
if(insMap){
ins=insMap[contractAddr];
if(ins){
return ins;
}
}else{
insMap={};
}
let tronweb=this.tronWebMap[nodeName];
ins=await tronweb.contract().at(contractAddr);
insMap[contractAddr]=ins;
this.nodeInsMap[nodeName]=insMap;
return ins;
}
module.exports=MTronWeb;