Version: V2

# 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

The easiest way to safely swap tokens is to use the router, 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.

Check out the Pricing page for a more in depth discussion on getting prices.

# Example

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

## transferFrom​

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​

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​

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