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
| // SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Callee.sol'; import './interfaces/IUniswapV2Pair.sol'; import './interfaces/IERC20.sol';
contract ExampleFlashSwap is IUniswapV2Callee {
//以下变量修改你部署合约地址 address private constant WETH = 0xc5697643c5d76F7ea252eF911171d9cbbEe359ec; address private constant USDT = 0xccCDC0B397B2D6fb3717C13738f8865AaC5A2B9C; address private constant MYTOKEN = 0x7241CBC94A6f76D6eFF7fea6Fd141284338F8e46; address private constant PAIR = 0xfb85b7DedCFcea3f4fe6894931c0fA75A1ef7844; address private constant FACTORY = 0xd7330EdCd8665C0369606d2B07E13EBE1f4319c7;
event Log(string message, uint256 val); //借100USDT function loanFlashSwap(address _usdtBorrow, uint256 _amount) external {
address token0 = IUniswapV2Pair(PAIR).token0(); address token1 = IUniswapV2Pair(PAIR).token1(); uint256 amount0Out = _usdtBorrow == token0 ? _amount : 0; uint256 amount1Out = _usdtBorrow == token1 ? _amount : 0; bytes memory data = abi.encode(_usdtBorrow, _amount);
IUniswapV2Pair(PAIR).swap(amount0Out, amount1Out, address(this), data);
}
function uniswapV2Call(address _sender, uint _amount0, uint _amount1, bytes calldata _data ) external override { address token0 = IUniswapV2Pair(msg.sender).token0(); address token1 = IUniswapV2Pair(msg.sender).token1(); address pair = IUniswapV2Factory(FACTORY).getPair(token0, token1); require(msg.sender == pair, "!pair"); require(_sender == address(this), "!sender");
(address usdtBorrow, uint amount) = abi.decode(_data, (address, uint)); // 加上利息 0.3% uint fee = ((amount * 3) / 997) + 1; uint amountToRepay = amount + fee;
//执行我们的业务逻辑 emit Log("amount", amount); emit Log("amount0", _amount0); emit Log("amount1", _amount1); emit Log("fee", fee); emit Log("amount to repay", amountToRepay); //把借来的Token还回去 IERC20(usdtBorrow).transfer(pair, amountToRepay); }
receive() external payable {} }
|