问题描述
我正在通过在Kyber交换合约的.estimateGas()
函数上调用Trade
来估算汽油量。
async getGas(inputToken: TokenInfo,outputToken: TokenInfo,walletAddress: string,amountInWei = Utils.toWei(1),minRate: BN) {
if (amountInWei.lt(toBN(1000))) throw `{${this.name}}.getGas(): The amount ${amountInWei} must be >= 1000.`;
var contract = this.getContract();
let ethValue = inputToken.isETH ? amountInWei: Utils.ZERO_BN;
var tx: ContractSendMethod = contract.methods.Trade(inputToken.contractAddress,amountInWei,outputToken.contractAddress,walletAddress,MAX_ALLOWANCE,minRate,Utils.ZERO_ADDRESS); //Utils.getWalletAddress()
debugger;
var gas = await tx.estimateGas({ from: walletAddress,gas: 10000000000,value: ethValue }); // FAILS HERE
debugger;
return toBN(gas);
}
我尝试了estimateGas()
,不带参数,但带参数(如上所示)。然后,我在文档中发现您可能必须先致电ERC20合同上的approve
,所以我也做了(摘自文档并进行修改以适合):
async checkAndApprovetokenForTrade(srcToken: TokenInfo,userAddress: string,srcQty: BN) {
if (!srcToken.abi || srcToken.contractAddress == Tokens.ETH.contractAddress)
return;
// check existing allowance given to proxy contract
var srcTokenContract = srcToken.contract;
let existingallowance = toBN(await srcTokenContract.methods.allowance(userAddress,KyberExchange.KYBER_RATE_ADDRESS/*IKyberNetworkProxy_ADDRESS*/).call());
// if zero allowance,just set to MAX_UINT256
if (existingallowance.eq(Utils.ZERO_BN)) {
console.log("Approving KNP contract to max allowance.");
var result = await srcTokenContract.methods.approve(KyberExchange.KYBER_RATE_ADDRESS,srcQty).call();
} else if (existingallowance.lt(srcQty)) {
// if existing allowance is insufficient,reset to zero,then set to MAX_UINT256
console.log("Approving KNP contract to zero,then max allowance.");
result = await srcTokenContract.methods.approve(KyberExchange.KYBER_RATE_ADDRESS,Utils.ZERO_BN).call();
result = await srcTokenContract.methods.approve(KyberExchange.KYBER_RATE_ADDRESS,srcQty).call();
}
}
async getGas(inputToken: TokenInfo,minRate: BN) {
if (amountInWei.lt(toBN(1000))) throw `{${this.name}}.getGas(): The amount ${amountInWei} must be >= 1000.`;
await this.checkAndApprovetokenForTrade(inputToken,amountInWei);
var contract = this.getContract();
let ethValue = inputToken.isETH ? amountInWei: Utils.ZERO_BN;
var tx: ContractSendMethod = contract.methods.Trade(inputToken.contractAddress,Utils.ZERO_ADDRESS); //Utils.getWalletAddress()
var gas = await tx.estimateGas({ from: walletAddress,value: ethValue }); // STILL FAILS
return toBN(gas);
}
我不断收到“返回的错误:所需的气体超出限额(123965250)或交易始终失败。”。我已经没办法解决这个问题了。我希望该错误能够更准确地说明问题所在。我在想函数本身很可能引发错误,但不知道是什么或为什么。我可以打电话给交换合约以获取汇率,因此系统的其余部分都可以正常工作,而不仅仅是估算天然气的部分。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)