共计 2084 个字符,预计需要花费 6 分钟才能阅读完成。
Uniswap 是去中心化的,不仅跟传统的加密货币交易所不同,也跟一般的去中心化代币交易所不同。Uniswap 是一组部署到以太坊网络的合约,所有的交易都在链上进行。
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,dapp 流动性质押挖矿零碎开发卫星:hkkf5566
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = UniswapV2Library.pairFor(factory, token, WETH);
// 把 coin 从合约调用者账户转到币对
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
// 把发送的 eth 兑换成 WETH 到 swap 合约
IWETH(WETH).deposit{value: amountETH}();
//swap 合约把上一步兑换的 weth 充值到币对
assert(IWETH(WETH).transfer(pair, amountETH));
// 增加流动性
liquidity = IUniswapV2Pair(pair).mint(to);
// 把发送的多于的 eth 发回给调用者
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
首先应用修改器做了一次工夫戳校验,传入的工夫戳必须大于以后区块的工夫戳。
modifier ensure(uint deadline) {require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
_;
}
而后调用了_addLiquidity
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA, //yp
address tokenB, // Weth
uint amountADesired, //yp amount
uint amountBDesired, // msg.value
uint amountAMin, // 滑点后
uint amountBMin // 滑点后
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
// 创立币对
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
//
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {(amountA, amountB) = (amountADesired, amountBDesired);
} else {uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
// 计算出来的 weth 数量小于发送的 eth 数量
if (amountBOptimal <= amountBDesired) {require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else { // 大于。uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
正文完