我试图通过调用Kyber 交换合约.estimateGas()
的功能来估算 gas。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()
不带参数和带(如上所示)。然后我在文档中发现您可能必须先调用approve
ERC20 合约,所以我也这样做了(取自文档并修改为适合):
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, 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.`;
await this.checkAndApproveTokenForTrade(inputToken, walletAddress, amountInWei);
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()
var gas = await tx.estimateGas({ from: walletAddress, gas: 10000000000, value: ethValue }); // STILL FAILS
return toBN(gas);
}
- 1 - BN = "34950159783737063"
- 5 - BN = "2762660877769768"
我不断收到“返回错误:所需气体超过限额 (123965250) 或交易总是失败。”。我已经没有办法解决这个问题了。我希望该错误能够更准确地描述问题所在。我认为函数本身很可能会引发错误,但不知道是什么或为什么。我可以调用交换合约来获取汇率,所以系统的其余部分都在工作,而不是估计气体的部分。