/
UniswapV2Swapper.sol
65 lines (53 loc) · 1.93 KB
/
UniswapV2Swapper.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.0;
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "./interfaces/ISwapper.sol";
import "@solmate/utils/SafeTransferLib.sol";
/// @title UniswapV2Swapper.
/// @author Morpho Labs.
/// @custom:contact security@morpho.xyz
/// @notice Swapper contract for Uniswap V2 DEXes.
contract UniswapV2Swapper is ISwapper {
using SafeTransferLib for ERC20;
/// STORAGE ///
IUniswapV2Router02 public immutable swapRouter;
address public immutable wrappedNativeToken;
/// CONSTRUCTOR ///
/// @notice Constructs contract.
/// @param _swapRouter The swap router used for swapping assets.
/// @param _wrappedNativeToken The wrapped native token of the given network.
constructor(address _swapRouter, address _wrappedNativeToken) {
swapRouter = IUniswapV2Router02(_swapRouter);
wrappedNativeToken = _wrappedNativeToken;
}
/// EXTERNAL ///
/// @inheritdoc ISwapper
function executeSwap(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
address _recipient
) external returns (uint256 amountOut) {
address[] memory path;
if (_tokenIn == wrappedNativeToken || _tokenOut == wrappedNativeToken) {
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
} else {
path = new address[](3);
path[0] = _tokenIn;
path[1] = wrappedNativeToken;
path[2] = _tokenOut;
}
ERC20(_tokenIn).safeApprove(address(swapRouter), _amountIn);
uint256[] memory amountsOut = swapRouter.swapExactTokensForTokens(
_amountIn,
0,
path,
_recipient,
block.timestamp
);
amountOut = amountsOut[amountsOut.length - 1];
emit Swapped(_tokenIn, _amountIn, _tokenOut, amountOut, _recipient);
}
}