> For the complete documentation index, see [llms.txt](https://affection.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://affection.gitbook.io/docs/bots-and-scripts/core-functions/swap_tokens.md).

# swap\_tokens

## Function

```python
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


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://affection.gitbook.io/docs/bots-and-scripts/core-functions/swap_tokens.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
