estimate_swap_result

Function

def estimate_swap_result(router_name, token0_address, token1_address, token0_amount, attempts=18):
    routers = json.load(open('./data/routers.json'))
    router_contract = load_contract(routers[router_name][0], routers[router_name][1])
    token0_info = get_token_info(token0_address)
    while attempts > 0:
        try:
            expected_output_amounts = router_contract.functions.getAmountsOut(
                int(token0_amount * 10 ** token0_info['decimals']),
                [token0_address, token1_address]
            ).call()
        except Exception as e:
            logging.debug(e)
            attempts -= 1
            time.sleep(1)
        else:
            return expected_output_amounts
    return []

Description

  • Load a list of DEX routers

  • Load the router contract by name

  • Get the info for token0 to convert the amount to decimals

  • Set max attempts

  • Try to get the estimated swap result by calling getAmountsOut for the router

  • Return the expected output amounts or an empty list if no attempts remaining