# Implement a Swap

When trading from a smart contract, the most important thing to keep in mind is that access to an external price source is *required*. Without this, trades can be frontrun for considerable loss.

## Using the Router <a href="#using-the-router" id="using-the-router"></a>

The easiest way to safely swap tokens is to use the route&#x72;*,* which provides a variety of methods to safely swap to and from different assets. You’ll notice that there is a function for each permutation of swapping to/from an exact amount of ETH/tokens.

First you must use an external price source to calculate the safety parameters for the function you’d like to call. This is either a minimum amount received when selling an exact input or the maximum amount you are willing to pay when a buying an exact output amount

It is also important to ensure that your contract controls enough ETH/tokens to make the swap, and has granted approval to the router to withdraw this many tokens.

## Example <a href="#example" id="example"></a>

Imagine you want to swap 50 DAI for as much ETH as possible from your smart contract.

### transferFrom <a href="#transferfrom" id="transferfrom"></a>

Before swapping, our smart contracts needs to be in control of 50 DAI. The easiest way to accomplish this is by calling `transferFrom` on DAI with the owner set to `msg.sender`:

```
uint amountIn = 50 * 10 ** DAI.decimals();
require(DAI.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');
```

### approve <a href="#approve" id="approve"></a>

Now that our contract owns 50 DAI, we need to approve to the router to withdraw this DAI:

```
require(DAI.approve(address(UniswapV2Router02), amountIn), 'approve failed.');
```

### swapExactTokensForETH <a href="#swapexacttokensforeth" id="swapexacttokensforeth"></a>

Now we’re ready to swap:

```
// amountOutMin must be retrieved from an oracle of some kind
address[] memory path = new address[](2);
path[0] = address(DAI);
path[1] = UniswapV2Router02.WETH();
UniswapV2Router02.swapExactTokensForETH(amountIn, amountOutMin, path, msg.sender, block.timestamp);
```

## Safety Considerations <a href="#safety-considerations" id="safety-considerations"></a>

Because Ethereum transactions occur in an adversarial environment, smart contracts that do not perform safety checks *can be exploited for profit*. If a smart contract assumes that the current price on Swipeswap is a “fair” price without performing safety checks, *it is vulnerable to manipulation*. A bad actor could e.g. easily insert transactions before and after the swap (a “sandwich” attack) causing the smart contract to trade at a much worse price, profit from this at the trader’s expense, and then return the contracts to their original state. (One important caveat is that these types of attacks are mitigated by trading in extremely liquid pools, and/or at low values.)

The best way to protect against these attacks is to use an external price feed or “price oracle”. The best “oracle” is simply *traders’ off-chain observation of the current price*, which can be passed into the trade as a safety check. This strategy is best for situations *where users initiate trades on their own behalf*.

However, when an off-chain price can’t be used, an on-chain oracle should be used instead. Determining the best oracle for a given situation is a not part of this guide, but for more details on the Swipeswap approach to oracles.


---

# Agent Instructions: 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://docs.swipe.org/swap/smart-contract/implement-a-swap.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.
