swap_tokens
Function
def swap_tokens(account, router_name, token_route, estimated_swap_result, slippage_percent, taxed=False, attempts=18):
routers = json.load(open('./data/routers.json'))
router_contract = load_contract(routers[router_name][0], routers[router_name][1])
approve_token_spending(account, token_route[0], routers[router_name][0], estimated_swap_result[0])
if token_route[-1] == "0xA1077a294dDE1B09bB078844df40758a5D0f9a27":
tx = router_contract.functions.swapExactTokensForETH(
estimated_swap_result[0],
estimated_swap_result[1] - round(estimated_swap_result[1] * (slippage_percent / 100)),
token_route,
account.address,
int(time.time()) + (60 * 3)
)
tx_params = {
"from": account.address,
"nonce": get_nonce(account.address)
}
elif token_route[0] == "0xA1077a294dDE1B09bB078844df40758a5D0f9a27":
if taxed:
swap_function = router_contract.functions.swapExactETHForTokensSupportingFeeOnTransferTokens
else:
swap_function = router_contract.functions.swapExactETHForTokens
tx = swap_function(
0,
token_route,
account.address,
int(time.time()) + (60 * 3)
)
tx_params = {
"from": account.address,
"nonce": get_nonce(account.address),
"value": estimated_swap_result[0]
}
else:
if taxed:
swap_function = router_contract.functions.swapExactTokensForETHSupportingFeeOnTransferTokens
else:
swap_function = router_contract.functions.swapExactTokensForETH
tx = swap_function(
estimated_swap_result[0],
estimated_swap_result[1] - (estimated_swap_result[1] * slippage_percent),
token_route,
account.address,
int(time.time()) + (60 * 3)
)
tx_params = {
"from": account.address,
"nonce": get_nonce(account.address)
}
try:
tx = tx.build_transaction(tx_params)
return broadcast_transaction(account, tx, True, attempts)
except Exception as e:
if error := interpret_exception_message(e):
logging.error("{}. Failed to swap".format(error))
return False
Description
Load a list of routers
Load the router by name
Approve tokens for swapping
Determine which Uniswap v2 swap function to use
Create a transaction to swap token0 to token1 with an expiry time of 3 minutes
Broadcast and return True/False