Проверенный контрактЧастичноеMIT
SwapX
Адрес0x5ce741a6e8307c8b11f2d27a75df0844f06bfef1
- Баланс
0 ETH
- Транзакций
47 143
- Компилятор
solc 0.8.28
- Тот же код
ещё 1 контракт
Подробности
- Компилятор
- solc 0.8.28+commit.7893614a
- Язык
- solidity
- Оптимизация
- Да, 10 прогонов
- Версия EVM
- prague
- Через IR
- да
- Лицензия
- MIT
- Совпадение
- Частичноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 24 904 975
- Транзакция создания
- 0x1f71b7ae40…5aa4c1752b
- Библиотеки
- contracts/SwapX.sol:OkxLib0x4204…19c7c4contracts/SwapX.sol:UniV2Lib0xc514…350968contracts/SwapX.sol:UniV3Lib0x9296…e4ccadcontracts/SwapX.sol:UniV4Lib0x04b2…ddfee0
40 файлов
- contracts/SwapX.solглавный45,89 КБ
- contracts/Storage.sol413 Б
- contracts/contracts-upgradeable/access/OwnableUpgradeable.sol3,57 КБ
- contracts/contracts-upgradeable/interfaces/IERC1271Upgradeable.sol648 Б
- contracts/contracts-upgradeable/proxy/utils/Initializable.sol8,28 КБ
- contracts/contracts-upgradeable/security/PausableUpgradeable.sol3,38 КБ
- contracts/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol3,78 КБ
- contracts/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol2,79 КБ
- contracts/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol2,22 КБ
- contracts/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol6,6 КБ
- contracts/contracts-upgradeable/utils/AddressUpgradeable.sol6,27 КБ
- contracts/contracts-upgradeable/utils/ContextUpgradeable.sol1,34 КБ
- contracts/extLib/Constants.sol1,87 КБ
- contracts/extLib/OkxLib.sol9,22 КБ
- contracts/extLib/UniV2Lib.sol5,47 КБ
- contracts/extLib/UniV3Lib.sol2,99 КБ
- contracts/extLib/UniV4Lib.sol10,26 КБ
- contracts/extLib/common.sol4,45 КБ
- contracts/extLib/constants.sol1,87 КБ
- contracts/interfaces/IFourTokenManager.sol796 Б
- contracts/interfaces/IOKXDexRouter.sol2,78 КБ
- contracts/interfaces/IPancakeV3SwapCallback.sol1,26 КБ
- contracts/interfaces/IUniswapV2Pair.sol2,55 КБ
- contracts/interfaces/IUniswapV3Pool.sol1 КБ
- contracts/interfaces/IUniswapV3SwapCallback.sol1,11 КБ
- contracts/interfaces/IV4PoolManager.sol12,65 КБ
- contracts/interfaces/IV4Router.sol2,95 КБ
- contracts/interfaces/IWETH.sol356 Б
- contracts/libs/BalanceDelta.sol2,33 КБ
- contracts/libs/BytesLib.sol4,47 КБ
- contracts/libs/CallbackValidation.sol1,5 КБ
- contracts/libs/CustomRevert.sol5,17 КБ
- contracts/libs/Locker.sol734 Б
- contracts/libs/Path.sol3,01 КБ
- contracts/libs/PoolAddress.sol3,63 КБ
- contracts/libs/SafeCast.sol2,27 КБ
- contracts/libs/SafeMath.sol915 Б
- contracts/libs/TickMath.sol8,84 КБ
- contracts/libs/UniswapV2Library.sol6,04 КБ
- contracts/libs/clones.sol3,56 КБ
contracts/SwapX.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.28;
import "./Storage.sol";
import "./contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./contracts-upgradeable/interfaces/IERC1271Upgradeable.sol";
import "./contracts-upgradeable/proxy/utils/Initializable.sol";
import "./contracts-upgradeable/security/PausableUpgradeable.sol";
import "./contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {UniV2Lib} from "./extLib/UniV2Lib.sol";
import {UniV3Lib} from "./extLib/UniV3Lib.sol";
import {UniV4Lib} from "./extLib/UniV4Lib.sol";
import {OkxLib} from "./extLib/OkxLib.sol";
import {Common} from "./extLib/common.sol";
import "./interfaces/IUniswapV2Pair.sol";
import "./interfaces/IUniswapV3Pool.sol";
import "./interfaces/IPancakeV3SwapCallback.sol";
import "./interfaces/IUniswapV3SwapCallback.sol";
import "./interfaces/IWETH.sol";
import "./libs/CallbackValidation.sol";
import "./libs/Path.sol";
import "./libs/SafeCast.sol";
import "./libs/SafeMath.sol";
import "./libs/TickMath.sol";
import "./libs/UniswapV2Library.sol";
contract SwapX is
Storage,
IUniswapV3SwapCallback,
IPancakeV3SwapCallback,
Initializable,
OwnableUpgradeable,
ReentrancyGuardUpgradeable,
PausableUpgradeable
{
address public pancakeFactoryV3; // not used anymore
address constant PANCAKE_V3_FACTORY = 0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865;
address constant PANCAKE_V3_DEPLOYER = 0x41ff9AA7e16B8B1a8a8dc4f0eFacd93D02d071c9;
address constant UNISWAP_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
address constant SUSHISWAP_V3_FACTORY = 0xbACEB8eC6b9355Dfc0269C18bac9d6E2Bdc29C4F;
address internal constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD;
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMath for uint256;
using Path for bytes;
using SafeCast for uint256;
struct ExactInputSingleParams {
address factoryAddress;
address poolAddress;
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
struct ExactInputParams {
address[] factoryAddresses;
address[] poolAddresses;
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
struct ExactOutputSingleParams {
address factoryAddress;
address poolAddress;
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
struct ExactOutputParams {
address[] factoryAddresses;
address[] poolAddresses;
bytes path;
address tokenIn;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
struct ExactInputMixedParams {
string[] routes;
bytes path1;
address factory1;
address poolAddress1;
bytes path2;
address factory2;
address poolAddress2;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
struct ExactOutputMixedParams {
string[] routes;
bytes path1;
address factory1;
bytes path2;
address factory2;
uint256 amountIn2; // only for v2-v3 router
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
struct SwapCallbackData {
bytes path;
address payer;
address payerOrigin;
}
event Swap(
address indexed payer,
address indexed receiver,
address indexed feeToken,
uint256 amountIn,
uint256 amountOut,
Common.SwapDesc[] descs
);
event FeeCollected(address indexed token, address indexed payer, uint256 amount, uint256 timestamp);
modifier checkDeadline(uint256 deadline) {
require(block.timestamp <= deadline, "Transaction too old");
_;
}
receive() external payable {}
function initialize(
address _factoryV3,
address _pancakeFactoryV3,
address _WETH,
address _feeCollector,
uint256 _feeRate
) public initializer {
__Ownable_init(msg.sender);
__ReentrancyGuard_init();
__Pausable_init();
factoryV3 = _factoryV3;
pancakeFactoryV3 = _pancakeFactoryV3;
feeCollector = _feeCollector;
feeRate = _feeRate;
feeDenominator = 10000;
WETH = _WETH;
amountInCached = type(uint256).max;
}
// take fee
function takeFee(address tokenIn, uint256 amountIn) internal returns (uint256) {
if (feeExcludeList[msg.sender]) {
return 0;
}
uint256 fee = amountIn.mul(feeRate).div(feeDenominator);
if (tokenIn == address(0) || tokenIn == WETH) {
require(address(this).balance > fee, "insufficient funds");
(bool success,) = address(feeCollector).call{value: fee}("");
require(success, "SwapX: take fee error");
emit FeeCollected(address(0), msg.sender, fee, block.timestamp);
} else {
IERC20Upgradeable(tokenIn).safeTransferFrom(msg.sender, feeCollector, fee);
emit FeeCollected(tokenIn, msg.sender, fee, block.timestamp);
}
return fee;
}
function takeFeeTo(address tokenIn, uint256 amountIn) internal returns (uint256) {
uint256 fee = amountIn.mul(feeRate).div(feeDenominator);
if (fee > 0) {
Common.pay(tokenIn, address(this), feeCollector, fee);
emit FeeCollected(tokenIn, msg.sender, fee, block.timestamp);
}
return fee;
}
function swap(Common.SwapDesc[] memory descs, address feeToken, uint256 amountIn, uint256 minReturn)
public
payable
nonReentrant
whenNotPaused
{
require(descs.length > 0, "BAD_ARGS");
address payer = msg.sender;
address receiver = msg.sender;
uint256 amountInBefore = amountIn;
address payerOrigin = msg.sender;
uint256 amountOut = 0;
uint256 balanceBefore = Common.tryGetBalance(descs[descs.length - 1].tokenOut, msg.sender);
// charge fromToken
if ((Common.isNative(descs[0].tokenIn) && Common.isNative(feeToken)) || descs[0].tokenIn == feeToken) {
if (msg.value > 0) {
require(feeToken == address(0), "BAD_ARGS");
amountIn = address(this).balance; // 重新設值, 以避免需要refund的情況.
uint256 fee = takeFee(address(0), amountIn);
amountIn -= fee;
payer = address(this);
Common.wrap(address(this).balance);
} else {
uint256 fee = takeFee(feeToken, amountIn);
amountIn -= fee;
}
}
// charge toToken, for example: BNB - USDC, charge USDC.
else if (
(Common.isNative(descs[descs.length - 1].tokenOut) && Common.isNative(feeToken))
|| descs[descs.length - 1].tokenOut == feeToken
) {
if (msg.value > 0) {
require(Common.isNative(descs[0].tokenIn), "BAD_ARGS");
payer = address(this);
amountIn = address(this).balance; // 重新設值, 以避免需要refund的情況.
Common.wrap(address(this).balance);
}
receiver = address(this);
}
// not charge
else {
require(feeToken == DEAD_ADDRESS, "BAD_ARGS");
if (msg.value > 0) {
require(Common.isNative(descs[0].tokenIn), "BAD_ARGS");
payer = address(this);
amountIn = address(this).balance; // 重新設值, 以避免需要refund的情況.
Common.wrap(address(this).balance);
}
if (Common.isNative(descs[descs.length - 1].tokenOut)) {
receiver = address(this);
}
}
address assetTo = Common.getAssetTo(descs, 0);
if (assetTo != address(this)) {
Common.pay(descs[0].tokenIn, payer, assetTo, amountIn);
}
for (uint256 i = 0; i < descs.length; i++) {
Common.SwapDesc memory desc = descs[i];
address middleReceiver = Common.getMiddleReceiver(descs, i, receiver);
if (desc.swapType == Common.SwapType.V2_EXACT_IN) {
amountOut = UniV2Lib.swap(payer, middleReceiver, payerOrigin, amountIn, desc);
} else if (desc.swapType == Common.SwapType.V3_EXACT_IN) {
amountOut = UniV3Lib.swap(payer, middleReceiver, payerOrigin, amountIn, desc);
} else if (desc.swapType == Common.SwapType.V4_EXACT_IN) {
amountOut = UniV4Lib.swap(payer, middleReceiver, payerOrigin, amountIn, desc);
} else if (desc.swapType == Common.SwapType.OKX_EXACT_IN) {
amountOut = OkxLib.swap(payer, middleReceiver, payerOrigin, amountIn, desc);
} else {
revert("BAD_ARGS");
}
// update amountIn for next swap
if (i != descs.length - 1) {
payer = address(this);
amountIn = amountOut;
}
}
if (receiver == address(this)) {
if (feeToken == DEAD_ADDRESS) {
require(Common.isNative(descs[descs.length - 1].tokenOut), "BAD_ARGS");
Common.tryUnwrap(amountOut);
Common.pay(address(0), address(this), msg.sender, amountOut);
} else if (feeToken == address(0)) {
Common.tryUnwrap(amountOut);
uint256 fee = takeFeeTo(address(0), amountOut);
amountOut -= fee;
Common.pay(address(0), address(this), msg.sender, amountOut);
} else {
uint256 fee = takeFeeTo(feeToken, amountOut);
amountOut -= fee;
Common.pay(feeToken, address(this), msg.sender, amountOut);
}
}
uint256 balanceAfter = Common.tryGetBalance(descs[descs.length - 1].tokenOut, msg.sender);
require(balanceAfter - balanceBefore >= minReturn, "ERR_EXCEEDED_SLIPPAGE:minReturn not reached");
emit Swap(msg.sender, msg.sender, feeToken, amountInBefore, balanceAfter - balanceBefore, descs);
}
function unlockCallback(bytes memory data) external returns (bytes memory) {
return UniV4Lib.unlockCallback(data);
}
// V2: Any swap, ExactIn single-hop - SupportingFeeOnTransferTokens
function swapV2ExactIn(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOutMin,
address poolAddress
) public payable nonReentrant whenNotPaused returns (uint256 amountOut) {
require(poolAddress != address(0), "SwapX: invalid pool address");
require(amountIn > 0, "SwapX: amout in is zero");
bool nativeIn = false;
if (tokenIn == address(0)) {
require(msg.value >= amountIn, "SwapX: amount in and value mismatch");
nativeIn = true;
tokenIn = WETH;
// refund
uint256 amount = msg.value - amountIn;
if (amount > 0) {
(bool success,) = address(msg.sender).call{value: amount}("");
require(success, "SwapX: refund ETH error");
}
uint256 fee = takeFee(address(0), amountIn);
amountIn = amountIn - fee;
}
if (nativeIn) {
pay(tokenIn, address(this), poolAddress, amountIn);
} else {
pay(tokenIn, msg.sender, poolAddress, amountIn);
}
bool nativeOut = false;
if (tokenOut == address(0)) {
nativeOut = true;
}
uint256 balanceBefore = nativeOut
? IERC20Upgradeable(WETH).balanceOf(address(this))
: IERC20Upgradeable(tokenOut).balanceOf(msg.sender);
IUniswapV2Pair pair = IUniswapV2Pair(poolAddress);
address token0 = pair.token0();
uint256 amountInput;
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(uint256 reserve0, uint256 reserve1,) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) =
tokenIn == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20Upgradeable(tokenIn).balanceOf(address(pair)).sub(reserveInput);
amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint256 amount0Out, uint256 amount1Out) =
tokenIn == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0));
address to = nativeOut ? address(this) : msg.sender;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
if (nativeOut) {
amountOut = IERC20Upgradeable(WETH).balanceOf(address(this)).sub(balanceBefore);
IWETH(WETH).withdraw(amountOut);
uint256 fee = takeFee(address(0), amountOut);
(bool success,) = address(msg.sender).call{value: amountOut - fee}("");
require(success, "SwapX: send ETH out error");
} else {
amountOut = IERC20Upgradeable(tokenOut).balanceOf(msg.sender).sub(balanceBefore);
}
require(amountOut >= amountOutMin, "SwapX: insufficient output amount");
}
// V2: Any swap, ExactOut single-hop - * not support fee-on-transfer tokens *
// function swapV2ExactOut(
// address tokenIn,
// address tokenOut,
// uint256 amountInMax,
// uint256 amountOut,
// address poolAddress
// ) payable public nonReentrant whenNotPaused returns (uint amountIn){
// require(poolAddress != address(0), "SwapX: invalid pool address");
// require(amountInMax > 0, "SwapX: amout in max is zero");
// bool nativeIn = false;
// if (tokenIn == address(0)) {
// tokenIn = WETH;
// nativeIn = true;
// require(msg.value >= amountInMax, "SwapX: amount in and value mismatch");
// }
// bool nativeOut = false;
// if (tokenOut == address(0))
// nativeOut = true;
// IUniswapV2Pair pair = IUniswapV2Pair(poolAddress);
// address token0 = pair.token0();
// { // scope to avoid stack too deep errors
// (uint256 reserve0, uint256 reserve1,) = pair.getReserves();
// (uint256 reserveInput, uint256 reserveOutput) = tokenIn == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
// amountIn = UniswapV2Library.getAmountIn(amountOut, reserveInput, reserveOutput);
// require(amountIn <= amountInMax, "SwapX: eswapV2ExactOutxcessive input amount");
// uint256 fee = 0;
// if (!nativeOut) {
// fee = takeFee(tokenIn, amountIn);
// amountIn = amountIn - fee;
// }
// if(nativeIn) {
// pay(tokenIn, address(this), poolAddress, amountIn);
// uint256 amount = msg.value - amountIn - fee;
// // refund
// if (amount > 0) {
// (bool success, ) = address(msg.sender).call{value: amount}("");
// require(success, "SwapX: refund ETH error");
// }
// } else {
// pay(tokenIn, msg.sender, poolAddress, amountIn);
// }
// }
// (uint256 amount0Out, uint256 amount1Out) = tokenIn == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0));
// address to = nativeOut ? address(this) : msg.sender;
// pair.swap(amount0Out, amount1Out, to, new bytes(0));
// if (nativeOut) {
// IWETH(WETH).withdraw(amountOut);
// uint256 fee = takeFee(address(0), amountOut);
// (bool success, ) = address(msg.sender).call{value: amountOut-fee}("");
// require(success, "SwapX: send ETH out error");
// }
// }
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint256[] memory amounts, address[] memory path, address _to, address _factory) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) =
input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(_factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(_factory, input, output))
.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to, address _factory) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(_factory, input, output));
uint256 amountInput;
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(uint256 reserve0, uint256 reserve1,) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) =
input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20Upgradeable(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint256 amount0Out, uint256 amount1Out) =
input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(_factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
// V2-V2: Uniswap/Sushiswap, SupportingFeeOnTransferTokens and multi-hop
function swapV2MultiHopExactIn(
address tokenIn,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address recipient,
uint256 deadline,
address factory
) public payable nonReentrant whenNotPaused checkDeadline(deadline) returns (uint256[] memory amounts) {
require(amountIn > 0, "SwapX: amout in is zero");
bool nativeIn = false;
if (tokenIn == address(0)) {
require(msg.value >= amountIn, "SwapX: amount in and value mismatch");
nativeIn = true;
tokenIn = WETH;
// refund
uint256 amount = msg.value - amountIn;
if (amount > 0) {
(bool success,) = address(msg.sender).call{value: amount}("");
require(success, "SwapX: refund ETH error");
}
}
bool nativeOut = false;
address tokenOut = path[path.length - 1];
if (tokenOut == WETH) {
nativeOut = true;
}
if (!nativeOut) {
uint256 fee = takeFee(tokenIn, amountIn);
amountIn = amountIn - fee;
}
address firstPool = UniswapV2Library.pairFor(factory, path[0], path[1]);
if (nativeIn) {
pay(tokenIn, address(this), firstPool, amountIn);
} else {
pay(tokenIn, msg.sender, firstPool, amountIn);
}
require(tokenIn == path[0], "invalid path");
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
uint256 balanceBefore = IERC20Upgradeable(tokenOut).balanceOf(nativeOut ? address(this) : recipient);
_swapSupportingFeeOnTransferTokens(path, nativeOut ? address(this) : recipient, factory);
uint256 amountOut =
IERC20Upgradeable(tokenOut).balanceOf(nativeOut ? address(this) : recipient).sub(balanceBefore);
amounts[path.length - 1] = amountOut;
require(amountOut >= amountOutMin, "SwapX: insufficient output amount");
if (nativeOut) {
IWETH(WETH).withdraw(amountOut);
uint256 fee = takeFee(address(0), amountOut);
(bool success,) = address(recipient).call{value: amountOut - fee}("");
require(success, "SwapX: send ETH out error");
}
}
// // V2-V2: Uniswap, ExactOut multi-hop, not support fee-on-transfer token in output
// function swapV2MultiHopExactOut(
// address tokenIn,
// uint256 amountInMax,
// uint256 amountOut,
// address[] calldata path,
// address recipient,
// uint deadline,
// address factory
// ) payable public nonReentrant whenNotPaused checkDeadline(deadline) returns (uint[] memory amounts){
// require(amountInMax > 0, "SwapX: amount in max is zero");
// bool nativeIn = false;
// if (tokenIn == address(0)) {
// nativeIn = true;
// tokenIn = WETH;
// require(msg.value >= amountInMax, "SwapX: amount in and value mismatch");
// }
// bool nativeOut = false;
// address tokenOut = path[path.length-1];
// if (tokenOut == WETH)
// nativeOut = true;
// amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
// uint256 fee = 0;
// if (!nativeOut) {
// fee = takeFee(tokenIn, amounts[0]);
// amounts[0] = amounts[0] - fee;
// require(amounts[0] + fee <= amountInMax, 'SwapX: excessive input amount');
// }
// address firstPool = UniswapV2Library.pairFor(factory, path[0], path[1]);
// if (nativeIn) {
// pay(tokenIn, address(this), firstPool, amounts[0]);
// uint amount = msg.value - amounts[0] - fee;
// // refund
// if (amount > 0) {
// (bool success, ) = address(msg.sender).call{value: amount}("");
// require(success, "SwapX: refund ETH error");
// }
// } else
// pay(tokenIn, msg.sender, firstPool, amounts[0]);
// _swap(amounts, path, nativeOut ? address(this) : recipient, factory);
// if (nativeOut) {
// IWETH(WETH).withdraw(amountOut);
// fee = takeFee(address(0), amountOut);
// (bool success, ) = address(recipient).call{value: amountOut-fee}("");
// require(success, "SwapX: send ETH out error");
// }
// }
/// UniswapV3SwapCallback
function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata _data) external override {
require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
address factory = IUniswapV3Pool(msg.sender).factory();
address tokenIn;
address tokenOut;
uint24 fee = 0;
int24 tickSpacing = 0;
if (factory == UNISWAP_V3_FACTORY) {
(tokenIn, tokenOut, fee) = data.path.decodeFirstPool();
CallbackValidation.verifyCallback(UNISWAP_V3_FACTORY, tokenIn, tokenOut, fee, tickSpacing);
} else if (factory == SUSHISWAP_V3_FACTORY) {
(tokenIn, tokenOut, fee) = data.path.decodeFirstPool();
CallbackValidation.verifyCallback(SUSHISWAP_V3_FACTORY, tokenIn, tokenOut, fee, tickSpacing);
} else {
revert("SwapX: Invalid pool");
}
(bool isExactInput, uint256 amountToPay) =
amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta)) : (tokenOut < tokenIn, uint256(amount1Delta));
if (isExactInput) {
pay(tokenIn, data.payer, msg.sender, amountToPay);
if (tokenIn == WETH) {
IWETH(WETH).deposit{value: address(this).balance}();
}
uint256 amount = IERC20Upgradeable(tokenIn).balanceOf(address(this));
if (amount > 0) {
if (tokenIn == WETH) {
Common.tryUnwrap(amount);
Common.pay(address(0), address(this), data.payerOrigin, amount);
} else {
Common.pay(tokenIn, address(this), data.payerOrigin, amount);
}
}
}
}
/// PancakeV3SwapCallback
function pancakeV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata _data) external override {
require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
(address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();
CallbackValidation.verifyCallback(PANCAKE_V3_FACTORY, tokenIn, tokenOut, fee, 0);
(bool isExactInput, uint256 amountToPay) =
amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta)) : (tokenOut < tokenIn, uint256(amount1Delta));
if (isExactInput) {
pay(tokenIn, data.payer, msg.sender, amountToPay);
if (tokenIn == WETH) {
IWETH(WETH).deposit{value: address(this).balance}();
}
uint256 amount = IERC20Upgradeable(tokenIn).balanceOf(address(this));
if (amount > 0) {
if (tokenIn == WETH) {
Common.tryUnwrap(amount);
Common.pay(address(0), address(this), data.payerOrigin, amount);
} else {
Common.pay(tokenIn, address(this), data.payerOrigin, amount);
}
}
}
}
// V3: ExactIn single-hop
function swapV3ExactIn(ExactInputSingleParams memory params)
external
payable
nonReentrant
whenNotPaused
checkDeadline(params.deadline)
returns (uint256 amountOut)
{
require(params.amountIn > 0, "SwapX: amount in is zero");
if (params.tokenIn == WETH || params.tokenIn == address(0)) {
params.tokenIn = WETH;
require(msg.value >= params.amountIn, "SwapX: amount in and value mismatch");
// refund
uint256 amount = msg.value - params.amountIn;
if (amount > 0) {
(bool success,) = address(msg.sender).call{value: amount}("");
require(success, "SwapX: refund ETH error");
}
}
bool nativeOut = false;
if (params.tokenOut == WETH) {
nativeOut = true;
}
if (!nativeOut) {
uint256 fee = takeFee(params.tokenIn, params.amountIn);
params.amountIn = params.amountIn - fee;
}
factoryV3 = params.factoryAddress;
amountOut = exactInputInternal(
params.poolAddress,
params.amountIn,
nativeOut ? address(0) : params.recipient,
params.sqrtPriceLimitX96,
SwapCallbackData({
path: abi.encodePacked(params.tokenIn, params.fee, params.tokenOut),
payer: msg.sender,
payerOrigin: msg.sender
})
);
require(amountOut >= params.amountOutMinimum, "SwapX: insufficient out amount");
if (nativeOut) {
IWETH(WETH).withdraw(amountOut);
uint256 fee = takeFee(address(0), amountOut);
(bool success,) = address(params.recipient).call{value: amountOut - fee}("");
require(success, "SwapX: send ETH out error");
}
}
// // V3: ExactOut single-hop
// function swapV3ExactOut (
// ExactOutputSingleParams memory params
// ) payable public nonReentrant whenNotPaused checkDeadline(params.deadline) returns (uint256 amountIn) {
// require(params.amountInMaximum > 0, "SwapX: amount in max is zero");
// bool nativeIn = false;
// if (params.tokenIn == WETH || params.tokenIn == address(0)) {
// params.tokenIn = WETH;
// nativeIn = true;
// require(msg.value >= params.amountInMaximum, "SwapX: amount in max and value mismatch");
// }
// bool nativeOut = false;
// if (params.tokenOut == WETH || params.tokenOut == address(0)) {
// params.tokenOut = WETH;
// nativeOut = true;
// }
// uint256 fee = 0;
// if (!nativeOut) {
// fee = takeFee(params.tokenIn, amountIn);
// amountIn = amountIn - fee;
// require(amountIn + fee <= params.amountInMaximum, "SwapX: too much requested");
// }
// amountIn = exactOutputInternal(
// params.amountOut,
// nativeOut ? address(0) : params.recipient,
// params.sqrtPriceLimitX96,
// SwapCallbackData({path: abi.encodePacked(params.tokenOut, params.fee, params.tokenIn), payer: msg.sender, payerOrigin: msg.sender})
// );
// if (nativeIn) {
// uint amount = msg.value - amountIn - fee;
// // refund
// if (amount > 0) {
// (bool success, ) = address(msg.sender).call{value: amount}("");
// require(success, "SwapX: refund ETH error");
// }
// }
// if (nativeOut) {
// IWETH(WETH).withdraw(params.amountOut);
// fee = takeFee(address(0), params.amountOut);
// (bool success, ) = address(params.recipient).call{value: params.amountOut - fee}("");
// require(success, "SwapX: send ETH out error");
// }
// amountInCached = type(uint256).max;
// }
// V3-V3: ExactIn multi-hop
function swapV3MultiHopExactIn(ExactInputParams memory params)
public
payable
nonReentrant
whenNotPaused
checkDeadline(params.deadline)
returns (uint256 amountOut)
{
require(params.amountIn > 0, "SwapX: amount in is zero");
if (msg.value > 0) {
require(msg.value >= params.amountIn, "SwapX: amount in and value mismatch");
// refund
uint256 amount = msg.value - params.amountIn;
if (amount > 0) {
(bool success,) = address(msg.sender).call{value: amount}("");
require(success, "SwapX: refund ETH error");
}
}
(address tokenIn,,) = params.path.decodeFirstPool();
if (tokenIn == WETH || tokenIn == address(0)) {
tokenIn = WETH;
uint256 fee = takeFee(address(0), params.amountIn);
params.amountIn = params.amountIn - fee;
}
address payer = msg.sender; // msg.sender pays for the first hop
bool nativeOut = false;
uint256 i = 0;
while (true) {
bool hasMultiplePools = params.path.hasMultiplePools();
if (!hasMultiplePools) {
(, address tokenOut,) = params.path.decodeFirstPool();
if (tokenOut == WETH) {
nativeOut = true;
}
}
// the outputs of prior swaps become the inputs to subsequent ones
factoryV3 = params.factoryAddresses[i];
params.amountIn = exactInputInternal(
params.poolAddresses[i],
params.amountIn,
hasMultiplePools ? address(this) : (nativeOut ? address(this) : params.recipient),
0,
SwapCallbackData({path: params.path.getFirstPool(), payer: payer, payerOrigin: msg.sender})
);
// decide whether to continue or terminate
if (hasMultiplePools) {
payer = address(this); // at this point, the caller has paid
params.path = params.path.skipToken();
i++;
} else {
amountOut = params.amountIn;
break;
}
}
require(amountOut >= params.amountOutMinimum, "SwapX: too little received");
if (nativeOut) {
IWETH(WETH).withdraw(amountOut);
uint256 fee = takeFee(address(0), amountOut);
(bool success,) = address(params.recipient).call{value: amountOut - fee}("");
require(success, "SwapX: send ETH out error");
}
}
// V3-V3: ExactOut multi-hop
// function swapV3MultiHopExactOut(
// ExactOutputParams memory params
// ) external payable nonReentrant whenNotPaused checkDeadline(params.deadline) returns (uint256 amountIn) {
// require(params.amountInMaximum > 0, "SwapX: amount in max is zero");
// if (msg.value > 0)
// require(msg.value >= params.amountInMaximum, "SwapX: amount in max and value mismatch");
// bool nativeOut = false;
// (address tokenOut, , ) = params.path.decodeFirstPool();
// if (tokenOut == WETH)
// nativeOut = true;
// uint256 fee = 0;
// if (!nativeOut) {
// fee = takeFee(params.tokenIn, amountIn);
// amountIn = amountIn - fee;
// require(amountIn + fee <= params.amountInMaximum, 'SwapX: too much requested');
// }
// exactOutputInternal(
// params.amountOut,
// nativeOut ? address(this) : params.recipient,
// 0,
// SwapCallbackData({path: params.path, payer: msg.sender, payerOrigin: msg.sender})
// );
// amountIn = amountInCached;
// if (params.tokenIn == WETH || params.tokenIn == address(0)) {
// if (msg.value > 0) {
// // refund
// uint256 amount = msg.value - amountIn - fee;
// if (amount > 0) {
// (bool success, ) = address(msg.sender).call{value: amount}("");
// require(success, "SwapX: refund ETH error");
// }
// }
// }
// if (nativeOut) {
// IWETH(WETH).withdraw(params.amountOut);
// fee = takeFee(address(0), params.amountOut);
// (bool success, ) = address(params.recipient).call{value: params.amountOut-fee}("");
// require(success, "SwapX: send ETH out error");
// }
// amountInCached = type(uint256).max;
// }
function isStrEqual(string memory str1, string memory str2) internal pure returns (bool) {
return keccak256(bytes(str1)) == keccak256(bytes(str2));
}
// Mixed: ExactIn multi-hop, token not supporting zero address
function swapMixedMultiHopExactIn(ExactInputMixedParams memory params)
public
payable
nonReentrant
whenNotPaused
checkDeadline(params.deadline)
returns (uint256 amountOut)
{
require(params.routes.length == 2, "SwapX: only 2 routes supported");
require(params.amountIn > 0, "SwapX: amount in is zero");
(address tokenIn, address tokenOut1, uint24 fee1) = params.path1.decodeFirstPool();
bool nativeIn = false;
if (tokenIn == WETH || tokenIn == address(0)) {
require(msg.value >= params.amountIn, "SwapX: amount in and value mismatch");
nativeIn = true;
tokenIn = WETH;
// refund
uint256 amount = msg.value - params.amountIn;
if (amount > 0) {
(bool success,) = address(msg.sender).call{value: amount}("");
require(success, "SwapX: refund ETH error");
}
uint256 fee = takeFee(address(0), params.amountIn);
params.amountIn = params.amountIn - fee;
}
if (isStrEqual(params.routes[0], "v2") && isStrEqual(params.routes[1], "v2")) {
// uni - sushi, or verse
address poolAddress1 = UniswapV2Library.pairFor(params.factory1, tokenIn, tokenOut1);
if (nativeIn) {
pay(tokenIn, address(this), poolAddress1, params.amountIn);
} else {
pay(tokenIn, msg.sender, poolAddress1, params.amountIn);
}
address[] memory path1 = new address[](2);
path1[0] = tokenIn;
path1[1] = tokenOut1;
(, address tokenOut,) = params.path2.decodeFirstPool();
address[] memory path2 = new address[](2);
path2[0] = tokenOut1;
path2[1] = tokenOut;
address poolAddress2 = UniswapV2Library.pairFor(params.factory2, tokenOut1, tokenOut);
bool nativeOut = tokenOut == WETH;
uint256 balanceBefore = IERC20Upgradeable(tokenOut).balanceOf(nativeOut ? address(this) : params.recipient);
_swapSupportingFeeOnTransferTokens(path1, poolAddress2, params.factory1);
_swapSupportingFeeOnTransferTokens(path2, nativeOut ? address(this) : params.recipient, params.factory2);
amountOut =
IERC20Upgradeable(tokenOut).balanceOf(nativeOut ? address(this) : params.recipient).sub(balanceBefore);
if (nativeOut) {
IWETH(WETH).withdraw(amountOut);
uint256 fee = takeFee(address(0), amountOut);
(bool success,) = address(params.recipient).call{value: amountOut - fee}("");
require(success, "SwapX: send ETH out error");
}
} else if (isStrEqual(params.routes[0], "v2") && isStrEqual(params.routes[1], "v3")) {
address poolAddress1 = UniswapV2Library.pairFor(params.factory1, tokenIn, tokenOut1);
if (nativeIn) {
pay(tokenIn, address(this), poolAddress1, params.amountIn);
} else {
pay(tokenIn, msg.sender, poolAddress1, params.amountIn);
}
address[] memory path1 = new address[](2);
path1[0] = tokenIn;
path1[1] = tokenOut1;
(, address tokenOut,) = params.path2.decodeFirstPool();
bool nativeOut = tokenOut == WETH;
uint256 balanceBefore = IERC20Upgradeable(tokenOut).balanceOf(nativeOut ? address(this) : params.recipient);
_swapSupportingFeeOnTransferTokens(path1, address(this), params.factory1);
factoryV3 = params.factory2;
amountOut = exactInputInternal(
params.poolAddress2,
IERC20Upgradeable(tokenOut1).balanceOf(address(this)),
nativeOut ? address(this) : params.recipient,
0,
SwapCallbackData({path: params.path2, payer: address(this), payerOrigin: msg.sender})
);
amountOut =
IERC20Upgradeable(tokenOut).balanceOf(nativeOut ? address(this) : params.recipient).sub(balanceBefore);
if (nativeOut) {
IWETH(WETH).withdraw(amountOut);
uint256 fee = takeFee(address(0), amountOut);
(bool success,) = address(params.recipient).call{value: amountOut - fee}("");
require(success, "SwapX: send ETH out error");
}
} else if (isStrEqual(params.routes[0], "v3") && isStrEqual(params.routes[1], "v2")) {
(address tokenIn2, address tokenOut,) = params.path2.decodeFirstPool();
address pairV2Address = UniswapV2Library.pairFor(params.factory2, tokenIn2, tokenOut);
factoryV3 = params.factory1;
uint256 amountOut1 = exactInputInternal(
params.poolAddress1,
params.amountIn,
pairV2Address,
0,
SwapCallbackData({
path: abi.encodePacked(tokenIn, fee1, tokenOut1), payer: msg.sender, payerOrigin: msg.sender
})
);
address[] memory path2 = new address[](2);
path2[0] = tokenIn2;
path2[1] = tokenOut;
uint256[] memory amounts2 = UniswapV2Library.getAmountsOut(params.factory2, amountOut1, path2);
amountOut = amounts2[amounts2.length - 1];
bool nativeOut = tokenOut == WETH;
uint256 balanceBefore = IERC20Upgradeable(tokenOut).balanceOf(nativeOut ? address(this) : params.recipient);
_swapSupportingFeeOnTransferTokens(path2, nativeOut ? address(this) : params.recipient, params.factory2);
amountOut =
IERC20Upgradeable(tokenOut).balanceOf(nativeOut ? address(this) : params.recipient).sub(balanceBefore);
if (nativeOut) {
IWETH(WETH).withdraw(amountOut);
uint256 fee = takeFee(address(0), amountOut);
(bool success,) = address(params.recipient).call{value: amountOut - fee}("");
require(success, "SwapX: send ETH out error");
}
}
require(amountOut >= params.amountOutMinimum, "SwapX: too little received");
}
/// V3: Performs a single exact input swap
function exactInputInternal(
address poolAddress,
uint256 amountIn,
address recipient,
uint160 sqrtPriceLimitX96,
SwapCallbackData memory data
) private returns (uint256 amountOut) {
// allow swapping to the router address with address 0
if (recipient == address(0)) recipient = address(this);
(address tokenIn, address tokenOut,) = data.path.decodeFirstPool();
bool zeroForOne = tokenIn < tokenOut;
(int256 amount0, int256 amount1) = IUniswapV3Pool(poolAddress)
.swap(
recipient,
zeroForOne,
amountIn.toInt256(),
sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: sqrtPriceLimitX96,
abi.encode(data)
);
return uint256(-(zeroForOne ? amount1 : amount0));
}
/// Performs a single exact output swap
// function exactOutputInternal(
// uint256 amountOut,
// address recipient,
// uint160 sqrtPriceLimitX96,
// SwapCallbackData memory data
// ) private returns (uint256 amountIn) {
// // allow swapping to the router address with address 0
// if (recipient == address(0)) recipient = address(this);
// (address tokenOut, address tokenIn, uint24 fee) = data.path.decodeFirstPool();
// bool zeroForOne = tokenIn < tokenOut;
// (int256 amount0Delta, int256 amount1Delta) =
// getPool(tokenIn, tokenOut, fee).swap(
// recipient,
// zeroForOne,
// -amountOut.toInt256(),
// sqrtPriceLimitX96 == 0
// ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
// : sqrtPriceLimitX96,
// abi.encode(data)
// );
// uint256 amountOutReceived;
// (amountIn, amountOutReceived) = zeroForOne
// ? (uint256(amount0Delta), uint256(-amount1Delta))
// : (uint256(amount1Delta), uint256(-amount0Delta));
// // it's technically possible to not receive the full output amount,
// // so if no price limit has been specified, require this possibility away
// if (sqrtPriceLimitX96 == 0) require(amountOutReceived == amountOut);
// }
function pay(address token, address payer, address recipient, uint256 value) internal {
if (token == WETH && address(this).balance >= value) {
// pay with WETH
IWETH(WETH).deposit{value: value}(); // wrap only what is needed to pay
IWETH(WETH).transfer(recipient, value);
} else if (payer == address(this)) {
// pay with tokens already in the contract (for the exact input multihop case)
IERC20Upgradeable(token).safeTransfer(recipient, value);
} else {
// pull payment
IERC20Upgradeable(token).safeTransferFrom(payer, recipient, value);
}
}
function pause() external onlyOwner {
require(paused() == false, "paused already");
_pause();
}
function unpause() external onlyOwner {
require(paused() == true, "unpaused already");
_unpause();
}
// function setWETH(address addr) external onlyOwner {
// require(addr != address(0), "invalid addr");
// WETH = addr;
// }
// function setWhitelistAddr(address addr) external onlyOwner {
// require(addr != address(0),"invalid addr");
// feeExcludeList[addr] = true;
// }
function withdraw(address token, address receiver, uint256 amount) external onlyOwner {
if (token == address(0)) {
(bool s,) = payable(receiver).call{value: amount}("");
require(s, "withdraw native failed");
} else {
IERC20Upgradeable(token).safeTransfer(receiver, amount);
}
}
}
contracts/Storage.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
contract Storage {
uint256 public amountInCached;
uint256 public feeRate;
uint256 public feeDenominator;
address public feeCollector;
address public WETH;
address public factoryV2; // used only in obselete method
address public factoryV3; // used only in obselete method
mapping(address => bool) public feeExcludeList;
}
contracts/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import "../proxy/utils/Initializable.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
contracts/contracts-upgradeable/interfaces/IERC1271Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*/
interface IERC1271Upgradeable {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
contracts/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0e;
/**
* @dev The contract is already initialized.
*/
error AlreadyInitialized();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
if (!(isTopLevelCall && initialized < 1) && !(address(this).code.length == 0 && initialized == 1)) {
revert AlreadyInitialized();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert AlreadyInitialized();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert AlreadyInitialized();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
contracts/contracts-upgradeable/security/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.20;
import "../proxy/utils/Initializable.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
contracts/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
contracts/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
contracts/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
contracts/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {AddressUpgradeable} from "../../../utils/AddressUpgradeable.sol";
import {IERC20Upgradeable} from "../IERC20Upgradeable.sol";
import {IERC20PermitUpgradeable} from "../extensions/IERC20PermitUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
if (nonceAfter != nonceBefore + 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
contracts/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success,) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(address target, bool success, bytes memory returndata)
internal
view
returns (bytes memory)
{
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
contracts/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.20;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {}
function __Context_init_unchained() internal onlyInitializing {}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
contracts/extLib/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Constants {
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
address internal constant PANCAKE_V3_FACTORY = 0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865;
address internal constant PANCAKE_V3_DEPLOYER = 0x41ff9AA7e16B8B1a8a8dc4f0eFacd93D02d071c9;
address internal constant UNISWAP_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
address internal constant SUSHISWAP_V3_FACTORY = 0xbACEB8eC6b9355Dfc0269C18bac9d6E2Bdc29C4F;
bytes32 internal constant UNISWAP_V3_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
bytes32 internal constant PANCAKE_V3_CODE_HASH = 0x6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e2;
address internal constant UNISWAP_V2_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address internal constant PANCAKE_V2_FACTORY = 0x1097053Fd2ea711dad45caCcc45EfF7548fCB362;
address internal constant SUSHISWAP_V2_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac;
bytes32 internal constant UNISWAP_V2_CODE_HASH = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f;
bytes32 internal constant PANCAKE_V2_CODE_HASH = 0x57224589c67f3f30a6b0d7a1b54cf3153ab84563bc609ef41dfb34f8b2974d2d;
address internal constant ETH = address(0);
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address internal constant poolManager = address(payable(0x000000000004444c5dc75cB358380D2e3dE08A90));
}
contracts/extLib/OkxLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IOKXDexRouter} from "../interfaces/IOKXDexRouter.sol";
import {IERC20Upgradeable} from "../contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable} from "../contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IFourTokenManager} from "../interfaces/IFourTokenManager.sol";
import {IWETH} from "../interfaces/IWETH.sol";
import {Common} from "./common.sol";
import {Constants} from "./constants.sol";
library OkxLib {
using SafeERC20Upgradeable for IERC20Upgradeable;
function swap(address payer, address receiver, address payerOrigin, uint256 amountIn, Common.SwapDesc calldata desc)
external
returns (uint256 amountOut)
{
if (desc.tokenIn == address(0)) {
// USE native token as input token
Common.unwrap(amountIn);
amountIn = address(this).balance;
bytes memory scaledCallData = _okxScaling(desc.hookData, amountIn, address(this));
(bool success,) = payable(address(desc.poolAddress)).call{value: amountIn}(scaledCallData);
require(success, "OkxLib: swap failed");
} else {
Common.claim(desc.tokenIn, payer, address(this), amountIn);
amountIn = IERC20Upgradeable(desc.tokenIn).balanceOf(address(this));
bytes memory scaledCallData = _okxScaling(desc.hookData, amountIn, address(this));
address tokenApprove = __getTokenApproveForChain(block.chainid);
require(tokenApprove != address(0), "OkxLib: token approve not found");
IERC20Upgradeable(desc.tokenIn).forceApprove(address(tokenApprove), amountIn);
(bool success,) = address(desc.poolAddress).call(scaledCallData);
require(success, "OkxLib: swap failed");
}
if (desc.tokenOut == address(0)) {
amountOut = address(this).balance;
Common.wrap(amountOut);
Common.pay(Constants.WETH, address(this), receiver, amountOut);
} else {
amountOut = IERC20Upgradeable(desc.tokenOut).balanceOf(address(this));
Common.pay(desc.tokenOut, address(this), receiver, amountOut);
}
return amountOut;
}
function _okxScaling(bytes calldata rawCallData, uint256 actualAmount, address receiverToReplace)
internal
pure
returns (bytes memory scaledCallData)
{
bytes4 selector = bytes4(rawCallData[:4]);
bytes calldata dataToDecode = rawCallData[4:];
uint256 rawAmountIn;
if (selector == IOKXDexRouter.uniswapV3SwapTo.selector) {
(uint256 receiver, uint256 amount, uint256 minReturn, uint256[] memory pools) =
abi.decode(dataToDecode, (uint256, uint256, uint256, uint256[]));
rawAmountIn = amount;
minReturn = (minReturn * actualAmount) / amount;
amount = actualAmount;
scaledCallData = abi.encodeWithSelector(selector, receiverToReplace, amount, minReturn, pools);
} else if (selector == IOKXDexRouter.smartSwapTo.selector) {
(
uint256 orderId,
address receiver,
IOKXDexRouter.BaseRequest memory baseRequest,
uint256[] memory batchesAmount,
IOKXDexRouter.RouterPath[][] memory batches,
IOKXDexRouter.PMMSwapRequest[] memory extraData
) = abi.decode(
dataToDecode,
(
uint256,
address,
IOKXDexRouter.BaseRequest,
uint256[],
IOKXDexRouter.RouterPath[][],
IOKXDexRouter.PMMSwapRequest[]
)
);
rawAmountIn = baseRequest.fromTokenAmount;
batchesAmount = _scaleArray(batchesAmount, actualAmount, baseRequest.fromTokenAmount);
baseRequest.minReturnAmount = (baseRequest.minReturnAmount * actualAmount) / baseRequest.fromTokenAmount;
baseRequest.fromTokenAmount = actualAmount;
scaledCallData = abi.encodeWithSelector(
selector, orderId, receiverToReplace, baseRequest, batchesAmount, batches, extraData
);
} else if (selector == IOKXDexRouter.unxswapTo.selector) {
(uint256 srcToken, uint256 amount, uint256 minReturn, address receiver, bytes32[] memory pools) =
abi.decode(dataToDecode, (uint256, uint256, uint256, address, bytes32[]));
minReturn = (minReturn * actualAmount) / amount;
rawAmountIn = amount;
amount = actualAmount;
scaledCallData = abi.encodeWithSelector(selector, srcToken, amount, minReturn, receiver, pools);
} else if (selector == IOKXDexRouter.unxswapByOrderId.selector) {
(uint256 srcToken, uint256 amount, uint256 minReturn, bytes32[] memory pools) =
abi.decode(dataToDecode, (uint256, uint256, uint256, bytes32[]));
rawAmountIn = amount;
minReturn = (minReturn * actualAmount) / amount;
amount = actualAmount;
scaledCallData = abi.encodeWithSelector(selector, srcToken, amount, minReturn, pools);
} else if (selector == IOKXDexRouter.smartSwapByOrderId.selector) {
(
uint256 orderId,
IOKXDexRouter.BaseRequest memory baseRequest,
uint256[] memory batchesAmount,
IOKXDexRouter.RouterPath[][] memory batches,
IOKXDexRouter.PMMSwapRequest[] memory extraData
) = abi.decode(
dataToDecode,
(
uint256,
IOKXDexRouter.BaseRequest,
uint256[],
IOKXDexRouter.RouterPath[][],
IOKXDexRouter.PMMSwapRequest[]
)
);
rawAmountIn = baseRequest.fromTokenAmount;
batchesAmount = _scaleArray(batchesAmount, actualAmount, baseRequest.fromTokenAmount);
baseRequest.minReturnAmount = (baseRequest.minReturnAmount * actualAmount) / baseRequest.fromTokenAmount;
baseRequest.fromTokenAmount = actualAmount;
scaledCallData = abi.encodeWithSelector(selector, orderId, baseRequest, batchesAmount, batches, extraData);
} else if (selector == IOKXDexRouter.dagSwapTo.selector) {
(
uint256 orderId,
address receiver,
IOKXDexRouter.BaseRequest memory baseRequest,
IOKXDexRouter.RouterPath[] memory paths
) = abi.decode(dataToDecode, (uint256, address, IOKXDexRouter.BaseRequest, IOKXDexRouter.RouterPath[]));
rawAmountIn = baseRequest.fromTokenAmount;
baseRequest.minReturnAmount = (baseRequest.minReturnAmount * actualAmount) / baseRequest.fromTokenAmount;
baseRequest.fromTokenAmount = actualAmount;
scaledCallData = abi.encodeWithSelector(selector, orderId, receiverToReplace, baseRequest, paths);
} else if (selector == IOKXDexRouter.dagSwapByOrderId.selector) {
(uint256 orderId, IOKXDexRouter.BaseRequest memory baseRequest, IOKXDexRouter.RouterPath[] memory paths) =
abi.decode(dataToDecode, (uint256, IOKXDexRouter.BaseRequest, IOKXDexRouter.RouterPath[]));
rawAmountIn = baseRequest.fromTokenAmount;
baseRequest.minReturnAmount = (baseRequest.minReturnAmount * actualAmount) / baseRequest.fromTokenAmount;
baseRequest.fromTokenAmount = actualAmount;
scaledCallData = abi.encodeWithSelector(selector, orderId, baseRequest, paths);
} else {
revert("OkxLib: OKX selector not supported");
}
bytes memory tail = rawCallData[scaledCallData.length:];
scaledCallData = bytes.concat(scaledCallData, tail);
return scaledCallData;
}
function _scaleArray(uint256[] memory arr, uint256 newAmount, uint256 oldAmount)
internal
pure
returns (uint256[] memory scaledArr)
{
scaledArr = new uint256[](arr.length);
for (uint256 i = 0; i < arr.length; i++) {
scaledArr[i] = (arr[i] * newAmount) / oldAmount;
}
}
function __getTokenApproveForChain(uint256 chainid) private pure returns (address) {
if (chainid == 1) {
return 0x40aA958dd87FC8305b97f2BA922CDdCa374bcD7f;
}
if (chainid == 10) {
return 0x68D6B739D2020067D1e2F713b999dA97E4d54812;
}
if (chainid == 56) {
return 0x2c34A2Fb1d0b4f55de51E1d0bDEfaDDce6b7cDD6;
}
if (chainid == 42_161) {
return 0x70cBb871E8f30Fc8Ce23609E9E0Ea87B6b222F58;
}
if (chainid == 8453 || chainid == 5000) {
return 0x57df6092665eb6058DE53939612413ff4B09114E;
}
if (chainid == 146) {
return 0xD321ab5589d3E8FA5Df985ccFEf625022E2DD910;
}
if (chainid == 9745) {
return 0x9FD43F5E4c24543b2eBC807321E58e6D350d6a5A;
}
return address(0);
}
}
contracts/extLib/UniV2Lib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Upgradeable} from "../contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable} from "../contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IUniswapV2Pair} from "../interfaces/IUniswapV2Pair.sol";
import {Common} from "./common.sol";
import {Constants} from "./constants.sol";
library UniV2Lib {
function swap(address payer, address receiver, address payerOrigin, uint256 amountIn, Common.SwapDesc memory desc)
external
returns (uint256)
{
(, uint256 amountOut) = swapV2ExactIn(desc.tokenIn, desc.tokenOut, amountIn, desc.poolAddress, receiver);
return amountOut;
}
// slippage is controlled outside the lib
// amount should be transferred directly to the pool
function swapV2ExactIn(address tokenIn, address tokenOut, uint256 amountIn, address poolAddress, address receiver)
internal
returns (uint256, uint256)
{
require(poolAddress != address(0), "SwapX: invalid pool address");
require(amountIn > 0, "SwapX: amout in is zero");
// bool needWrap;
// bool needUnWrap;
if (tokenIn == address(0)) {
tokenIn = Constants.WETH;
} else if (tokenOut == address(0)) {
tokenOut = Constants.WETH;
}
bool zeroForOne = tokenIn < tokenOut;
uint256 balanceIn = IERC20Upgradeable(tokenIn).balanceOf(poolAddress);
(uint256 r0, uint256 r1,) = IUniswapV2Pair(poolAddress).getReserves();
(uint256 reserveIn, uint256 reserveOut) = zeroForOne ? (r0, r1) : (r1, r0);
uint256 amountDelta = balanceIn - reserveIn;
uint256 amountOut = _getAmountOut(amountDelta, reserveIn, reserveOut, _getFee(tokenIn, tokenOut, poolAddress));
(uint256 amount0, uint256 amount1) = zeroForOne ? (uint256(0), amountOut) : (amountOut, 0);
uint256 balanceOut = IERC20Upgradeable(tokenOut).balanceOf(receiver);
IUniswapV2Pair(poolAddress).swap(amount0, amount1, receiver, "");
amountOut = IERC20Upgradeable(tokenOut).balanceOf(receiver) - balanceOut;
return (amountDelta, amountOut);
}
function swapV2ExactOut(
address tokenIn,
address tokenOut,
uint256 amountInMax,
uint256 amountOut,
address poolAddress,
address payer,
address receiver
) internal {
require(poolAddress != address(0), "SwapX: invalid pool address");
require(amountOut > 0, "SwapX: amout out is zero");
bool zeroForOne = tokenIn < tokenOut;
(uint256 r0, uint256 r1,) = IUniswapV2Pair(poolAddress).getReserves();
(uint256 reserveIn, uint256 reserveOut) = zeroForOne ? (r0, r1) : (r1, r0);
uint256 amountIn = _getAmountIn(amountOut, reserveIn, reserveOut, _getFee(tokenIn, tokenOut, poolAddress));
require(amountIn <= amountInMax, "slippage");
Common.pay(tokenIn, payer, poolAddress, amountIn);
(uint256 amount0, uint256 amount1) = zeroForOne ? (uint256(0), amountOut) : (amountOut, 0);
IUniswapV2Pair(poolAddress).swap(amount0, amount1, receiver, "");
}
function _getFee(address tokenIn, address tokenOut, address pool) internal pure returns (uint256) {
if (pool == _getPoolAddr(Constants.PANCAKE_V2_FACTORY, Constants.PANCAKE_V2_CODE_HASH, tokenIn, tokenOut)) {
return 25;
} else {
return 30;
}
}
function _getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut, uint256 fee)
internal
pure
returns (uint256)
{
// uint amountInWithFee = amountIn.mul(997);
// uint numerator = amountInWithFee.mul(reserveOut);
// uint denominator = reserveIn.mul(1000).add(amountInWithFee);
// amountOut = numerator / denominator;
uint256 amountInWithFee = amountIn * (10000 - fee);
uint256 numerator = amountInWithFee * reserveOut;
uint256 denominator = reserveIn * 10000 + amountInWithFee;
uint256 amountOut = numerator / denominator;
return amountOut;
}
function _getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut, uint256 fee)
internal
pure
returns (uint256)
{
// uint numerator = reserveIn.mul(amountOut).mul(1000);
// uint denominator = reserveOut.sub(amountOut).mul(997);
// amountIn = (numerator / denominator).add(1);
uint256 numerator = reserveIn * amountOut * 10000;
uint256 denominator = (reserveOut - amountOut) * (10000 - fee);
uint256 amountIn = numerator / denominator + 1;
return amountIn;
}
function _getPoolAddr(address factory, bytes32 initCodeHash, address tokenA, address tokenB)
internal
pure
returns (address pair)
{
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
// init code hash
initCodeHash
)
)
)
)
);
}
}
contracts/extLib/UniV3Lib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Upgradeable} from "../contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable} from "../contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IUniswapV3Pool} from "../interfaces/IUniswapV3Pool.sol";
import {CallbackValidation} from "../libs/CallbackValidation.sol";
import {Path} from "../libs/Path.sol";
import {PoolAddress} from "../libs/PoolAddress.sol";
import {SafeCast} from "../libs/SafeCast.sol";
import {Common} from "./common.sol";
import {Constants} from "./constants.sol";
library UniV3Lib {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeCast for *;
using Path for bytes;
struct ExactInputSingleParams {
address factoryAddress;
address poolAddress;
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
struct SwapCallbackData {
bytes path;
address payer;
address payerOrigin;
}
function swap(address payer, address receiver, address payerOrigin, uint256 amountIn, Common.SwapDesc memory desc)
external
returns (uint256)
{
uint256 amountOut = exactInputInternal(
desc.poolAddress,
amountIn,
receiver,
SwapCallbackData({
path: abi.encodePacked(desc.tokenIn, desc.fee, desc.tokenOut), payer: payer, payerOrigin: payerOrigin
})
);
return amountOut;
}
function swapV3ExactIn(ExactInputSingleParams memory params) internal returns (uint256 amountOut) {
amountOut = exactInputInternal(
params.poolAddress,
params.amountIn,
params.recipient,
SwapCallbackData({
path: abi.encodePacked(params.tokenIn, params.fee, params.tokenOut),
payer: msg.sender,
payerOrigin: msg.sender
})
);
}
/// V3: Performs a single exact input swap
function exactInputInternal(address poolAddress, uint256 amountIn, address recipient, SwapCallbackData memory data)
internal
returns (uint256 amountOut)
{
// allow swapping to the router address with address 0
if (recipient == address(0)) recipient = address(this);
(address tokenIn, address tokenOut,) = data.path.decodeFirstPool();
bool zeroForOne = tokenIn < tokenOut;
(int256 amount0, int256 amount1) = IUniswapV3Pool(poolAddress)
.swap(
recipient,
zeroForOne,
amountIn.toInt256(),
zeroForOne ? Constants.MIN_SQRT_RATIO + 1 : Constants.MAX_SQRT_RATIO - 1,
abi.encode(data)
);
return uint256(-(zeroForOne ? amount1 : amount0));
}
}
contracts/extLib/UniV4Lib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Upgradeable} from "../contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable} from "../contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "../interfaces/IV4PoolManager.sol";
import "../interfaces/IV4Router.sol";
import {Locker} from "../libs/Locker.sol";
import {SafeCast} from "../libs/SafeCast.sol";
import {Common} from "./common.sol";
import {Constants} from "./constants.sol";
library UniV4Lib {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeCast for *;
enum CMD {
SWAP_V4_EXACT_IN,
SWAP_V4_EXACT_OUT
}
error ContractLocked();
modifier isNotLocked(address payer) {
if (Locker.get() != address(0)) revert ContractLocked();
require(payer == address(this) || payer == tx.origin || payer == msg.sender, "not valid payer in uniV4");
Locker.set(payer);
_;
Locker.set(address(0));
}
function _getLocker() internal view returns (address) {
return Locker.get();
}
function _msgSender() internal view returns (address) {
return _getLocker();
}
function swap(address payer, address receiver, address payerOrigin, uint256 amountIn, Common.SwapDesc memory desc)
internal
returns (uint256)
{
IV4Router.PathKey[] memory path = new IV4Router.PathKey[](1);
path[0] = IV4Router.PathKey(desc.tokenOut, desc.fee, desc.tickSpacing, desc.hooks, desc.hookData);
(, uint256 amountOut) = swapV4ExactIn(
IV4Router.ExactInputParams({
currencyIn: desc.tokenIn,
currencyOut: desc.tokenOut,
amountIn: uint128(amountIn),
amountOutMinimum: 0,
path: path
}),
receiver,
payerOrigin,
payer
);
return amountOut;
}
function swapV4ExactIn(
IV4Router.ExactInputParams memory params,
address recipient,
address payerOrigin,
address payer
) public isNotLocked(payer) returns (uint256 amountIn, uint256 amountOut) {
bytes memory data = abi.encode(CMD.SWAP_V4_EXACT_IN, abi.encode(params, recipient, payerOrigin));
bytes memory result = IV4PoolManager(Constants.poolManager).unlock(data);
return abi.decode(result, (uint256, uint256));
}
// function swapV4ExactOut(IV4Router.ExactOutputParams memory params, address recipient, address payer)
// public
// isNotLocked(payer)
// returns (uint256 amountIn, uint256 amountOut)
// {
// bytes memory data = abi.encode(CMD.SWAP_V4_EXACT_OUT, abi.encode(params, recipient));
// bytes memory result = IV4PoolManager(Constants.poolManager).unlock(data);
// return abi.decode(result, (uint256, uint256));
// }
function unlockCallback(bytes memory data) external returns (bytes memory) {
require(msg.sender == address(IV4PoolManager(Constants.poolManager)), "UniV4Lib: not pool manager");
(CMD cmd, bytes memory params) = abi.decode(data, (CMD, bytes));
// 击穿问题
// pool.token0 = 1ether, token1 = 10 ether
// amountIN = 100 ether, expectToken = 10 ether, actualAmountIn = 1 ether, left = 99 ether
// v3: refund 99 ether to user
// v4: swap() => +10 ether, -1 ether
// v4: take() => +10 ether => user
// v4: settle() => -1 ether from user
// v4: left 99 ether => refund
if (cmd == CMD.SWAP_V4_EXACT_IN) {
(IV4Router.ExactInputParams memory params, address recipient, address payerOrigin) =
abi.decode(params, (IV4Router.ExactInputParams, address, address));
_swapV4ExactIn(params);
address currencyOut = params.path[params.path.length - 1].intermediateCurrency;
uint256 amountOut = _getFullCredit(currencyOut);
_take(currencyOut, recipient, amountOut);
uint256 amountIn = _getFullDebt(params.currencyIn);
_settle(params.currencyIn, _msgSender(), amountIn);
_refund(params.currencyIn, payerOrigin);
return abi.encode(amountIn, amountOut);
} else {
revert("no cmd");
}
}
function _swapV4ExactIn(IV4Router.ExactInputParams memory params) private {
unchecked {
// Caching for gas savings
uint256 pathLength = params.path.length;
uint128 amountOut;
address currencyIn = params.currencyIn;
uint128 amountIn = params.amountIn;
IV4Router.PathKey memory pathKey;
for (uint256 i = 0; i < pathLength; i++) {
pathKey = params.path[i];
(IV4PoolManager.PoolKey memory poolKey, bool zeroForOne) = getPoolAndSwapDirection(pathKey, currencyIn);
// The output delta will always be positive, except for when interacting with certain hook pools
amountOut = _swap(poolKey, zeroForOne, -int256(uint256(amountIn)), pathKey.hookData).toUint128();
amountIn = amountOut;
currencyIn = pathKey.intermediateCurrency;
}
}
}
function _swap(
IV4PoolManager.PoolKey memory poolKey,
bool zeroForOne,
int256 amountSpecified,
bytes memory hookData
) private returns (int128 reciprocalAmount) {
// for protection of exactOut swaps, sqrtPriceLimit is not exposed as a feature in this contract
unchecked {
BalanceDelta delta = IV4PoolManager(Constants.poolManager)
.swap(
poolKey,
IV4PoolManager.SwapParams(
zeroForOne,
amountSpecified,
zeroForOne ? Constants.MIN_SQRT_RATIO + 1 : Constants.MAX_SQRT_RATIO - 1
),
hookData
);
reciprocalAmount = (zeroForOne == amountSpecified < 0) ? delta.amount1() : delta.amount0();
}
}
function _computeSlot(address target, address currency) internal pure returns (bytes32 hashSlot) {
assembly ("memory-safe") {
mstore(0, and(target, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(32, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
hashSlot := keccak256(0, 64)
}
}
/// @notice Obtain the full amount owed by this contract (negative delta)
/// @param currency Currency to get the delta for
/// @return amount The amount owed by this contract as a uint256
function _getFullDebt(address currency) internal view returns (uint256 amount) {
bytes32 slot = _computeSlot(address(this), currency);
int256 _amount = int256(uint256(IV4PoolManager(Constants.poolManager).exttload(slot)));
// If the amount is positive, it should be taken not settled.
if (_amount > 0) revert("v4 full debt amount error");
// Casting is safe due to limits on the total supply of a pool
amount = uint256(-_amount);
}
/// @notice Obtain the full credit owed to this contract (positive delta)
/// @param currency Currency to get the delta for
/// @return amount The amount owed to this contract as a uint256
function _getFullCredit(address currency) internal view returns (uint256 amount) {
bytes32 slot = _computeSlot(address(this), currency);
int256 _amount = int256(uint256(IV4PoolManager(Constants.poolManager).exttload(slot)));
// If the amount is negative, it should be settled not taken.
if (_amount < 0) revert("v4 full credit amount error");
amount = uint256(_amount);
}
function _settle(address currency, address payer, uint256 amount) internal {
IV4PoolManager(Constants.poolManager).sync(currency);
if (currency == address(0)) {
Common.tryUnwrap(amount);
IV4PoolManager(Constants.poolManager).settle{value: amount}();
} else {
_pay(currency, payer, amount);
IV4PoolManager(Constants.poolManager).settle();
}
}
function _refund(address currency, address receiver) internal {
if (currency == address(0)) {
uint256 amount = Common.getBalance(Constants.WETH, address(this));
if (amount == 0) return;
Common.tryUnwrap(amount);
(bool success,) = receiver.call{value: amount}("");
require(success, "ERR_INSUFFICIENT_BALANCE: refund ETH error");
} else {
uint256 amount = IERC20Upgradeable(currency).balanceOf(address(this));
if (amount == 0) return;
IERC20Upgradeable(currency).safeTransfer(receiver, amount);
}
}
// WETH in, receive WETH from outside
function _pay(address currency, address payer, uint256 amount) internal {
if (amount == 0) return;
if (payer == address(this)) {
IERC20Upgradeable(currency).safeTransfer(Constants.poolManager, amount);
} else {
IERC20Upgradeable(currency).safeTransferFrom(payer, Constants.poolManager, amount);
}
}
// WETH out, pay WETH to user
function _take(address currency, address recipient, uint256 amount) internal {
if (amount == 0) return;
IV4PoolManager(Constants.poolManager).take(currency, address(this), amount);
if (currency == address(0)) {
Common.wrapTo(amount, recipient);
} else {
IERC20Upgradeable(currency).safeTransfer(recipient, amount);
}
}
function getPoolAndSwapDirection(IV4Router.PathKey memory params, address currencyIn)
internal
pure
returns (IV4PoolManager.PoolKey memory poolKey, bool zeroForOne)
{
address currencyOut = params.intermediateCurrency;
(address currency0, address currency1) =
currencyIn < currencyOut ? (currencyIn, currencyOut) : (currencyOut, currencyIn);
zeroForOne = currencyIn == currency0;
poolKey = IV4PoolManager.PoolKey(currency0, currency1, params.fee, params.tickSpacing, params.hooks);
}
}
contracts/extLib/common.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IWETH} from "../interfaces/IWETH.sol";
import {Constants} from "./Constants.sol";
library Common {
using SafeERC20Upgradeable for IERC20Upgradeable;
enum SwapType {
V2_EXACT_IN,
V3_EXACT_IN,
V4_EXACT_IN,
OKX_EXACT_IN
}
struct SwapDesc {
SwapType swapType;
address tokenIn;
address tokenOut;
address poolAddress;
uint24 fee; // V3, V4
int24 tickSpacing; // V4
address hooks; // V4
bytes hookData; // V4
}
function pay(address token, address payer, address recipient, uint256 value) internal {
if (payer == recipient) return;
if (token == address(0)) {
(bool success,) = recipient.call{value: value}("");
require(success, "SwapX: send ETH out error");
} else if (payer == address(this)) {
IERC20Upgradeable(token).safeTransfer(recipient, value);
} else {
IERC20Upgradeable(token).safeTransferFrom(payer, recipient, value);
}
}
function getAssetTo(SwapDesc[] memory descs, uint256 i) internal view returns (address) {
SwapDesc memory desc = descs[i];
if (desc.swapType == SwapType.V2_EXACT_IN) {
return desc.poolAddress;
} else {
return address(this);
}
}
function getMiddleReceiver(SwapDesc[] memory descs, uint256 i, address receiver) internal view returns (address) {
if (i == descs.length - 1) {
return receiver;
}
SwapDesc memory desc = descs[i + 1];
if (desc.swapType == SwapType.V2_EXACT_IN) {
return desc.poolAddress;
} else if (desc.swapType == SwapType.V3_EXACT_IN) {
return address(this);
} else if (desc.swapType == SwapType.V4_EXACT_IN) {
return address(this);
} else {
return address(this);
}
}
function claim(address token, address payer, address recipient, uint256 value) internal {
require(payer != address(this), "payer is address this");
pay(token, payer, recipient, value);
}
function wrap(uint256 amount) internal {
if (amount == 0) return;
require(address(this).balance >= amount, "wrap failed");
IWETH(Constants.WETH).deposit{value: amount}();
}
function unwrap(uint256 amount) internal {
if (amount == 0) return;
require(IWETH(Constants.WETH).balanceOf(address(this)) >= amount, "unwrap failed");
IWETH(Constants.WETH).withdraw(amount);
}
function tryUnwrap(uint256 amount) internal {
if (amount == 0) return;
uint256 balance = IWETH(Constants.WETH).balanceOf(address(this));
if (balance >= amount) {
IWETH(Constants.WETH).withdraw(amount);
}
}
// only used in snapshot, ETH in & Token out. or Token in & ETH out. no WETH out case.
function tryGetBalance(address token, address user) internal view returns (uint256) {
if (token == address(0) || token == Constants.WETH) {
return address(user).balance;
} else {
return IERC20Upgradeable(token).balanceOf(user);
}
}
function wrapTo(uint256 amount, address to) internal {
wrap(amount);
if (to != address(this)) {
IWETH(Constants.WETH).transfer(to, amount);
}
}
function unwrapTo(uint256 amount, address to) internal {
unwrap(amount);
if (to != address(this)) {
(bool s,) = payable(address(to)).call{value: amount}("");
require(s, "unwrapTo failed");
}
}
function getBalance(address token, address user) internal view returns (uint256) {
if (token == address(0)) {
return address(user).balance;
} else {
return IERC20Upgradeable(token).balanceOf(user);
}
}
function wrapToken(address token) internal returns (address) {
if (token == address(0)) {
return Constants.WETH;
} else {
return token;
}
}
function isNative(address token) internal pure returns (bool) {
return token == address(0) || token == Constants.WETH;
}
}
contracts/extLib/constants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Constants {
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
address internal constant PANCAKE_V3_FACTORY = 0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865;
address internal constant PANCAKE_V3_DEPLOYER = 0x41ff9AA7e16B8B1a8a8dc4f0eFacd93D02d071c9;
address internal constant UNISWAP_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
address internal constant SUSHISWAP_V3_FACTORY = 0xbACEB8eC6b9355Dfc0269C18bac9d6E2Bdc29C4F;
bytes32 internal constant UNISWAP_V3_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
bytes32 internal constant PANCAKE_V3_CODE_HASH = 0x6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e2;
address internal constant UNISWAP_V2_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address internal constant PANCAKE_V2_FACTORY = 0x1097053Fd2ea711dad45caCcc45EfF7548fCB362;
address internal constant SUSHISWAP_V2_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac;
bytes32 internal constant UNISWAP_V2_CODE_HASH = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f;
bytes32 internal constant PANCAKE_V2_CODE_HASH = 0x57224589c67f3f30a6b0d7a1b54cf3153ab84563bc609ef41dfb34f8b2974d2d;
address internal constant ETH = address(0);
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address internal constant poolManager = address(payable(0x000000000004444c5dc75cB358380D2e3dE08A90));
}
contracts/interfaces/IFourTokenManager.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
interface IFourTokenManager {
// v1
function purchaseTokenAMAP(address token, uint256 funds, uint256 minAmount) external payable;
// v2
function buyTokenAMAP(address token, address to, uint256 funds, uint256 minAmount) external payable;
function sellToken(address token, uint256 amount) external;
function sellToken(
uint256 origin,
address token,
uint256 amount,
uint256 minFunds,
uint256 feeRate,
address feeRecipient
) external;
function sellToken(
uint256 origin,
address token,
address from,
uint256 amount,
uint256 minFunds,
uint256 feeRate,
address feeRecipient
) external;
}
contracts/interfaces/IOKXDexRouter.sol
interface IOKXDexRouter {
struct BaseRequest {
uint256 fromToken;
address toToken;
uint256 fromTokenAmount;
uint256 minReturnAmount;
uint256 deadLine;
}
struct RouterPath {
address[] mixAdapters;
address[] assetTo;
uint256[] rawData;
bytes[] extraData;
uint256 fromToken;
}
struct PMMSwapRequest {
uint256 pathIndex;
address payer;
address fromToken;
address toToken;
uint256 fromTokenAmountMax;
uint256 toTokenAmountMax;
uint256 salt;
uint256 deadLine;
bool isPushOrder;
bytes extension;
}
// // address marketMaker;
// // uint256 subIndex;
// // bytes signature;
// // uint256 source; 1byte type + 1byte bool(reverse) + 0...0 + 20 bytes address
// function smartSwapByInvest(
// BaseRequest calldata baseRequest,
// uint256[] calldata batchesAmount,
// RouterPath[][] calldata batches,
// PMMSwapRequest[] calldata extraData,
// address to
// ) external payable;
function uniswapV3SwapTo(uint256 receiver, uint256 amount, uint256 minReturn, uint256[] calldata pools)
external
payable
returns (uint256 returnAmount);
function smartSwapTo(
uint256 orderId,
address receiver,
BaseRequest calldata baseRequest,
uint256[] calldata batchesAmount,
RouterPath[][] calldata batches,
PMMSwapRequest[] calldata extraData
) external payable;
function unxswapTo(
uint256 srcToken,
uint256 amount,
uint256 minReturn,
address receiver,
// solhint-disable-next-line no-unused-vars
bytes32[] calldata pools
) external payable returns (uint256 returnAmount);
function unxswapByOrderId(
uint256 srcToken,
uint256 amount,
uint256 minReturn,
// solhint-disable-next-line no-unused-vars
bytes32[] calldata pools
)
external
payable
returns (uint256 returnAmount);
function smartSwapByOrderId(
uint256 orderId,
BaseRequest calldata baseRequest,
uint256[] calldata batchesAmount,
RouterPath[][] calldata batches,
PMMSwapRequest[] calldata extraData
) external payable returns (uint256 returnAmount);
function dagSwapTo(uint256 orderId, address receiver, BaseRequest calldata baseRequest, RouterPath[] calldata paths)
external
payable
returns (uint256 returnAmount);
function dagSwapByOrderId(uint256 orderId, BaseRequest calldata baseRequest, RouterPath[] calldata paths)
external
payable
returns (uint256 returnAmount);
}
contracts/interfaces/IPancakeV3SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IPancakeV3PoolActions#swap
/// @notice Any contract that calls IPancakeV3PoolActions#swap must implement this interface
interface IPancakeV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IPancakeV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a PancakeV3Pool deployed by the canonical PancakeV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IPancakeV3PoolActions#swap call
function pancakeV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}
contracts/interfaces/IUniswapV2Pair.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
contracts/interfaces/IUniswapV3Pool.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IUniswapV3Pool {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
}
contracts/interfaces/IUniswapV3SwapCallback.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}
contracts/interfaces/IV4PoolManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {BalanceDelta} from "../libs/BalanceDelta.sol";
/// @notice Interface for the PoolManager
interface IV4PoolManager {
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
address currency0;
/// @notice The higher currency of the pool, sorted numerically
address currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
address hooks;
}
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error addressNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
bytes32 indexed id,
address indexed currency0,
address indexed currency1,
uint24 fee,
int24 tickSpacing,
address hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
bytes32 indexed id,
address indexed sender,
int24 tickLower,
int24 tickUpper,
int256 liquidityDelta,
bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
bytes32 indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(bytes32 indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(address currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(address currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(address currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}
contracts/interfaces/IV4Router.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IV4Router
/// @notice Interface for the V4Router contract
interface IV4Router {
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
address currency0;
/// @notice The higher currency of the pool, sorted numerically
address currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
address hooks;
}
// BNB-USDT-trump:
// tokenIn: BNB
// tokenOut: trump
// pool1.intermediateCurrency: USDT
// pool1.fee: 3000
// pool1.tickSpacing: 60
// pool1.hooks: 0x0000000000000000000000000000000000000000
// pool1.hookData: 0x
// pool2.intermediateCurrency: trump
// pool2.fee: 3000
// pool2.tickSpacing: 60
// pool2.hooks: 0x0000000000000000000000000000000000000000
// pool2.hookData: 0x
// tokenOut: USDT
struct PathKey {
address intermediateCurrency;
uint24 fee;
int24 tickSpacing;
address hooks;
bytes hookData;
}
/// @notice Emitted when an exactInput swap does not receive its minAmountOut
/// @notice Emitted trying to settle a positive delta.
error DeltaNotPositive(address currency);
/// @notice Emitted trying to take a negative delta.
error DeltaNotNegative(address currency);
/// @notice Emitted when the contract does not have enough balance to wrap or unwrap.
error InsufficientBalance();
error V4TooLittleReceived(uint256 minAmountOutReceived, uint256 amountReceived);
/// @notice Emitted when an exactOutput is asked for more than its maxAmountIn
error V4TooMuchRequested(uint256 maxAmountInRequested, uint256 amountRequested);
/// @notice Parameters for a single-hop exact-input swap
struct ExactInputSingleParams {
PoolKey poolKey;
bool zeroForOne;
uint128 amountIn;
uint128 amountOutMinimum;
bytes hookData;
}
/// @notice Parameters for a multi-hop exact-input swap
struct ExactInputParams {
address currencyIn;
address currencyOut;
PathKey[] path;
uint128 amountIn;
uint128 amountOutMinimum;
}
/// @notice Parameters for a single-hop exact-output swap
struct ExactOutputSingleParams {
PoolKey poolKey;
bool zeroForOne;
uint128 amountOut;
uint128 amountInMaximum;
bytes hookData;
}
/// @notice Parameters for a multi-hop exact-output swap
struct ExactOutputParams {
address currencyIn;
address currencyOut;
PathKey[] path;
uint128 amountOut;
uint128 amountInMaximum;
}
}
contracts/interfaces/IWETH.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "../contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IWETH is IERC20Upgradeable {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
contracts/libs/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "./SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
contracts/libs/BytesLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity >=0.5.0 <0.9.0;
library BytesLib {
function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3, "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toInt24(bytes memory _bytes, uint256 _start) internal pure returns (int24) {
require(_start + 3 >= _start, "UO"); // uint24 overflow
require(_bytes.length >= _start + 3, "UOB"); // uint24 out of bounds
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
require(tempUint <= uint24(type(int24).max), "IO"); // int24 overflow
return int24(tempUint);
}
}
contracts/libs/CallbackValidation.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
import "../interfaces/IUniswapV3Pool.sol";
import "./PoolAddress.sol";
/// @notice Provides validation for callbacks from Uniswap V3 Pools
library CallbackValidation {
/// @notice Returns the address of a valid Uniswap V3 Pool
/// @param factory The contract address of the Uniswap V3 factory
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The V3 pool contract address
function verifyCallback(address factory, address tokenA, address tokenB, uint24 fee, int24 tickSpacing)
internal
view
returns (IUniswapV3Pool pool)
{
return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee, tickSpacing));
}
/// @notice Returns the address of a valid Uniswap V3 Pool
/// @param factory The contract address of the Uniswap V3 factory
/// @param poolKey The identifying key of the V3 pool
/// @return pool The V3 pool contract address
function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey)
internal
view
returns (IUniswapV3Pool pool)
{
pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
require(msg.sender == address(pool), "CallbackValidation: sender is not the pool");
}
}
contracts/libs/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
contracts/libs/Locker.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library Locker {
// The slot holding the locker state, transiently. bytes32(uint256(keccak256("LockedBy")) - 1)
bytes32 constant LOCKED_BY_SLOT = 0x0aedd6bde10e3aa2adec092b02a3e3e805795516cda41f27aa145b8f300af87a;
function set(address locker) internal {
assembly {
tstore(LOCKED_BY_SLOT, locker)
}
}
function get() internal view returns (address locker) {
assembly {
locker := tload(LOCKED_BY_SLOT)
}
}
}
contracts/libs/Path.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import "./BytesLib.sol";
/// @title Functions for manipulating path data for multihop swaps
library Path {
using BytesLib for bytes;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint256 private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev The offset of an encoded pool key
uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
/// @dev The minimum length of an encoding that contains 2 or more pools
uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
/// @notice Returns true iff the path contains two or more pools
/// @param path The encoded swap path
/// @return True if path contains two or more pools, otherwise false
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}
/// @notice Returns the number of pools in the path
/// @param path The encoded swap path
/// @return The number of pools in the path
function numPools(bytes memory path) internal pure returns (uint256) {
// Ignore the first token address. From then on every fee and token offset indicates a pool.
return ((path.length - ADDR_SIZE) / NEXT_OFFSET);
}
/// @notice Decodes the first pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return tokenB The second token of the given pool
/// @return fee The fee level of the pool
function decodeFirstPool(bytes memory path) internal pure returns (address tokenA, address tokenB, uint24 fee) {
tokenA = path.toAddress(0);
fee = path.toUint24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}
function decodeFirstPoolAerodrome(bytes memory path)
internal
pure
returns (address tokenA, address tokenB, int24 tickSpacing)
{
tokenA = path.toAddress(0);
tickSpacing = path.toInt24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}
/// @notice Gets the segment corresponding to the first pool in the path
/// @param path The bytes encoded swap path
/// @return The segment containing all data necessary to target the first pool in the path
function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
return path.slice(0, POP_OFFSET);
}
/// @notice Skips a token + fee element from the buffer and returns the remainder
/// @param path The swap path
/// @return The remaining token + fee elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
}
contracts/libs/PoolAddress.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "./clones.sol";
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
address constant PANCAKE_V3_FACTORY = 0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865;
address constant PANCAKE_V3_DEPLOYER = 0x41ff9AA7e16B8B1a8a8dc4f0eFacd93D02d071c9;
address constant UNISWAP_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
address constant SUSHISWAP_V3_FACTORY = 0xbACEB8eC6b9355Dfc0269C18bac9d6E2Bdc29C4F;
bytes32 constant UNISWAP_V3_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
bytes32 constant PANCAKE_V3_CODE_HASH = 0x6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e2;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
int24 tickSpacing;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(address tokenA, address tokenB, uint24 fee, int24 tickSpacing)
internal
pure
returns (PoolKey memory)
{
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee, tickSpacing: tickSpacing});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1, "PoolAddress: token0 > token1");
if (factory == address(PANCAKE_V3_FACTORY)) {
// pancakeswap v3(mainnet)
bytes32 pubKey = keccak256(
abi.encodePacked(
hex"ff",
PANCAKE_V3_DEPLOYER,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
PANCAKE_V3_CODE_HASH
)
);
// bytes32 to address:
assembly {
mstore(0x0, pubKey)
pool := mload(0x0)
}
} else if (factory == address(UNISWAP_V3_FACTORY)) {
// uniswap v3(mainnet)
bytes32 pubKey = keccak256(
abi.encodePacked(
hex"ff",
UNISWAP_V3_FACTORY,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
UNISWAP_V3_CODE_HASH
)
);
// bytes32 to address:
assembly {
mstore(0x0, pubKey)
pool := mload(0x0)
}
} else if (factory == address(SUSHISWAP_V3_FACTORY)) {
// sushiswap v3(mainnet)
bytes32 pubKey = keccak256(
abi.encodePacked(
hex"ff",
SUSHISWAP_V3_FACTORY,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
UNISWAP_V3_CODE_HASH
)
);
// bytes32 to address:
assembly {
mstore(0x0, pubKey)
pool := mload(0x0)
}
}
}
}
contracts/libs/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}
contracts/libs/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
}
contracts/libs/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= toUint256(MAX_TICK), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
function toUint256(int24 value) public pure returns (uint256) {
require(value >= 0, "Input value is negative");
int256 convertedInt = int256(value);
return uint256(convertedInt);
}
}
contracts/libs/UniswapV2Library.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "../interfaces/IUniswapV2Pair.sol";
import "./SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint256;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
if (factory == address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f)) {
bytes32 pubKey = keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // uniswap init code hash
)
);
assembly {
mstore(0x0, pubKey)
pair := mload(0x0)
}
} else if (factory == address(0x71524B4f93c58fcbF659783284E38825f0622859)) {
bytes32 pubKey = keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // sushiswap init code hash
)
);
assembly {
mstore(0x0, pubKey)
pair := mload(0x0)
}
} else if (factory == address(0x1097053Fd2ea711dad45caCcc45EfF7548fCB362)) {
bytes32 pubKey = keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"57224589c67f3f30a6b0d7a1b54cf3153ab84563bc609ef41dfb34f8b2974d2d" // pancakeswap init code hash
)
);
assembly {
mstore(0x0, pubKey)
pair := mload(0x0)
}
}
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB)
internal
view
returns (uint256 reserveA, uint256 reserveB)
{
(address token0,) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) internal pure returns (uint256 amountB) {
require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT");
require(reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY");
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut)
internal
pure
returns (uint256 amountOut)
{
require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY");
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
internal
pure
returns (uint256 amountIn)
{
require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY");
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint256 amountIn, address[] memory path)
internal
view
returns (uint256[] memory amounts)
{
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint256 amountOut, address[] memory path)
internal
view
returns (uint256[] memory amounts)
{
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
contracts/libs/clones.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address master) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt, address deployer)
internal
pure
returns (address predicted)
{
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"contracts/SwapX.sol": {
"OkxLib": "0x420452021764ff3027598226ff69406be719c7c4",
"UniV2Lib": "0xc5146d997cc45958ab8b531dc5f590b430350968",
"UniV3Lib": "0x929635c71a613cc2de013e2bd57a37a1eae4ccad",
"UniV4Lib": "0x04b23ceb6a8b0b5ab5e2ddff59a75087b1ddfee0"
}
},
"optimizer": {
"runs": 10,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@openzeppelin/=node_modules/@openzeppelin/",
"eth-gas-reporter/=node_modules/eth-gas-reporter/",
"hardhat/=node_modules/hardhat/",
"solidity-code-metrics/=node_modules/solidity-code-metrics/",
"forge-std/=lib/forge-std/src/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.