유니스왑 v2의 코드를 이전 포스팅에서 본 유니스왑 백서에 기반하여 분석해보자
유니스왑 깃허브에 들어가면 유니스왑 코드를 확인 할 수 있다.
유니스왑 깃허브를 들어가면 다음과 같은 폴더와 파일이 나온다.

여기서 봐야할 것은 UniswapV2Factory.sol, UniswapV2Pair.sol 두가지이다.
pragma solidity =0.5.16;
import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';
contract UniswapV2Factory is IUniswapV2Factory {
//토큰 컨트렉트에서 거래되는 fee의 일부(0.05%)
address public feeTo;
address public feeToSetter;
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor(address _feeToSetter) public {
feeToSetter = _feeToSetter;
}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
// 새로운 페어를 만들기 위한 메소드
function createPair(address tokenA, address tokenB) external returns (address pair) {
// 서로 다른 두 토큰을 인자로 받아온다.
// TokenA 와 TokenB가 다른 주소를 가진 경우에만 실행
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
// 토큰의 크기를 비교
// 토큰의 주소로 토큰 pair의 순서를 정한다.
// ex) WETC (0x2260....) 과 WETH (0xC02....) 의 주소를 비교하면 첫 자리가 2인 WETC보다 첫자리가 16진수 C (12) 가 크므로 WETC-WETH Pair가 결정된다.
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
//주소가 0인 컨트렉트는 존재하지 않으므로 token0 가 0인지 아닌지 검사
//token1은 무조건 Token0보다 크므로 token0에 대해서만 검사한다.
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
// 두 token Pair에 해당하는 컨트렉트가 이미 존재하는지 검사
// getPair : Token Pair를 관리하는 자료구조를 담고있는 변수
// token0과 token1를 넣었을 때 0인 주소가 나오면 이미 생성되어있는 컨트렉트
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
//UniswapV2Pair.sol의 코드를 byte코드로 가져옴.
bytes memory bytecode = type(UniswapV2Pair).creationCode;
//token0, token1의 abi를 keccak256 함수를 사용해서 salt 생성.
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
// 어셈블리어
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
// 초기화
IUniswapV2Pair(pair).initialize(token0, token1);
// 각 조합에 대해서 주소를 넣어줌.
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
//컨트렉트가 생성되면 로그에 기록
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeTo = _feeTo;
}
function setFeeToSetter(address _feeToSetter) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2Pair.sol';
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
// 현재 컨트렉트 (UniswapV2Pair)를 배포한 컨트렉트 = UniswapV2Factory 컨트렉트이므로
// factory의 msg.sender를 통해 컨트렉트를 생성한 주소를 넣어줌
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// 컨트렉트의 잔고가 얼마인지 확인하고 token pool에 token이 얼마나 들어왔는지 확인하고 정보 업데이트
// 현재 컨트렉트의 잔고보다 token0, token1에서 확인한 잔고가 더 많으면
// 돈을 받았다는 것을 확인 할 수 있게 됨.
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// uniwap을 price oracle로 쓰기위한 로직
// 현재가격 : 각각의 price들이 유지된 시간의 가중치를 더해 평균을 낸 값.
//price0CumulativeLast, price0CumulativeLast는 public으로 다른 컨트렉트에서 가격을 확인 할 수 있다.
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price0CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// 프로토콜 Fee를 구하는 메소드
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// LP Token을 만드는 메소드
// mint를 하는 기준 : 현재 컨트렉트가 기록하고있는 자산의 양 < token0, token1에 기록된 자산이 많으면 mint
// 적으면 burn을 해야함.
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
/// mint를 하기위해 balanceOf로 잔고를 받아옴.
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
// 받은 잔고 = 기록되어있는 잔고 - balanceOf로 확인한 잔고
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
// 수수료 계산
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
// _totalSupply == 0 : 처음 컨트렉트에 Pair를 넣은 사람
// pair가 처음됐을땐 LP token의 1000배를 burn해야한다.
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
// 0번 주소에 MINIMUM_LIQUIDITY생성
// 0번 주소는 소유자가 없으므로 즉 burn이 된다.
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
// 처음 pair하는 경우가 아니면 인플레이션을 한다.
// _reserve0, _reserve1를 계산했을 때 작은 값이 liquidity가 된다.
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
// to : 돈을 넣은 주소에게
// liquidity :LP token을 share한다.
_mint(to, liquidity);
// 잔고를 업데이트 해준다.
_update(balance0, balance1, _reserve0, _reserve1);
// K = 두 토큰(reserve0, reserve1)의 곱
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
// 로그 남기기.
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
// 각 토큰에 대해 잔고 정보를 받아옴.
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
// liquidity의 비율에 해당하는 각각의 토큰의 amount0(1) 만큼을 태우게 됨.
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
// 전송
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
// 잔고 업데이트
_update(balance0, balance1, _reserve0, _reserve1);
// K 값 계산
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
// 로그 기록
emit Burn(msg.sender, amount0, amount1, to);
}
// 토큰을 교환 하는 함수
// amount0Out, amount1Out : out이 2개 있는 이유
// 암호화폐 대출서비스 (Aava, Compound)에서 빌린 토큰을 Swap하면서 만든 차액을 반납하는 경우를 대비해서 탄생
// 즉, 유니스왑을 할 때 한 토큰만을 집어넣지 않을 수도 있다.
// in 하는 시점 : swap함수가 실행되기 전에 pair컨트렉트의 교환하고자 하는 주소에 토큰을 먼저 넣고 swap 함수를 실행.
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
// amount0Out, amount0Out 0보다 작으면 입금액이 부족함으로 수행하지 않음.
require(amount0Out > 0 || amount0Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
// _token0,_token0를 amount0Out,amount1Out 만큼 전송함.
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token0, to, amount1Out); // optimistically transfer tokens
//uniswapV2Call : 유니스왑을 실행하고나서 다른 행동을 하고싶은 경우 data가 0보다 크면 data를 인자로 받아서 함수 호출.
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
//돈을 넣었는지 잔고 확인.
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
// balance 조정.
// balance가 보낼수 있는 양보다 작으면 0을 대입.
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
// amount0Out, amount0Out 0보다 작으면 입금액이 부족함으로 수행하지 않음.
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{
// 수수료 (0.3%)를 낼 수 있는지 확인.
// scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
// 잔고 업데이트.
_update(balance0, balance1, _reserve0, _reserve1);
// 로그 기록.
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// 입금된 토큰이 pair 컨트렉트에 담을 수 있는 토큰의 양을 넘으면 남은 여유분을 회수하는 메소드
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// 토큰간 imbalance가 생겼을때 맞춰주기 위한 메소드
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}