def _estimate_gas(self, token_amount: TokenAmount, account: Account,
                   transaction_params: dict, **kw):
     latest_block = self.w3.eth.getBlock("latest")
     deadline = latest_block.timestamp + WEB3_TIMEOUT
     return estimate_gas(
         self.w3,
         account,
         self.router_proxy.functions.swapETHForExactTokens,
         token_amount.as_wei,
         [self.weth_address, token_amount.address],
         account.address,
         deadline,
         **transaction_params,
     )
    def _estimate_gas(self, token_amount: TokenAmount, account: Account,
                      transaction_params: dict, **kw):
        exchange_rate = kw.get("exchange_rate")
        if exchange_rate is None:
            raise ExchangeError(
                f"An exchange rate is needed to estimate gas for a swap on {self.name}"
            )

        eth_address = self.get_token_network_address(TokenTicker("ETH"))
        return estimate_gas(
            self.w3,
            account,
            self.network_contract_proxy.functions.trade,
            eth_address,
            transaction_params["value"],
            self.get_token_network_address(token_amount.ticker),
            account.address,
            token_amount.as_wei,
            exchange_rate.as_wei,
            account.address,
            **transaction_params,
        )
Example #3
0
    def _calculate_transaction_costs(self, token_amount: TokenAmount,
                                     account: Account) -> dict:
        exchange_rate = self.get_current_rate(token_amount)
        eth_sold = EthereumAmount(token_amount.value * exchange_rate.value)
        gas_price = EthereumAmount(Wei(self.w3.eth.generateGasPrice()))
        exchange_proxy = self._get_exchange_proxy(token_amount.ticker)
        latest_block = self.w3.eth.getBlock("latest")
        deadline = latest_block.timestamp + self.EXCHANGE_TIMEOUT
        transaction_params = {
            "from": account.address,
            "value": eth_sold.as_wei,
            "gasPrice": gas_price.as_wei,
        }

        gas = estimate_gas(
            self.w3,
            account,
            exchange_proxy.functions.ethToTokenSwapOutput,
            token_amount.as_wei,
            deadline,
            **transaction_params,
        )

        max_gas_limit = Wei(int(latest_block["gasLimit"] * 0.9))
        gas_with_margin = Wei(int(gas * GAS_LIMIT_MARGIN))
        gas = min(gas_with_margin, max_gas_limit)
        gas_cost = EthereumAmount(Wei(gas * gas_price.as_wei))
        total = EthereumAmount(gas_cost.value + eth_sold.value)
        log.debug("transaction cost",
                  gas_price=gas_price,
                  gas=gas,
                  eth=eth_sold)
        return {
            "gas_price": gas_price,
            "gas": gas,
            "eth_sold": eth_sold,
            "total": total,
            "exchange_rate": exchange_rate,
        }