Проверенный контрактЧастичноеMIT
DelegationFarm
Адрес0x0628f18113e478d22fd3c8efd27e413889bd2d52
- Баланс
0 ETH
- Транзакций
38
- Компилятор
solc 0.8.24
- Тот же код
ещё 1 контракт
Подробности
- Компилятор
- solc 0.8.24+commit.e11b9ed9
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Версия EVM
- paris
- Через IR
- да
- Лицензия
- MIT
- Совпадение
- Частичноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 25 987 287
- Транзакция создания
- 0xad961f6fe1…a00e8178e6
- Основная копия (больше всего транзакций)
- 0xd96946fe…76fd2691
27 файлов
- contracts/delegation/DelegationFarm.solглавный21,23 КБ
- contracts/delegation/interfaces/IDelegationStrategy.sol1,86 КБ
- contracts/delegation/interfaces/IDelegationStrategyInfo.sol3,24 КБ
- contracts/interfaces/IConstants.sol2,3 КБ
- contracts/interfaces/IFarm.sol360 Б
- contracts/interfaces/IFarmEvent.sol2,33 КБ
- contracts/interfaces/IZap.sol1,23 КБ
- contracts/interfaces/external/IERC20Querier.sol333 Б
- contracts/interfaces/external/IWETH9.sol363 Б
- contracts/interfaces/uniswapV3/INonfungiblePositionManager.sol6,41 КБ
- contracts/interfaces/uniswapV3/IUniswapV3Pool.sol2,48 КБ
- contracts/libraries/uniswapV3/FixedPoint96.sol380 Б
- contracts/libraries/uniswapV3/FullMath.sol5,06 КБ
- contracts/libraries/uniswapV3/LiquidityAmounts.sol7,19 КБ
- contracts/libraries/uniswapV3/TickMath.sol4,4 КБ
- contracts/libraries/uniswapV3/TransferHelper.sol2,56 КБ
- node_modules/@openzeppelin/contracts/access/AccessControl.sol8,23 КБ
- node_modules/@openzeppelin/contracts/access/IAccessControl.sol2,92 КБ
- node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol3,13 КБ
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2,74 КБ
- node_modules/@openzeppelin/contracts/utils/Context.sol962 Б
- node_modules/@openzeppelin/contracts/utils/Strings.sol2,78 КБ
- node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol987 Б
- node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol853 Б
- node_modules/@openzeppelin/contracts/utils/math/Math.sol12,79 КБ
- node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol1,26 КБ
- node_modules/@openzeppelin/contracts/utils/structs/EnumerableSet.sol12,96 КБ
contracts/delegation/DelegationFarm.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import "../libraries/uniswapV3/LiquidityAmounts.sol";
import "../libraries/uniswapV3/TickMath.sol";
import "../interfaces/IFarmEvent.sol";
import "../interfaces/IFarm.sol";
import "./interfaces/IDelegationStrategy.sol";
import "./interfaces/IDelegationStrategyInfo.sol";
import "../interfaces/uniswapV3/INonfungiblePositionManager.sol";
import "../interfaces/uniswapV3/IUniswapV3Pool.sol";
import "../interfaces/IConstants.sol";
import "../interfaces/IZap.sol";
import "../interfaces/external/IWETH9.sol";
import "../libraries/uniswapV3/TransferHelper.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
interface IPositionManagerApproval {
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
/// @dev Delegation-aware Farm — rewards push directly to users, no claimReward pipeline.
contract DelegationFarm is IFarmEvent, IFarm, AccessControl, ReentrancyGuard {
using EnumerableSet for EnumerableSet.AddressSet;
receive() external payable {}
IConstants public Constants;
IZap public Zap;
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
uint24 public constant FEE_DENOMINATOR = 1000000;
uint24 public feeNumerator;
uint24 public maxFeeNumerator = 800_000;
uint24 public constant SHARE_DENOMINATOR = 1000000;
EnumerableSet.AddressSet private registeredStrategies;
EnumerableSet.AddressSet private userList;
mapping(address strategy => EnumerableSet.AddressSet) private strategyUserList;
struct DepositInfo {
uint128 increasedLiquidity;
uint256 increasedShare;
uint256 increasedToken0Amount;
uint256 increasedToken1Amount;
uint256 sendBackToken0Amount;
uint256 sendBackToken1Amount;
uint256 feeToken0;
uint256 feeToken1;
}
event UserNftMinted(address indexed user, address indexed strategy, uint256 tokenId);
event StrategyRegistered(address indexed strategy, address indexed executor);
event StrategyUnregistered(address indexed strategy, address indexed executor);
modifier checkStrategyAndSharePercentage(address _strategyContract, uint256 _sharePercentage) {
_validateStrategy(_strategyContract);
require(0 < _sharePercentage && _sharePercentage <= SHARE_DENOMINATOR, "Invalid share percentage");
_;
}
constructor(address _constants, address _zap) {
require(_constants != address(0), "Constants address cannot be zero");
require(_zap != address(0), "Zap address cannot be zero");
Constants = IConstants(_constants);
Zap = IZap(_zap);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(EXECUTOR_ROLE, msg.sender);
}
function depositLiquidity(
address _strategyContract,
bool _isETH,
address _inputToken,
uint256 _inputAmount,
uint256 _swapInAmount,
uint256 _minimumSwapOutAmount
) public payable {
require(!_isETH || msg.value == _inputAmount, "msg.value != _inputAmount");
require(_isETH || msg.value == 0, "msg.value != 0");
bool hadPosition = IDelegationStrategyInfo(_strategyContract).userNftId(msg.sender) != 0;
uint256 _remainingInputTokenAmount = getTokenAmountAfterFee(_inputAmount);
if (!_isETH) {
TransferHelper.safeTransferFrom(_inputToken, msg.sender, address(this), _inputAmount);
TransferHelper.safeApprove(_inputToken, _strategyContract, _remainingInputTokenAmount);
}
DepositInfo memory depositInfo = executeDeposit(
_strategyContract, _isETH, _inputToken, _remainingInputTokenAmount, _swapInAmount, _minimumSwapOutAmount
);
userList.add(msg.sender);
strategyUserList[_strategyContract].add(msg.sender);
if (!hadPosition) {
uint256 newTokenId = IDelegationStrategyInfo(_strategyContract).userNftId(msg.sender);
emit UserNftMinted(msg.sender, _strategyContract, newTokenId);
}
emit DepositLiquidity(
_strategyContract,
msg.sender,
IDelegationStrategyInfo(_strategyContract).userNftId(msg.sender),
_isETH,
_inputToken,
_inputAmount,
0, // no share tracking
depositInfo.increasedLiquidity,
depositInfo.increasedShare,
depositInfo.increasedToken0Amount,
depositInfo.increasedToken1Amount,
depositInfo.sendBackToken0Amount,
depositInfo.sendBackToken1Amount,
depositInfo.feeToken0,
depositInfo.feeToken1
);
}
function depositUSDCForLiquidity(
address _strategyContract,
address _inputToken,
uint256 _inputAmount,
uint256 _swapInAmount,
uint256 _minimumSwapOutAmount
) public payable {
require(msg.value == 0, "msg.value != 0");
require(
_inputToken == Constants.USDC_ADDRESS() || _inputToken == Constants.USDCE_ADDRESS(),
"invalid USDC or USDC.e address"
);
(address token0, address token1) = getTokenAddresses(_strategyContract);
if (_inputToken == token0 || _inputToken == token1) {
depositLiquidity(_strategyContract, false, _inputToken, _inputAmount, _swapInAmount, _minimumSwapOutAmount);
} else {
bool hadPosition = IDelegationStrategyInfo(_strategyContract).userNftId(msg.sender) != 0;
uint256 _remainingInputTokenAmount = getTokenAmountAfterFee(_inputAmount);
TransferHelper.safeTransferFrom(_inputToken, msg.sender, address(this), _inputAmount);
TransferHelper.safeApprove(_inputToken, address(Zap), _remainingInputTokenAmount);
// token0 may be native ETH (address(0)); the zap can only output ERC20, so target WETH instead
bool _token0IsETH = token0 == address(0);
address _zapOutputToken = _token0IsETH ? Constants.WETH_ADDRESS() : token0;
uint256 depositInputAmount =
Zap.swapToken(false, _inputToken, _zapOutputToken, _remainingInputTokenAmount, address(this));
DepositInfo memory depositInfo;
if (_token0IsETH) {
// unwrap WETH -> native ETH; executeDeposit forwards it as msg.value via the isETH path
IWETH9(Constants.WETH_ADDRESS()).withdraw(depositInputAmount);
depositInfo = executeDeposit(
_strategyContract, true, address(0), depositInputAmount, _swapInAmount, _minimumSwapOutAmount
);
} else {
TransferHelper.safeApprove(token0, _strategyContract, depositInputAmount);
depositInfo = executeDeposit(
_strategyContract, false, token0, depositInputAmount, _swapInAmount, _minimumSwapOutAmount
);
}
userList.add(msg.sender);
strategyUserList[_strategyContract].add(msg.sender);
if (!hadPosition) {
uint256 newTokenId = IDelegationStrategyInfo(_strategyContract).userNftId(msg.sender);
emit UserNftMinted(msg.sender, _strategyContract, newTokenId);
}
emit DepositLiquidity(
_strategyContract,
msg.sender,
IDelegationStrategyInfo(_strategyContract).userNftId(msg.sender),
false,
_inputToken,
_inputAmount,
0, // no share tracking
depositInfo.increasedLiquidity,
depositInfo.increasedShare,
depositInfo.increasedToken0Amount,
depositInfo.increasedToken1Amount,
depositInfo.sendBackToken0Amount,
depositInfo.sendBackToken1Amount,
depositInfo.feeToken0,
depositInfo.feeToken1
);
}
}
function executeDeposit(
address _strategyContract,
bool _isETH,
address _inputToken,
uint256 _inputAmount,
uint256 _swapInAmount,
uint256 _minimumSwapOutAmount
) internal nonReentrant returns (DepositInfo memory depositInfo) {
(
depositInfo.increasedLiquidity,
depositInfo.increasedShare,
depositInfo.increasedToken0Amount,
depositInfo.increasedToken1Amount,
depositInfo.sendBackToken0Amount,
depositInfo.sendBackToken1Amount,
depositInfo.feeToken0,
depositInfo.feeToken1
) = IDelegationStrategy(_strategyContract).depositLiquidity{value: _isETH ? _inputAmount : 0}(
_isETH, msg.sender, _inputToken, _inputAmount, _swapInAmount, _minimumSwapOutAmount
);
}
function getTokenAddresses(address _strategyAddress) internal view returns (address token0, address token1) {
token0 = IDelegationStrategyInfo(_strategyAddress).token0Address();
token1 = IDelegationStrategyInfo(_strategyAddress).token1Address();
}
function withdrawLiquidity(address _strategyContract, uint256 _sharePercentage)
public
checkStrategyAndSharePercentage(_strategyContract, _sharePercentage)
nonReentrant
{
address _userAddress = msg.sender;
(address token0, address token1) = getTokenAddresses(_strategyContract);
uint256 userTokenId = IDelegationStrategyInfo(_strategyContract).userNftId(_userAddress);
(uint256 _remainingToken0Amount, uint256 _remainingToken1Amount, uint256 _feeToken0, uint256 _feeToken1) =
_withdrawAndChargeFee(_strategyContract, _sharePercentage, _userAddress);
if (token0 == address(0)) {
TransferHelper.safeTransferETH(_userAddress, _remainingToken0Amount);
} else {
TransferHelper.safeTransfer(token0, _userAddress, _remainingToken0Amount);
}
TransferHelper.safeTransfer(token1, _userAddress, _remainingToken1Amount);
if (IDelegationStrategyInfo(_strategyContract).userNftId(_userAddress) == 0) {
userList.remove(_userAddress);
strategyUserList[_strategyContract].remove(_userAddress);
}
emit WithdrawLiquidity(
_strategyContract,
_userAddress,
userTokenId,
_sharePercentage,
IDelegationStrategyInfo(_strategyContract).userNftId(_userAddress),
_remainingToken0Amount,
_remainingToken1Amount,
_feeToken0,
_feeToken1
);
}
function withdrawUSDCfromLiquidity(
address _strategyContract,
uint256 _sharePercentage,
address _outputToken,
uint256 _minimumToken0SwapOutAmount,
uint256 _minimumToken1SwapOutAmount
) public checkStrategyAndSharePercentage(_strategyContract, _sharePercentage) nonReentrant {
require(
_outputToken == Constants.USDC_ADDRESS() || _outputToken == Constants.USDCE_ADDRESS(),
"invalid USDC or USDC.e address"
);
address _userAddress = msg.sender;
(address token0, address token1) = getTokenAddresses(_strategyContract);
uint256 userTokenId = IDelegationStrategyInfo(_strategyContract).userNftId(_userAddress);
(uint256 _remainingToken0Amount, uint256 _remainingToken1Amount, uint256 _feeToken0, uint256 _feeToken1) =
_withdrawAndChargeFee(_strategyContract, _sharePercentage, _userAddress);
uint256 _outputAmount = _zapTokens(
_userAddress,
_outputToken,
token0,
_remainingToken0Amount,
token1,
_remainingToken1Amount,
_minimumToken0SwapOutAmount,
_minimumToken1SwapOutAmount
);
if (IDelegationStrategyInfo(_strategyContract).userNftId(_userAddress) == 0) {
userList.remove(_userAddress);
strategyUserList[_strategyContract].remove(_userAddress);
}
emit WithdrawUSDCfromLiquidity(
_strategyContract,
_userAddress,
userTokenId,
_sharePercentage,
IDelegationStrategyInfo(_strategyContract).userNftId(_userAddress),
_remainingToken0Amount,
_remainingToken1Amount,
_feeToken0,
_feeToken1,
_outputToken,
_outputAmount
);
}
function _withdrawAndChargeFee(address _strategyContract, uint256 _sharePercentage, address _userAddress)
internal
returns (uint256 _remainingToken0Amount, uint256 _remainingToken1Amount, uint256 _feeToken0, uint256 _feeToken1)
{
// The strategy collects the position fee BEFORE decreaseLiquidity and refunds it to the user
// in full (not charged the withdraw fee). userReceived* therefore carries the principal only,
// and _chargeFee charges only the principal. _feeToken0/1 is surfaced on the event below.
(uint256 _userReceivedToken0Amount, uint256 _userReceivedToken1Amount, uint256 _fee0, uint256 _fee1) =
IDelegationStrategy(_strategyContract).withdrawLiquidity(_userAddress, _sharePercentage);
_feeToken0 = _fee0;
_feeToken1 = _fee1;
(_remainingToken0Amount, _remainingToken1Amount) =
_chargeFee(_userReceivedToken0Amount, _userReceivedToken1Amount);
require(_remainingToken0Amount <= _userReceivedToken0Amount, "Fee charge error on token0");
require(_remainingToken1Amount <= _userReceivedToken1Amount, "Fee charge error on token1");
}
function _chargeFee(uint256 _userReceivedToken0Amount, uint256 _userReceivedToken1Amount)
internal
view
returns (uint256 _remainingToken0Amount, uint256 _remainingToken1Amount)
{
_remainingToken0Amount = getTokenAmountAfterFee(_userReceivedToken0Amount);
_remainingToken1Amount = getTokenAmountAfterFee(_userReceivedToken1Amount);
}
/// @return _outputAmount total amount of `_outputToken` the user received across both legs
/// (direct transfer when a side already equals `_outputToken`, plus zap output otherwise).
function _zapTokens(
address _userAddress,
address _outputToken,
address _token0,
uint256 _token0Amount,
address _token1,
uint256 _token1Amount,
uint256 _minimumToken0SwapOutAmount,
uint256 _minimumToken1SwapOutAmount
) internal returns (uint256 _outputAmount) {
if (_token0Amount > 0) {
if (_token0 == _outputToken) {
TransferHelper.safeTransfer(_token0, _userAddress, _token0Amount);
_outputAmount += _token0Amount;
} else if (_token0 == address(0)) {
_outputAmount += Zap.swapTokenWithMinimumOutput{value: _token0Amount}(
true, _token0, _outputToken, _token0Amount, _minimumToken0SwapOutAmount, _userAddress
);
} else {
TransferHelper.safeApprove(_token0, address(Zap), _token0Amount);
_outputAmount += Zap.swapTokenWithMinimumOutput(
false, _token0, _outputToken, _token0Amount, _minimumToken0SwapOutAmount, _userAddress
);
}
}
if (_token1Amount > 0) {
if (_token1 == _outputToken) {
TransferHelper.safeTransfer(_token1, _userAddress, _token1Amount);
_outputAmount += _token1Amount;
} else {
TransferHelper.safeApprove(_token1, address(Zap), _token1Amount);
_outputAmount += Zap.swapTokenWithMinimumOutput(
false, _token1, _outputToken, _token1Amount, _minimumToken1SwapOutAmount, _userAddress
);
}
}
}
function isNftApproved(address _strategyContract, address _user) external view returns (bool) {
address pm = IDelegationStrategyInfo(_strategyContract).getPositionManagerAddress();
return IPositionManagerApproval(pm).isApprovedForAll(_user, _strategyContract);
}
function _validateStrategy(address _strategyContract) internal view {
require(_strategyContract != address(0), "Invalid strategy address");
require(registeredStrategies.contains(_strategyContract), "Strategy not registered");
}
function getEstimatedUsedDepositToken(address _strategyContract, uint256 _depositAmount0, uint256 _depositAmount1)
public
view
returns (uint256 estimatedUsedAmount0, uint256 estimatedUsedAmount1)
{
(uint160 sqrtPriceX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96) = getSqrtPriceInfo(_strategyContract);
uint128 estimatedLiquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, _depositAmount0, _depositAmount1
);
(estimatedUsedAmount0, estimatedUsedAmount1) =
LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, estimatedLiquidity);
}
function getSqrtPriceInfo(address _strategyContract)
internal
view
returns (uint160 sqrtPriceX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96)
{
address poolAddress = IDelegationStrategyInfo(_strategyContract).poolAddress();
(, int24 tick,,,,,) = IUniswapV3Pool(poolAddress).slot0();
sqrtPriceX96 = TickMath.getSqrtRatioAtTick(tick);
sqrtRatioAX96 = sqrtPriceX96;
sqrtRatioBX96 = sqrtPriceX96;
}
function getUserShare(address _strategyContract, address _userAddress) public view returns (uint256) {
return IDelegationStrategyInfo(_strategyContract).userNftId(_userAddress) != 0 ? 1 : 0;
}
function setMaxFeeNumerator(uint24 _maxFeeNumerator) external onlyRole(EXECUTOR_ROLE) {
maxFeeNumerator = _maxFeeNumerator;
}
function setFeeNumerator(uint24 _feeNumerator) external onlyRole(EXECUTOR_ROLE) {
require(_feeNumerator <= maxFeeNumerator, "fee exceeds cap");
uint24 _oldFeeNumerator = feeNumerator;
feeNumerator = _feeNumerator;
emit SetFeeNumerator(_oldFeeNumerator, _feeNumerator);
}
function executorWithdraw(address _token, address _to, uint256 _amount)
external
onlyRole(EXECUTOR_ROLE)
nonReentrant
{
require(_to != address(0), "_to cannot be 0 address");
require(_amount > 0, "_amount cannot be 0");
if (_token == address(0)) {
TransferHelper.safeTransferETH(_to, _amount);
} else {
TransferHelper.safeTransfer(_token, _to, _amount);
}
emit ExecutorWithdraw(msg.sender, _token, _to, _amount);
}
function getTokenAmountAfterFee(uint256 _tokenAmount) public view returns (uint256 _remainingTokenAmount) {
_remainingTokenAmount = _tokenAmount - ((_tokenAmount * feeNumerator) / FEE_DENOMINATOR);
}
function registerStrategy(address _strategyContract) external onlyRole(EXECUTOR_ROLE) {
require(_strategyContract != address(0), "Invalid strategy contract");
require(!registeredStrategies.contains(_strategyContract), "Strategy already registered");
require(
IDelegationStrategyInfo(_strategyContract).getFarmAddress() == address(this),
"Strategy farm address is not this contract"
);
registeredStrategies.add(_strategyContract);
emit StrategyRegistered(_strategyContract, msg.sender);
}
function unregisterStrategy(address _strategyContract) external onlyRole(EXECUTOR_ROLE) {
require(_strategyContract != address(0), "Invalid strategy contract");
require(registeredStrategies.contains(_strategyContract), "Strategy not registered");
registeredStrategies.remove(_strategyContract);
emit StrategyUnregistered(_strategyContract, msg.sender);
}
function isStrategyRegistered(address _strategyContract) external view returns (bool) {
return registeredStrategies.contains(_strategyContract);
}
function getRegisteredStrategies() external view returns (address[] memory) {
return registeredStrategies.values();
}
function getUserList() external view returns (address[] memory) {
return userList.values();
}
function isUserInList(address _userAddress) external view returns (bool) {
return userList.contains(_userAddress);
}
function getUserCount() external view returns (uint256) {
return userList.length();
}
function getStrategyUserList(address _strategy) external view returns (address[] memory) {
return strategyUserList[_strategy].values();
}
function getStrategyUserCount(address _strategy) external view returns (uint256) {
return strategyUserList[_strategy].length();
}
function isUserInStrategy(address _strategy, address _user) external view returns (bool) {
return strategyUserList[_strategy].contains(_user);
}
}
contracts/delegation/interfaces/IDelegationStrategy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IDelegationStrategy {
function depositLiquidity(
bool isETH,
address userAddress,
address inputToken,
uint256 inputAmount,
uint256 swapInAmount,
uint256 minimumSwapOutAmount
)
external
payable
returns (
uint128 increasedLiquidity,
uint256 increasedShare,
uint256 increasedToken0Amount,
uint256 increasedToken1Amount,
uint256 sendBackToken0Amount,
uint256 sendBackToken1Amount,
uint256 feeToken0,
uint256 feeToken1
);
/// @param withdrawPercentage out of 1_000_000 (SHARE_DENOMINATOR)
function withdrawLiquidity(address userAddress, uint256 withdrawPercentage)
external
returns (
uint256 userReceivedToken0Amount,
uint256 userReceivedToken1Amount,
uint256 feeToken0,
uint256 feeToken1
);
function earn(address userAddress, uint256 minimumFee0SwapOutAmount, uint256 minimumFee1SwapOutAmount)
external
returns (
uint256 rewardToken0Amount,
uint256 rewardToken1Amount,
uint256 totalReward,
uint256 userReward,
uint256 fundManagerAmount
);
function rescale(
address userAddress,
int24 newTickLower,
int24 newTickUpper,
uint256 swapInAmount,
uint256 minimumSwapOutAmount,
uint256 minimumFee0SwapOutAmount,
uint256 minimumFee1SwapOutAmount
) external returns (uint256 totalReward, uint256 userReward, uint256 fundManagerAmount);
function depositDustToken(bool depositDustToken0)
external
returns (uint256 increasedToken0Amount, uint256 increasedToken1Amount);
}
contracts/delegation/interfaces/IDelegationStrategyInfo.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IDelegationStrategyInfo {
/// @dev Uniswap-Transaction-related Variable
function transactionDeadlineDuration() external view returns (uint256);
function tickSpacing() external view returns (int24);
/// @dev get Pool-related Variable
function poolAddress() external view returns (address);
function poolFee() external view returns (uint24);
function token0Address() external view returns (address);
function token1Address() external view returns (address);
/// @dev Per-user NFT tracking
function userNftId(address user) external view returns (uint256);
function nftIdToUser(uint256 tokenId) external view returns (address);
/// @dev get Accumulative-Reward-related Variable
function totalRewardAmountAccumulated() external view returns (uint256);
function totalFundManagerRewardAccumulated() external view returns (uint256);
function totalDistributeRewardAmountAccumulated() external view returns (uint256);
function totalUserDistributeRewardAccumulated() external view returns (uint256);
function totalReferralRewardAccumulated() external view returns (uint256);
/// @dev per-user reward tracking (for APR calculation by frontend/backend)
function userDistributeRewardAccumulated(address user) external view returns (uint256);
function latestUserDistributeReward(address user) external view returns (uint256);
function lastEarnedAt(address user) external view returns (uint256);
/// @dev get Referral-Management-related Variable
function unClaimedReferrerReward(address referrer) external view returns (uint256);
function accumulatedReferrerToRefereeReward(address referrer, address referee) external view returns (uint256);
function accumulatedReferrerReward(address referrer) external view returns (uint256);
function totalUnClaimedReferrerReward() external view returns (uint256);
/// @dev get Buyback-related Variable
function buyBackToken() external view returns (address);
function buyBackNumerator() external view returns (uint24);
/// @dev get Fund-Manager-related Variable
struct FundManagerVault {
address fundManagerVaultAddress;
uint256 fundManagerProfitVaultNumerator;
}
function getAllFundManagerVaults() external view returns (FundManagerVault[3] memory);
/// @dev get Constant Variable
function getBuyBackDenominator() external pure returns (uint24);
function getFundManagerProfitVaultDenominator() external pure returns (uint24);
function getFarmAddress() external view returns (address);
function getControllerAddress() external view returns (address);
function getSwapAmountCalculatorAddress() external view returns (address);
function getZapAddress() external view returns (address);
function getPositionManagerAddress() external view returns (address);
/// @dev get Gas fee compensation Variable
function gasFeeToken() external view returns (address);
function earnGasFee() external view returns (uint256);
function rescaleGasFee() external view returns (uint256);
function gasWallet() external view returns (address);
}
contracts/interfaces/IConstants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IConstants {
/// @dev Uniswap v3 Related
function UNISWAP_V3_FACTORY_ADDRESS() external view returns (address);
function NONFUNGIBLE_POSITION_MANAGER_ADDRESS() external view returns (address);
function SWAP_ROUTER_ADDRESS() external view returns (address);
/// @dev Distribute reward token address
function DISTRIBUTE_REWARD_ADDRESS() external view returns (address);
/// @dev Token address (combine each chain)
function WETH_ADDRESS() external view returns (address);
function WSTETH_ADDRESS() external view returns (address);
function WBTC_ADDRESS() external view returns (address);
function ARB_ADDRESS() external view returns (address);
function USDC_ADDRESS() external view returns (address);
function USDCE_ADDRESS() external view returns (address);
function USDT_ADDRESS() external view returns (address);
function DAI_ADDRESS() external view returns (address);
function RDNT_ADDRESS() external view returns (address);
function LINK_ADDRESS() external view returns (address);
function DEGEN_ADDRESS() external view returns (address);
function BRETT_ADDRESS() external view returns (address);
function TOSHI_ADDRESS() external view returns (address);
function CIRCLE_ADDRESS() external view returns (address);
function ROOST_ADDRESS() external view returns (address);
function AERO_ADDRESS() external view returns (address);
function INT_ADDRESS() external view returns (address);
function HIGHER_ADDRESS() external view returns (address);
function KEYCAT_ADDRESS() external view returns (address);
function CBBTC_ADDRESS() external view returns (address);
/// @dev Black hole address
function BLACK_HOLE_ADDRESS() external view returns (address);
/// @dev Uniswap V4 addresses
function POOL_MANAGER_V4_ADDRESS() external view returns (address);
function POSITION_MANAGER_V4_ADDRESS() external view returns (address);
function STATE_VIEW_V4_ADDRESS() external view returns (address);
function UNIVERSAL_ROUTER_V4_ADDRESS() external view returns (address);
function PERMIT2_ADDRESS() external view returns (address);
function V4_ETH_ADDRESS() external view returns (address);
}
contracts/interfaces/IFarm.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IFarm {
function FEE_DENOMINATOR() external view returns (uint24);
function feeNumerator() external view returns (uint24);
function getTokenAmountAfterFee(uint256 _tokenAmount) external view returns (uint256);
function SHARE_DENOMINATOR() external view returns (uint24);
}
contracts/interfaces/IFarmEvent.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IFarmEvent {
event DepositLiquidity(
address indexed strategyAddress,
address indexed userAddress,
uint256 indexed liquidityNftId,
bool isETH,
address inputToken,
uint256 inputAmount,
uint256 userShareAfterDeposit,
uint128 increasedLiquidity,
uint256 increasedShare,
uint256 increasedToken0Amount,
uint256 increasedToken1Amount,
uint256 sendBackToken0Amount,
uint256 sendBackToken1Amount,
uint256 feeToken0,
uint256 feeToken1
);
event WithdrawLiquidity(
address indexed strategyAddress,
address indexed userAddress,
uint256 indexed liquidityNftId,
uint256 decreasedShare,
uint256 userShareAfterWithdraw,
uint256 userReceivedToken0Amount,
uint256 userReceivedToken1Amount,
uint256 feeToken0,
uint256 feeToken1
);
/// @notice Emitted on a zap-to-single-token withdraw. Mirrors all `WithdrawLiquidity` fields
/// (the pre-swap token0/token1 amounts and fee split) and additionally carries `outputToken` /
/// `outputAmount` — the actual amount of `outputToken` the user received after token0/token1
/// were swapped to it. A subgraph can read the realized output from this single event.
event WithdrawUSDCfromLiquidity(
address indexed strategyAddress,
address indexed userAddress,
uint256 indexed liquidityNftId,
uint256 decreasedShare,
uint256 userShareAfterWithdraw,
uint256 userReceivedToken0Amount,
uint256 userReceivedToken1Amount,
uint256 feeToken0,
uint256 feeToken1,
address outputToken,
uint256 outputAmount
);
event ClaimReward(
address indexed strategyAddress,
address indexed userAddress,
uint256 indexed liquidityNftId,
uint256 claimedRewardAmount
);
event BatchClaimReward(
address[] indexed strategyAddresses, address indexed userAddress, uint256 claimedRewardAmount
);
event SetFeeNumerator(uint24 oldFeeNumerator, uint24 newFeeNumerator);
event ExecutorWithdraw(address indexed executor, address indexed token, address indexed to, uint256 amount);
}
contracts/interfaces/IZap.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IZap {
/// @dev get zap data
function slippageToleranceNumerator() external view returns (uint24);
function getSwapInfo(address inputToken, address outputToken)
external
view
returns (bool isPathDefined, address[] memory swapPathArray, uint24[] memory swapTradeFeeArray);
function getTokenExchangeRate(address inputToken, address outputToken)
external
view
returns (address token0, address token1, uint256 tokenPriceWith18Decimals);
function getMinimumSwapOutAmount(address inputToken, address outputToken, uint256 inputAmount)
external
view
returns (uint256 minimumSwapOutAmount);
/// @dev swapToken
function swapToken(bool isETH, address inputToken, address outputToken, uint256 inputAmount, address recipient)
external
payable
returns (uint256 outputAmount);
function swapTokenWithMinimumOutput(
bool isETH,
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 minimumSwapOutAmount,
address recipient
) external payable returns (uint256 outputAmount);
}
contracts/interfaces/external/IERC20Querier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20Querier is IERC20 {
function decimals() external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
contracts/interfaces/external/IWETH9.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Interface for WETH9
import "./IERC20Querier.sol";
interface IWETH9 is IERC20Querier {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256 amount) external;
}
contracts/interfaces/uniswapV3/INonfungiblePositionManager.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
interface INonfungiblePositionManager {
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (uint128 liquidity, uint256 amount0, uint256 amount1);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
contracts/interfaces/uniswapV3/IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
interface IUniswapV3Pool {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @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);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
}
contracts/libraries/uniswapV3/FixedPoint96.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
contracts/libraries/uniswapV3/FullMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (~denominator) + 1;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
contracts/libraries/uniswapV3/LiquidityAmounts.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "./FullMath.sol";
import "./FixedPoint96.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0)
internal
pure
returns (uint128 liquidity)
{
if (sqrtRatioAX96 > sqrtRatioBX96) {
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
}
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1)
internal
pure
returns (uint128 liquidity)
{
if (sqrtRatioAX96 > sqrtRatioBX96) {
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
}
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) {
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
}
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity)
internal
pure
returns (uint256 amount0)
{
if (sqrtRatioAX96 > sqrtRatioBX96) {
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
}
uint256 originalResult = FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96
) / sqrtRatioAX96;
/// @dev handle overflow issue
if (originalResult != 0) {
return originalResult;
} else {
return FullMath.mulDiv(
(uint256(liquidity) << FixedPoint96.RESOLUTION) / sqrtRatioAX96,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
);
}
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity)
internal
pure
returns (uint256 amount1)
{
if (sqrtRatioAX96 > sqrtRatioBX96) {
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
}
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) {
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
}
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
contracts/libraries/uniswapV3/TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.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 <= uint256(int256(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));
}
}
contracts/libraries/uniswapV3/TransferHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(address token, address from, address to, uint256 value) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "STF");
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(address token, address to, uint256 value) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "ST");
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev Errors with 'SA' if transfer fails
/// @param token The contract address of the token to be approved
/// @param to The target of the approval
/// @param value The amount of the given token the target will be allowed to spend
function safeApprove(address token, address to, uint256 value) internal {
bool success;
bytes memory data;
(success, data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, 0));
(success, data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "SA");
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success,) = to.call{value: value}("");
require(success, "STE");
}
}
node_modules/@openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(account),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
node_modules/@openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @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 ReentrancyGuard {
// 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;
constructor() {
_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
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// 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;
}
}
node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}
node_modules/@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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 Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
node_modules/@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
node_modules/@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
node_modules/@openzeppelin/contracts/utils/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris",
"remappings": [
"@uniswap/v4-core/=node_modules/@uniswap/v4-core/",
"@uniswap/v4-periphery/=node_modules/@uniswap/v4-periphery/",
"permit2/=node_modules/@uniswap/v4-periphery/lib/permit2/",
"forge-std/=node_modules/@uniswap/v4-core/lib/forge-std/src/",
"solmate/=node_modules/@uniswap/v4-core/lib/solmate/",
"@openzeppelin/=node_modules/@openzeppelin/",
"ds-test/=node_modules/@uniswap/v4-core/lib/solmate/lib/ds-test/",
"erc4626-tests/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"eth-gas-reporter/=node_modules/eth-gas-reporter/",
"forge-gas-snapshot/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/forge-gas-snapshot/",
"hardhat/=node_modules/hardhat/",
"openzeppelin-contracts/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/",
"v4-core/=node_modules/@uniswap/v4-periphery/lib/v4-core/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.