基础知识点
pancake和uniswap类似,想要实现flash swap需要创建一个类似uniswapV2Call
的函数,你可以在这个找到
https://docs.uniswap.org/protocol/V2/guides/smart-contract-integration/using-flash-swaps
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) {
address token0 = IUniswapV2Pair(msg.sender).token0(); // fetch the address of token0
address token1 = IUniswapV2Pair(msg.sender).token1(); // fetch the address of token1
assert(msg.sender == IUniswapV2Factory(factoryV2).getPair(token0, token1)); // ensure that msg.sender is a V2 pair
// rest of the function goes here!
}
例子
这里引用@Fankouzu
老师的视频作为例子。下面代码展示借USDT
,换ETH
的过程,当然也可以还USDT
。
下面代码内部是USDT
转换为USDC
,USDC
再转化为WETH
function uniswapV2Call(address account,uint256 amount0,uint256 amount1,bytes memory data) public{
uint256 balance = IERC20(USDT).balanceOf(address(this));
emit Balance(balance);
address[] memory path1 = new address[](2);
path1[0] = USDT;
path1[1] = USDC;
uint[] memory amounts1 = uniRouter(router).swapExactTokensForTokens(balance,uint(0),path1,address(this),block.timestamp+1800);
emit Balance(amounts1[1]);
address[] memory path2 = new address[](2);
path2[0] = USDC;
path2[1] = WETH;
uint[] memory amounts2 = uniRouter(router).swapExactTokensForTokens(amounts1[1],uint(0),path2,address(this),block.timestamp+1800);
emit Balance(amounts2[1]);
address[] memory path3 = new address[](2);
path3[0] = WETH;
path3[1] = USDT;
uint[] memory amounts3 = uniRouter(router).getAmountsIn(loanAmount,path3);
emit Balance(amounts3[0]);
IERC20(WETH).transfer(USDTETH,amounts3[0]);
emit Balance(ETHAmount - amounts3[0]);
}
function swap(uint256 _loanAmount) public {
loanAmount = _loanAmount;
pair(USDTETH).swap(uint(0),_loanAmount,address(this),_data);
}
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
如何套利
参考这个文章币圈科学家系列:套利