Verified contractExactGPL-3.0-or-later
RouterHelper
Address0x2d0a16356d61dd3c8b49a587f0a91f1cd2cff5c9
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.13
- Same code
2 more contracts
Details
- Compiler
- solc 0.8.13+commit.abaa5c0e
- Language
- solidity
- Optimization
- Yes, 200 runs
- License
- GPL-3.0-or-later
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,135,515
- Creation transaction
- 0x4e80c343c6…5c19269838
50 files
- contracts/RouterHelper.solmain28.77 KB
- @cryptoalgebra/integral-base-plugin/contracts/interfaces/plugins/IFarmingPlugin.sol1.63 KB
- @cryptoalgebra/integral-core/contracts/interfaces/IAlgebraFactory.sol10.37 KB
- @cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol949 B
- @cryptoalgebra/integral-core/contracts/interfaces/IERC20Minimal.sol3.11 KB
- @cryptoalgebra/integral-core/contracts/interfaces/callback/IAlgebraSwapCallback.sol1.36 KB
- @cryptoalgebra/integral-core/contracts/interfaces/plugin/IAlgebraPluginFactory.sol1.22 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolActions.sol7.7 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolErrors.sol4.11 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolEvents.sol6.26 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolImmutables.sol1.23 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolPermissionedActions.sol2.3 KB
- @cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolState.sol11.46 KB
- @cryptoalgebra/integral-core/contracts/interfaces/vault/IAlgebraVaultFactory.sol921 B
- @cryptoalgebra/integral-farming/contracts/base/IncentiveKey.sol617 B
- @cryptoalgebra/integral-farming/contracts/interfaces/IAlgebraEternalFarming.sol14.37 KB
- @cryptoalgebra/integral-farming/contracts/interfaces/IFarmingCenter.sol4.29 KB
- @cryptoalgebra/integral-periphery/contracts/interfaces/IERC721Permit.sol1.49 KB
- @cryptoalgebra/integral-periphery/contracts/interfaces/IMulticall.sol718 B
- @cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol11.35 KB
- @cryptoalgebra/integral-periphery/contracts/interfaces/IPeripheryImmutableState.sol674 B
- @cryptoalgebra/integral-periphery/contracts/interfaces/IPeripheryPayments.sol1.63 KB
- @cryptoalgebra/integral-periphery/contracts/interfaces/IPoolInitializer.sol1.31 KB
- @cryptoalgebra/integral-periphery/contracts/interfaces/IQuoterV2.sol6.02 KB
- @cryptoalgebra/integral-periphery/contracts/interfaces/ISwapRouter.sol3.77 KB
- @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol3.17 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.64 KB
- @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol3.68 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol9.38 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.48 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol6.94 KB
- @openzeppelin/contracts/token/ERC721/IERC721.sol4.88 KB
- @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol987 B
- @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol1.02 KB
- @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol761 B
- @openzeppelin/contracts/utils/Address.sol9.36 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol853 B
- contracts/interfaces/IAlgebraPoolAPIStorage.sol382 B
- contracts/interfaces/IERC20.sol809 B
- contracts/interfaces/IGaugeCL.sol1.02 KB
- contracts/interfaces/IGaugeManager.sol1.49 KB
- contracts/interfaces/IPair.sol1.56 KB
- contracts/interfaces/IPairFactory.sol896 B
- contracts/interfaces/IRouter.sol1.57 KB
- contracts/interfaces/IRouterHelper.sol2.31 KB
- contracts/libraries/Errors.sol1.63 KB
- contracts/libraries/FarmingExitLib.sol4.16 KB
- contracts/libraries/Math.sol920 B
contracts/RouterHelper.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.13;
import './interfaces/IPair.sol';
import "./interfaces/IRouter.sol";
import './interfaces/IPairFactory.sol';
import '@cryptoalgebra/integral-periphery/contracts/interfaces/IQuoterV2.sol';
import '@cryptoalgebra/integral-periphery/contracts/interfaces/ISwapRouter.sol';
import "@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol";
import './interfaces/IAlgebraPoolAPIStorage.sol';
import { IERC20 as IERC20WithDecimals } from './interfaces/IERC20.sol';
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./libraries/Math.sol";
import "./interfaces/IRouterHelper.sol";
import './interfaces/IGaugeCL.sol';
import './interfaces/IGaugeManager.sol';
import '@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraFactory.sol';
import "./libraries/Errors.sol";
import "@cryptoalgebra/integral-farming/contracts/interfaces/IFarmingCenter.sol";
import "@cryptoalgebra/integral-core/contracts/interfaces/IERC20Minimal.sol";
import "./libraries/FarmingExitLib.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
contract RouterHelper is IRouterHelper, OwnableUpgradeable, ReentrancyGuardUpgradeable, IERC721Receiver {
using SafeERC20 for IERC20;
uint internal constant MINIMUM_LIQUIDITY = 10**3;
address public router;
modifier onlyRouter() {
if (msg.sender != router) revert NOT_AUTHORIZED();
_;
}
struct PairSwapMetadata {
uint decimals0;
uint decimals1;
uint reserve0;
uint reserve1;
bool stable;
address token0;
address token1;
uint balanceA;
uint balanceB;
uint reserveA;
uint reserveB;
uint decimalsA;
uint decimalsB;
}
address public factory;
IQuoterV2 public quoterV2;
IAlgebraPoolAPIStorage public algebraPoolAPIStorage;
address public swapRouter;
INonfungiblePositionManager public nfpm;
IAlgebraFactory public algebraFactory;
IGaugeManager public gaugeManager;
IFarmingCenter public farmingCenter;
event Swap(address indexed sender,uint amount0In, uint amount0Out,address _tokenIn, address indexed to, bool stable);
event StakeStatus(address indexed user, uint256 indexed tokenId, address indexed pool, address gauge, bool staked);
error ZA();
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(
address _factory,
address _quoterV2,
address _algebraPoolAPIStorage,
address _swapRouter,
address _nfpm,
address _algebraFactory,
address _gaugeManager,
address _router,
address _farmingCenter
) public initializer {
__Ownable_init();
__ReentrancyGuard_init();
factory = _factory;
quoterV2 = IQuoterV2(_quoterV2);
algebraPoolAPIStorage = IAlgebraPoolAPIStorage(_algebraPoolAPIStorage);
swapRouter = _swapRouter;
nfpm = INonfungiblePositionManager(_nfpm);
algebraFactory = IAlgebraFactory(_algebraFactory);
gaugeManager = IGaugeManager(_gaugeManager);
router = _router;
farmingCenter = IFarmingCenter(_farmingCenter);
}
function setRouter(address _router) external onlyOwner {
router = _router;
}
/**
* @notice Returns the output amounts and price information for a given input amount and swap route.
* @dev For each route, calculates the output amount and price before/after swap.
* The price values (priceBeforeSwap and priceAfterSwap) are always quoted as token1 price with respect to token0 (token0 to token1).
* For basic pairs, priceBeforeSwap and priceAfterSwap are the reserves ratio (reserve1/reserve0) before and after the swap.
* For CL pools, priceBeforeSwap and priceAfterSwap are the sqrt price at the current tick before and after the swap.
* @param amountIn The input token amount.
* @param routes The swap route array.
* @return amounts The resulting amounts after each swap step.
* @return priceBeforeSwap For basic pairs, this is the reserves ratio before swap; for CL pools, this is the sqrt price at the current tick before swap.
* @return priceAfterSwap For basic pairs, this is the reserves ratio after swap; for CL pools, this is the sqrt price at the current tick after swap.
*/
function getAmountsOut(uint amountIn, IRouter.route[] memory routes) public returns (uint[] memory amounts, uint[] memory priceBeforeSwap, uint[] memory priceAfterSwap) {
uint routesLen = routes.length;
require(routesLen >= 1, 'INP');
amounts = new uint[](routesLen+1);
priceAfterSwap = new uint[](routesLen+1);
priceBeforeSwap = new uint[](routesLen+1);
amounts[0] = amountIn;
priceAfterSwap[0] = 0;
priceBeforeSwap[0] = 0;
IQuoterV2.QuoteExactInputSingleParams memory clInputParams;
for (uint i = 0; i < routesLen; i++) {
IRouter.route memory route = routes[i];
if(route.concentrated){
clInputParams = IQuoterV2.QuoteExactInputSingleParams ({
tokenIn: route.from,
tokenOut: route.to,
deployer: IAlgebraPoolAPIStorage(algebraPoolAPIStorage).pairToDeployer(route.pair),
amountIn: amounts[i],
limitSqrtPrice: 0
});
try IQuoterV2(quoterV2).quoteExactInputSingle(clInputParams) returns (
uint quotedAmount,uint256,
uint160 sqrtPriceX96After,
uint32,
uint256,
uint16
) {
amounts[i+1] = quotedAmount;
priceAfterSwap[i+1] = sqrtPriceX96After;
(uint160 price, , , , , ) = IAlgebraPool(route.pair).globalState();
priceBeforeSwap[i+1] = uint(price);
} catch {
amounts[i+1] = 0;
priceAfterSwap[i+1] = 0;
priceBeforeSwap[i+1] = 0;
break;
}
}
else{
if (IPairFactory(factory).isPair(route.pair)) {
try IPair(route.pair).getAmountOut(amounts[i], route.from) returns (uint outAmt) {
(bool swapPossible, uint afterReseve0, uint afterReserve1) = _swapRatio(amounts[i], route.from, route.pair, outAmt);
if(!swapPossible) {
amounts[i+1] = 0;
priceAfterSwap[i+1] = 0;
break;
}
amounts[i+1] = outAmt;
uint decimals0 = IERC20WithDecimals(route.from).decimals();
uint decimals1 = IERC20WithDecimals(route.to).decimals();
if(route.from > route.to) {
(decimals0, decimals1) = (decimals1, decimals0);
}
(uint beforeReserve0, uint beforeReserve1,) = IPair(route.pair).getReserves();
// Check if this is a stable pair to use appropriate price formula
(, , , , bool stable,,) = IPair(route.pair).metadata();
if (stable) {
// Use stable swap price formula for both before and after swap
priceBeforeSwap[i+1] = _calculateStableSwapPrice(beforeReserve0, beforeReserve1, decimals0, decimals1);
priceAfterSwap[i+1] = _calculateStableSwapPrice(afterReseve0, afterReserve1, decimals0, decimals1);
} else {
// Use standard AMM price formula for volatile pairs
// Price = (r1 / decimals1) / (r0 / decimals0) * 1e18
// This gives us the price in 18 decimal precision
if(18 + decimals0 >= decimals1){
priceBeforeSwap[i+1] = (beforeReserve1 * 10**(18 + decimals0 - decimals1)) / (beforeReserve0);
priceAfterSwap[i+1] = (afterReserve1 * 10**(18 + decimals0 - decimals1)) / (afterReseve0);
} else {
priceBeforeSwap[i+1] = (beforeReserve1) / (beforeReserve0 * 10**(decimals1 - decimals0 - 18));
priceAfterSwap[i+1] = (afterReserve1) / (afterReseve0 * 10**(decimals1 - decimals0 - 18));
}
}
} catch {
amounts[i+1] = 0;
priceAfterSwap[i+1] = 0;
break;
}
} else {
amounts[i+1] = 0;
priceAfterSwap[i+1] = 0;
break;
}
}
}
}
function _swapRatio(uint amountIn, address tokenIn, address pair, uint amountOut) internal view returns (bool, uint, uint){
PairSwapMetadata memory pairSwapMetaData;
(pairSwapMetaData.decimals0, pairSwapMetaData.decimals1, pairSwapMetaData.reserve0,
pairSwapMetaData.reserve1, pairSwapMetaData.stable, pairSwapMetaData.token0, pairSwapMetaData.token1)
= IPair(pair).metadata();
uint _balance0 = IERC20(pairSwapMetaData.token0).balanceOf(address(pair));
uint _balance1 = IERC20(pairSwapMetaData.token1).balanceOf(address(pair));
(pairSwapMetaData.balanceA, pairSwapMetaData.balanceB) = tokenIn == pairSwapMetaData.token0 ? (_balance0, _balance1) : (_balance1, _balance0);
(pairSwapMetaData.reserveA, pairSwapMetaData.reserveB) = tokenIn == pairSwapMetaData.token0 ? (pairSwapMetaData.reserve0, pairSwapMetaData.reserve1) : (pairSwapMetaData.reserve1, pairSwapMetaData.reserve0);
(pairSwapMetaData.decimalsA, pairSwapMetaData.decimalsB) = tokenIn == pairSwapMetaData.token0 ? (pairSwapMetaData.decimals0, pairSwapMetaData.decimals1) : (pairSwapMetaData.decimals1, pairSwapMetaData.decimals0);
uint actualAmountIn = amountIn + pairSwapMetaData.balanceA - pairSwapMetaData.reserveA;
uint feeAmount = actualAmountIn * IPairFactory(factory).getFee(pair, pairSwapMetaData.stable) / 10000;
pairSwapMetaData.balanceA = pairSwapMetaData.balanceA + amountIn - feeAmount;
pairSwapMetaData.balanceB -= amountOut;
uint afterReserveA = pairSwapMetaData.reserveA + actualAmountIn - feeAmount;
uint afterReserveB = pairSwapMetaData.reserveB - amountOut;
uint afterReserve0 = tokenIn == pairSwapMetaData.token0 ? afterReserveA : afterReserveB;
uint afterReserve1 = tokenIn == pairSwapMetaData.token0 ? afterReserveB : afterReserveA;
if(_k(pairSwapMetaData.balanceA, pairSwapMetaData.balanceB, pairSwapMetaData.decimalsA, pairSwapMetaData.decimalsB, pairSwapMetaData.stable) >= _k(pairSwapMetaData.reserveA, pairSwapMetaData.reserveB, pairSwapMetaData.decimalsA, pairSwapMetaData.decimalsB, pairSwapMetaData.stable)){
return (true, afterReserve0, afterReserve1);
}
return (false, afterReserve0, afterReserve1);
}
function _k(uint x, uint y, uint decimals0, uint decimals1, bool stable) internal pure returns (uint) {
if (stable) {
uint _x = x * 1e18 / decimals0;
uint _y = y * 1e18 / decimals1;
uint _a = (_x * _y) / 1e18;
uint _b = ((_x * _x) / 1e18 + (_y * _y) / 1e18);
return _a * _b / 1e18; // x3y+y3x >= k
} else {
return x * y; // xy >= k
}
}
function _getMinimumLiquidity(uint amount0, uint amount1, uint decimals0, uint decimals1) internal pure returns (uint) {
uint totalLiquidity = Math.sqrt(amount0 * amount1);
uint minLiquidity0 = (decimals0 * totalLiquidity) / (1e4 * amount0);
uint minLiquidity1 = (decimals1 * totalLiquidity) / (1e4 * amount1);
return Math.max(minLiquidity0, minLiquidity1);
}
function _calculateStableSwapPrice(
uint x,
uint y,
uint decimals0,
uint decimals1
) internal pure returns (uint) {
// Normalize reserves to 18 decimals
uint _x = (x * 1e18) / 10**decimals0;
uint _y = (y * 1e18) / 10**decimals1;
if (_x == 0 || _y == 0) return 0;
// Precompute squared terms, scaled down
uint r0Sq = (_x * _x) / 1e18;
uint r1Sq = (_y * _y) / 1e18;
// Numerator and denominator coefficients (scaled terms)
uint numeratorCoeff = (3 * r0Sq + r1Sq);
uint denominatorCoeff = (r0Sq + 3 * r1Sq);
// Now compute numerator and denominator carefully, dividing early
uint numerator = (_y * numeratorCoeff) / 1e18; // scaled down
uint denominator = (_x * denominatorCoeff) / 1e18;
if (denominator == 0) return 0;
// Final scale to 1e18 precision
return (numerator * 1e18) / denominator;
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountOut(uint amountIn, address tokenIn, address tokenOut) public view returns (uint amount, bool stable) {
address pairStable = pairFor(tokenIn, tokenOut, true);
address pairVolatile = pairFor(tokenIn, tokenOut, false);
address pair;
uint amountStable;
uint amountVolatile;
uint amountOut;
if (IPairFactory(factory).isPair(pairStable)) {
// amountStable = IBaseV1Pair(pairStable).getAmountOut(amountIn, tokenIn);
try IPair(pairStable).getAmountOut(amountIn, tokenIn) returns (uint outAmt) {
amountStable = outAmt;
} catch {
amountStable = 0;
}
}
if (IPairFactory(factory).isPair(pairVolatile)) {
//amountVolatile = IBaseV1Pair(pairVolatile).getAmountOut(amountIn, tokenIn);
try IPair(pairVolatile).getAmountOut(amountIn, tokenIn) returns (uint outAmt) {
amountVolatile = outAmt;
} catch {
amountVolatile = 0;
}
}
(amountOut, stable, pair) = amountStable > amountVolatile ? (amountStable, true, pairStable) : (amountVolatile, false, pairVolatile);
if (pair == address(0)) {
return (0, true);
}
(bool swapPossible,,) = _swapRatio(amountIn, tokenIn, pair, amountOut);
if(swapPossible){
return (amountOut, stable);
}
return (0, true);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountOutForFeeOnTransfer(uint amountIn, address tokenIn, address tokenOut) public view returns (uint amount, bool stable) {
address pairStable = pairFor(tokenIn, tokenOut, true);
address pairVolatile = pairFor(tokenIn, tokenOut, false);
address pair;
uint amountStable;
uint amountVolatile;
uint amountOut;
if (IPairFactory(factory).isPair(pairStable)) {
// amountStable = IBaseV1Pair(pairStable).getAmountOut(amountIn, tokenIn);
try IPair(pairStable).getAmountOut(amountIn, tokenIn) returns (uint outAmt) {
amountStable = outAmt;
} catch {
amountStable = 0;
}
}
if (IPairFactory(factory).isPair(pairVolatile)) {
//amountVolatile = IBaseV1Pair(pairVolatile).getAmountOut(amountIn, tokenIn);
try IPair(pairVolatile).getAmountOut(amountIn, tokenIn) returns (uint outAmt) {
amountVolatile = outAmt;
} catch {
amountVolatile = 0;
}
}
(amountOut, stable, pair) = amountStable > amountVolatile ? (amountStable, true, pairStable) : (amountVolatile, false, pairVolatile);
if (pair == address(0)) {
return (0, true);
}
(bool swapPossible,,) = _swapRatio(0, tokenIn, pair, amountOut);
if(swapPossible){
return (amountOut, stable);
}
return (0, true);
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address tokenA, address tokenB, bool stable) internal view returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
return IPairFactory(factory).getPair(token0, token1, stable);
}
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0) && token0 != token1, 'IA');
}
function version() external pure returns (string memory) {
return "1.0.0-patch";
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quoteLiquidity(uint amountA, uint reserveA, uint reserveB) public pure returns (uint amountB) {
require(amountA > 0 && reserveA > 0 && reserveB > 0, 'INL');
amountB = amountA * reserveB / reserveA;
}
function getReserves(address tokenA, address tokenB, bool stable) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
address pair = pairFor(tokenA, tokenB, stable);
(uint reserve0, uint reserve1,) = IPair(pair).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function quoteAddLiquidity(
address tokenA,
address tokenB,
bool stable,
uint amountADesired,
uint amountBDesired
) public view returns (uint amountA, uint amountB, uint liquidity) {
address _pair = pairFor(tokenA, tokenB, stable);
(uint reserveA, uint reserveB) = (0,0);
uint _totalSupply = 0;
if (_pair != address(0)) {
_totalSupply = IERC20(_pair).totalSupply();
(reserveA, reserveB) = getReserves(tokenA, tokenB, stable);
}
if (_totalSupply == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
uint decimalsA = IERC20WithDecimals(tokenA).decimals();
uint decimalsB = IERC20WithDecimals(tokenB).decimals();
uint minimumLiquidity = stable
? _getMinimumLiquidity(amountA, amountB, decimalsA, decimalsB)
: MINIMUM_LIQUIDITY;
liquidity = Math.sqrt(amountA * amountB) - minimumLiquidity;
} else {
uint amountBOptimal = quoteLiquidity(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
(amountA, amountB) = (amountADesired, amountBOptimal);
liquidity = Math.min(amountA * _totalSupply / reserveA, amountB * _totalSupply / reserveB);
} else {
uint amountAOptimal = quoteLiquidity(amountBDesired, reserveB, reserveA);
(amountA, amountB) = (amountAOptimal, amountBDesired);
liquidity = Math.min(amountA * _totalSupply / reserveA, amountB * _totalSupply / reserveB);
require(amountAOptimal <= amountADesired, 'IA');
}
}
}
function quoteRemoveLiquidity(
address tokenA,
address tokenB,
bool stable,
uint liquidity
) external view returns (uint amountA, uint amountB) {
address _pair = IPairFactory(factory).getPair(tokenA, tokenB, stable);
if (_pair == address(0)) {
return (0,0);
}
(uint reserveA, uint reserveB) = getReserves(tokenA, tokenB, stable);
uint _totalSupply = IERC20(_pair).totalSupply();
amountA = liquidity * reserveA / _totalSupply; // using balances ensures pro-rata distribution
amountB = liquidity * reserveB / _totalSupply; // using balances ensures pro-rata distribution
}
function calculateAddLiquidity(
address tokenA,
address tokenB,
bool stable,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) external view returns (uint amountA, uint amountB) {
require(amountADesired >= amountAMin && amountBDesired >= amountBMin, 'DLMA');
// Check if pair exists (view function, just checks)
address _pair = pairFor(tokenA, tokenB, stable);
if (_pair == address(0)) {
revert("Pair not found");
}
(amountA, amountB,) = quoteAddLiquidity(tokenA, tokenB, stable, amountADesired, amountBDesired);
require(amountA >= amountAMin && amountB >= amountBMin, 'IAA');
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function swap(uint[] memory amounts, IRouter.route[] memory routes, uint deadline, address sender) external onlyRouter {
uint256 routesLen = routes.length;
for (uint i = 0; i < routesLen; i++) {
IRouter.route memory route = routes[i];
if (route.receiver == address(0)) revert ZA();
if(route.concentrated){
if (IERC20(route.from).allowance(address(this), swapRouter) < amounts[i]) {
IERC20(route.from).forceApprove(swapRouter, amounts[i]);
}
ISwapRouter.ExactInputSingleParams memory inputParams;
inputParams = ISwapRouter.ExactInputSingleParams ({
tokenIn: route.from,
tokenOut: route.to,
deployer: IAlgebraPoolAPIStorage(algebraPoolAPIStorage).pairToDeployer(route.pair),
recipient: route.receiver,
deadline: deadline,
amountIn: amounts[i],
amountOutMinimum: 0,
limitSqrtPrice: 0
});
amounts[i+1] = ISwapRouter(swapRouter).exactInputSingle(inputParams);
}
else{
(address token0,) = sortTokens(route.from, route.to);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = route.from == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
IPair(pairFor(route.from, route.to, route.stable)).swap(
amount0Out, amount1Out, route.receiver, new bytes(0)
);
}
emit Swap(sender, amounts[i], amounts[i+1], route.from, route.receiver, route.stable);
}
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function swapSupportingFeeOnTransferTokens(IRouter.route[] memory routes, address _to, address sender) external onlyRouter {
for (uint i; i < routes.length; i++) {
(address input, address output) = (routes[i].from, routes[i].to);
(address token0,) = sortTokens(input, output);
IPair pair = IPair(pairFor(routes[i].from, routes[i].to, routes[i].stable));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput,) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)) - reserveInput;
(amountOutput,) = getAmountOutForFeeOnTransfer(amountInput, input, output);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < routes.length - 1 ? pairFor(routes[i+1].from, routes[i+1].to, routes[i+1].stable) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
bool _stable = routes[i].stable;
emit Swap(sender,amountInput,amountOutput,input,_to,_stable);
}
}
/**
* @dev Mint a concentrated-liquidity position, optionally enter farming via GaugeCL,
* and then transfer the NFT to the recipient.
*
* Flow:
* - RouterV2 collects tokens from user and transfers them to this helper.
* - Helper approves NFPM and mints the position to itself.
* - Helper looks up the gauge address for the pool.
* - If gauge exists, helper calls `deposit(uint256)` on the GaugeCL contract to enter farming.
* - Helper transfers the NFT to the recipient.
* - Any unused tokens are refunded to the recipient.
*/
function mintCLAndStake(
INonfungiblePositionManager.MintParams calldata params,
address sender
) external onlyRouter nonReentrant returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) {
address recipient = params.recipient;
// Approve NFPM to spend tokens from this helper
if (params.amount0Desired > 0) {
IERC20(params.token0).forceApprove(address(nfpm), params.amount0Desired);
}
if (params.amount1Desired > 0) {
IERC20(params.token1).forceApprove(address(nfpm), params.amount1Desired);
}
// Mint position to this helper so it can perform farming actions
INonfungiblePositionManager.MintParams memory mintParams = INonfungiblePositionManager.MintParams({
token0: params.token0,
token1: params.token1,
deployer: params.deployer,
tickLower: params.tickLower,
tickUpper: params.tickUpper,
amount0Desired: params.amount0Desired,
amount1Desired: params.amount1Desired,
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
recipient: address(this),
deadline: params.deadline
});
(tokenId, liquidity, amount0, amount1) = nfpm.mint(mintParams);
// Reset approvals to zero for safety
if (params.amount0Desired > 0) {
IERC20(params.token0).forceApprove(address(nfpm), 0);
}
if (params.amount1Desired > 0) {
IERC20(params.token1).forceApprove(address(nfpm), 0);
}
// Refund any dust tokens back to the recipient
uint256 bal0 = IERC20(params.token0).balanceOf(address(this));
if (bal0 > 0) {
IERC20(params.token0).safeTransfer(sender, bal0);
}
uint256 bal1 = IERC20(params.token1).balanceOf(address(this));
if (bal1 > 0) {
IERC20(params.token1).safeTransfer(sender, bal1);
}
// Look up the pool address from algebraFactory
address pool = algebraFactory.customPoolByPair(params.deployer, params.token0, params.token1);
address gauge = gaugeManager.gauges(pool);
bool staked;
// If gauge exists, deposit the NFT to enter farming
if (gauge != address(0) && gaugeManager.isAlive(gauge)) {
INonfungiblePositionManager(nfpm).approve(gauge, tokenId);
IGaugeCL(gauge).deposit(tokenId);
staked = true;
}
emit StakeStatus(sender, tokenId, pool, gauge, staked);
// Transfer the NFT to the recipient
nfpm.safeTransferFrom(address(this), recipient, tokenId);
}
function unstakeAndWithdraw(
uint256 tokenId,
uint128 liquidity,
uint256 amount0Min,
uint256 amount1Min,
address recipient,
address sender,
uint256 deadline
) external onlyRouter nonReentrant {
FarmingExitLib.unstakeAndWithdraw(farmingCenter, nfpm, tokenId, liquidity, amount0Min, amount1Min, recipient, sender, deadline);
}
/*//////////////////////////////////////////////////////////////
INTERNAL UTILS
//////////////////////////////////////////////////////////////*/
function onERC721Received(address, address, uint256, bytes calldata) external pure override returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
}@cryptoalgebra/integral-base-plugin/contracts/interfaces/plugins/IFarmingPlugin.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Algebra farming plugin
/// @dev This contract used for virtual pools in farms
interface IFarmingPlugin {
/// @notice Emitted when new activeIncentive is set
/// @param newIncentive The address of the new incentive
event Incentive(address newIncentive);
/// @notice Connects or disconnects an incentive.
/// @dev Only farming can connect incentives.
/// The one who connected it and the current farming has the right to disconnect the incentive.
/// @param newIncentive The address associated with the incentive or zero address
function setIncentive(address newIncentive) external;
/// @notice Checks if the incentive is connected to pool
/// @dev Returns false if the plugin has a different incentive set, the plugin is not connected to the pool,
/// or the plugin configuration is incorrect.
/// @param targetIncentive The address of the incentive to be checked
/// @return Indicates whether the target incentive is active
function isIncentiveConnected(address targetIncentive) external view returns (bool);
/// @notice Returns the address of active incentive
/// @dev if there is no active incentive at the moment, incentiveAddress would be equal to address(0)
/// @return The address associated with the current active incentive
function incentive() external view returns (address);
/// @notice Returns the address of the pool the plugin is created for
/// @return address of the pool
function getPool() external view returns (address);
}
@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
import './plugin/IAlgebraPluginFactory.sol';
import './vault/IAlgebraVaultFactory.sol';
/// @title The interface for the Algebra Factory
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraFactory {
/// @notice Emitted when a process of ownership renounce is started
/// @param timestamp The timestamp of event
/// @param finishTimestamp The timestamp when ownership renounce will be possible to finish
event RenounceOwnershipStart(uint256 timestamp, uint256 finishTimestamp);
/// @notice Emitted when a process of ownership renounce cancelled
/// @param timestamp The timestamp of event
event RenounceOwnershipStop(uint256 timestamp);
/// @notice Emitted when a process of ownership renounce finished
/// @param timestamp The timestamp of ownership renouncement
event RenounceOwnershipFinish(uint256 timestamp);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param pool The address of the created pool
event Pool(address indexed token0, address indexed token1, address pool);
/// @notice Emitted when a pool is created
/// @param deployer The corresponding custom deployer contract
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param pool The address of the created pool
event CustomPool(address indexed deployer, address indexed token0, address indexed token1, address pool);
/// @notice Emitted when the default community fee is changed
/// @param newDefaultCommunityFee The new default community fee value
event DefaultCommunityFee(uint16 newDefaultCommunityFee);
/// @notice Emitted when the default tickspacing is changed
/// @param newDefaultTickspacing The new default tickspacing value
event DefaultTickspacing(int24 newDefaultTickspacing);
/// @notice Emitted when the default fee is changed
/// @param newDefaultFee The new default fee value
event DefaultFee(uint16 newDefaultFee);
/// @notice Emitted when the defaultPluginFactory address is changed
/// @param defaultPluginFactoryAddress The new defaultPluginFactory address
event DefaultPluginFactory(address defaultPluginFactoryAddress);
/// @notice Emitted when the vaultFactory address is changed
/// @param newVaultFactory The new vaultFactory address
event VaultFactory(address newVaultFactory);
/// @notice role that can change communityFee and tickspacing in pools
/// @return The hash corresponding to this role
function POOLS_ADMINISTRATOR_ROLE() external view returns (bytes32);
/// @notice role that can call `createCustomPool` function
/// @return The hash corresponding to this role
function CUSTOM_POOL_DEPLOYER() external view returns (bytes32);
/// @notice Returns `true` if `account` has been granted `role` or `account` is owner.
/// @param role The hash corresponding to the role
/// @param account The address for which the role is checked
/// @return bool Whether the address has this role or the owner role or not
function hasRoleOrOwner(bytes32 role, address account) external view returns (bool);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via transferOwnership(address newOwner)
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the current poolDeployerAddress
/// @return The address of the poolDeployer
function poolDeployer() external view returns (address);
/// @notice Returns the default community fee
/// @return Fee which will be set at the creation of the pool
function defaultCommunityFee() external view returns (uint16);
/// @notice Returns the default fee
/// @return Fee which will be set at the creation of the pool
function defaultFee() external view returns (uint16);
/// @notice Returns the default tickspacing
/// @return Tickspacing which will be set at the creation of the pool
function defaultTickspacing() external view returns (int24);
/// @notice Return the current pluginFactory address
/// @dev This contract is used to automatically set a plugin address in new liquidity pools
/// @return Algebra plugin factory
function defaultPluginFactory() external view returns (IAlgebraPluginFactory);
/// @notice Return the current vaultFactory address
/// @dev This contract is used to automatically set a vault address in new liquidity pools
/// @return Algebra vault factory
function vaultFactory() external view returns (IAlgebraVaultFactory);
/// @notice Returns the default communityFee, tickspacing, fee and communityFeeVault for pool
/// @return communityFee which will be set at the creation of the pool
/// @return tickSpacing which will be set at the creation of the pool
/// @return fee which will be set at the creation of the pool
function defaultConfigurationForPool() external view returns (uint16 communityFee, int24 tickSpacing, uint16 fee);
/// @notice Deterministically computes the pool address given the token0 and token1
/// @dev The method does not check if such a pool has been created
/// @param token0 first token
/// @param token1 second token
/// @return pool The contract address of the Algebra pool
function computePoolAddress(address token0, address token1) external view returns (address pool);
/// @notice Deterministically computes the custom pool address given the customDeployer, token0 and token1
/// @dev The method does not check if such a pool has been created
/// @param customDeployer the address of custom plugin deployer
/// @param token0 first token
/// @param token1 second token
/// @return customPool The contract address of the Algebra pool
function computeCustomPoolAddress(address customDeployer, address token0, address token1) external view returns (address customPool);
/// @notice Returns the pool address for a given pair of tokens, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @return pool The pool address
function poolByPair(address tokenA, address tokenB) external view returns (address pool);
/// @notice Returns the custom pool address for a customDeployer and a given pair of tokens, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param customDeployer The address of custom plugin deployer
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @return customPool The pool address
function customPoolByPair(address customDeployer, address tokenA, address tokenB) external view returns (address customPool);
/// @notice returns keccak256 of AlgebraPool init bytecode.
/// @dev the hash value changes with any change in the pool bytecode
/// @return Keccak256 hash of AlgebraPool contract init bytecode
function POOL_INIT_CODE_HASH() external view returns (bytes32);
/// @return timestamp The timestamp of the beginning of the renounceOwnership process
function renounceOwnershipStartTimestamp() external view returns (uint256 timestamp);
/// @notice Creates a pool for the given two tokens
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param data Data for plugin creation
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
/// The call will revert if the pool already exists or the token arguments are invalid.
/// @return pool The address of the newly created pool
function createPool(address tokenA, address tokenB, bytes calldata data) external returns (address pool);
/// @notice Creates a custom pool for the given two tokens using `deployer` contract
/// @param deployer The address of plugin deployer, also used for custom pool address calculation
/// @param creator The initiator of custom pool creation
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param data The additional data bytes
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
/// The call will revert if the pool already exists or the token arguments are invalid.
/// @return customPool The address of the newly created custom pool
function createCustomPool(
address deployer,
address creator,
address tokenA,
address tokenB,
bytes calldata data
) external returns (address customPool);
/// @dev updates default community fee for new pools
/// @param newDefaultCommunityFee The new community fee, _must_ be <= MAX_COMMUNITY_FEE
function setDefaultCommunityFee(uint16 newDefaultCommunityFee) external;
/// @dev updates default fee for new pools
/// @param newDefaultFee The new fee, _must_ be <= MAX_DEFAULT_FEE
function setDefaultFee(uint16 newDefaultFee) external;
/// @dev updates default tickspacing for new pools
/// @param newDefaultTickspacing The new tickspacing, _must_ be <= MAX_TICK_SPACING and >= MIN_TICK_SPACING
function setDefaultTickspacing(int24 newDefaultTickspacing) external;
/// @dev updates pluginFactory address
/// @param newDefaultPluginFactory address of new plugin factory
function setDefaultPluginFactory(address newDefaultPluginFactory) external;
/// @dev updates vaultFactory address
/// @param newVaultFactory address of new vault factory
function setVaultFactory(address newVaultFactory) external;
/// @notice Starts process of renounceOwnership. After that, a certain period
/// of time must pass before the ownership renounce can be completed.
function startRenounceOwnership() external;
/// @notice Stops process of renounceOwnership and removes timer.
function stopRenounceOwnership() external;
}
@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
import './pool/IAlgebraPoolImmutables.sol';
import './pool/IAlgebraPoolState.sol';
import './pool/IAlgebraPoolActions.sol';
import './pool/IAlgebraPoolPermissionedActions.sol';
import './pool/IAlgebraPoolEvents.sol';
import './pool/IAlgebraPoolErrors.sol';
/// @title The interface for a Algebra Pool
/// @dev The pool interface is broken up into many smaller pieces.
/// This interface includes custom error definitions and cannot be used in older versions of Solidity.
/// For older versions of Solidity use #IAlgebraPoolLegacy
/// Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPool is
IAlgebraPoolImmutables,
IAlgebraPoolState,
IAlgebraPoolActions,
IAlgebraPoolPermissionedActions,
IAlgebraPoolEvents,
IAlgebraPoolErrors
{
// used only for combining interfaces
}
@cryptoalgebra/integral-core/contracts/interfaces/IERC20Minimal.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Minimal ERC20 interface for Algebra
/// @notice Contains a subset of the full ERC20 interface that is used in Algebra
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IERC20Minimal {
/// @notice Returns the balance of a token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
@cryptoalgebra/integral-core/contracts/interfaces/callback/IAlgebraSwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IAlgebraPoolActions#swap
/// @notice Any contract that calls IAlgebraPoolActions#swap must implement this interface
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraSwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IAlgebraPool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method _must_ be checked to be a AlgebraPool deployed by the canonical AlgebraFactory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IAlgebraPoolActions#swap call
function algebraSwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}
@cryptoalgebra/integral-core/contracts/interfaces/plugin/IAlgebraPluginFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title An interface for a contract that is capable of deploying Algebra plugins
/// @dev Such a factory can be used for automatic plugin creation for new pools.
/// Also a factory be used as an entry point for custom (additional) pools creation
interface IAlgebraPluginFactory {
/// @notice Deploys new plugin contract for pool
/// @param pool The address of the new pool
/// @param creator The address that initiated the pool creation
/// @param deployer The address of new plugin deployer contract (0 if not used)
/// @param token0 First token of the pool
/// @param token1 Second token of the pool
/// @return New plugin address
function beforeCreatePoolHook(
address pool,
address creator,
address deployer,
address token0,
address token1,
bytes calldata data
) external returns (address);
/// @notice Called after the pool is created
/// @param plugin The plugin address
/// @param pool The address of the new pool
/// @param deployer The address of new plugin deployer contract (0 if not used)
function afterCreatePoolHook(address plugin, address pool, address deployer) external;
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @dev Initialization should be done in one transaction with pool creation to avoid front-running
/// @param initialPrice The initial sqrt price of the pool as a Q64.96
function initialize(uint160 initialPrice) external;
/// @notice Adds liquidity for the given recipient/bottomTick/topTick position
/// @dev The caller of this method receives a callback in the form of IAlgebraMintCallback#algebraMintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on bottomTick, topTick, the amount of liquidity, and the current price.
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address for which the liquidity will be created
/// @param bottomTick The lower tick of the position in which to add liquidity
/// @param topTick The upper tick of the position in which to add liquidity
/// @param liquidityDesired The desired amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return liquidityActual The actual minted amount of liquidity
function mint(
address leftoversRecipient,
address recipient,
int24 bottomTick,
int24 topTick,
uint128 liquidityDesired,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1, uint128 liquidityActual);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param bottomTick The lower tick of the position for which to collect fees
/// @param topTick The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 bottomTick,
int24 topTick,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param bottomTick The lower tick of the position for which to burn liquidity
/// @param topTick The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @param data Any data that should be passed through to the plugin
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(int24 bottomTick, int24 topTick, uint128 amount, bytes calldata data) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IAlgebraSwapCallback#algebraSwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback. If using the Router it should contain SwapRouter#SwapCallbackData
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Swap token0 for token1, or token1 for token0 with prepayment
/// @dev The caller of this method receives a callback in the form of IAlgebraSwapCallback#algebraSwapCallback
/// caller must send tokens in callback before swap calculation
/// the actually sent amount of tokens is used for further calculations
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountToSell The amount of the swap, only positive (exact input) amount allowed
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback. If using the Router it should contain SwapRouter#SwapCallbackData
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swapWithPaymentInAdvance(
address leftoversRecipient,
address recipient,
bool zeroToOne,
int256 amountToSell,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IAlgebraFlashCallback#algebraFlashCallback
/// @dev All excess tokens paid in the callback are distributed to currently in-range liquidity providers as an additional fee.
/// If there are no in-range liquidity providers, the fee will be transferred to the first active provider in the future
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external;
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolErrors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
/// @title Errors emitted by a pool
/// @notice Contains custom errors emitted by the pool
/// @dev Custom errors are separated from the common pool interface for compatibility with older versions of Solidity
interface IAlgebraPoolErrors {
// #### pool errors ####
/// @notice Emitted by the reentrancy guard
error locked();
/// @notice Emitted if arithmetic error occurred
error arithmeticError();
/// @notice Emitted if an attempt is made to initialize the pool twice
error alreadyInitialized();
/// @notice Emitted if an attempt is made to mint or swap in uninitialized pool
error notInitialized();
/// @notice Emitted if 0 is passed as amountRequired to swap function
error zeroAmountRequired();
/// @notice Emitted if invalid amount is passed as amountRequired to swap function
error invalidAmountRequired();
/// @notice Emitted if plugin fee param greater than fee/override fee
error incorrectPluginFee();
/// @notice Emitted if the pool received fewer tokens than it should have
error insufficientInputAmount();
/// @notice Emitted if there was an attempt to mint zero liquidity
error zeroLiquidityDesired();
/// @notice Emitted if actual amount of liquidity is zero (due to insufficient amount of tokens received)
error zeroLiquidityActual();
/// @notice Emitted if the pool received fewer tokens0 after flash than it should have
error flashInsufficientPaid0();
/// @notice Emitted if the pool received fewer tokens1 after flash than it should have
error flashInsufficientPaid1();
/// @notice Emitted if limitSqrtPrice param is incorrect
error invalidLimitSqrtPrice();
/// @notice Tick must be divisible by tickspacing
error tickIsNotSpaced();
/// @notice Emitted if a method is called that is accessible only to the factory owner or dedicated role
error notAllowed();
/// @notice Emitted if new tick spacing exceeds max allowed value
error invalidNewTickSpacing();
/// @notice Emitted if new community fee exceeds max allowed value
error invalidNewCommunityFee();
/// @notice Emitted if an attempt is made to manually change the fee value, but dynamic fee is enabled
error dynamicFeeActive();
/// @notice Emitted if an attempt is made by plugin to change the fee value, but dynamic fee is disabled
error dynamicFeeDisabled();
/// @notice Emitted if an attempt is made to change the plugin configuration, but the plugin is not connected
error pluginIsNotConnected();
/// @notice Emitted if a plugin returns invalid selector after hook call
/// @param expectedSelector The expected selector
error invalidHookResponse(bytes4 expectedSelector);
// #### LiquidityMath errors ####
/// @notice Emitted if liquidity underflows
error liquiditySub();
/// @notice Emitted if liquidity overflows
error liquidityAdd();
// #### TickManagement errors ####
/// @notice Emitted if the topTick param not greater then the bottomTick param
error topTickLowerOrEqBottomTick();
/// @notice Emitted if the bottomTick param is lower than min allowed value
error bottomTickLowerThanMIN();
/// @notice Emitted if the topTick param is greater than max allowed value
error topTickAboveMAX();
/// @notice Emitted if the liquidity value associated with the tick exceeds MAX_LIQUIDITY_PER_TICK
error liquidityOverflow();
/// @notice Emitted if an attempt is made to interact with an uninitialized tick
error tickIsNotInitialized();
/// @notice Emitted if there is an attempt to insert a new tick into the list of ticks with incorrect indexes of the previous and next ticks
error tickInvalidLinks();
// #### SafeTransfer errors ####
/// @notice Emitted if token transfer failed internally
error transferFailed();
// #### TickMath errors ####
/// @notice Emitted if tick is greater than the maximum or less than the minimum allowed value
error tickOutOfRange();
/// @notice Emitted if price is greater than the maximum or less than the minimum allowed value
error priceOutOfRange();
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swaps cannot be emitted by the pool before Initialize
/// @param price The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 price, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed bottomTick,
int24 indexed topTick,
uint128 liquidityAmount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @param owner The owner of the position for which fees are collected
/// @param recipient The address that received fees
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(address indexed owner, address recipient, int24 indexed bottomTick, int24 indexed topTick, uint128 amount0, uint128 amount1);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed bottomTick,
int24 indexed topTick,
uint128 liquidityAmount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when a plugin fee is applied during a burn
/// @param owner The owner of the position
/// @param pluginFee The fee to be sent to the plugin
event BurnFee(address indexed owner, uint24 pluginFee);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param price The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 price,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool after any swaps
/// @param sender The address that initiated the swap
/// @param overrideFee The fee to be applied to the trade
/// @param pluginFee The fee to be sent to the plugin
event SwapFee(address indexed sender, uint24 overrideFee, uint24 pluginFee);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);
/// @notice Emitted when the pool has higher balances than expected.
/// Any excess of tokens will be distributed between liquidity providers as fee.
/// @dev Fees after flash also will trigger this event due to mechanics of flash.
/// @param amount0 The excess of token0
/// @param amount1 The excess of token1
event ExcessTokens(uint256 amount0, uint256 amount1);
/// @notice Emitted when the community fee is changed by the pool
/// @param communityFeeNew The updated value of the community fee in thousandths (1e-3)
event CommunityFee(uint16 communityFeeNew);
/// @notice Emitted when the tick spacing changes
/// @param newTickSpacing The updated value of the new tick spacing
event TickSpacing(int24 newTickSpacing);
/// @notice Emitted when the plugin address changes
/// @param newPluginAddress New plugin address
event Plugin(address newPluginAddress);
/// @notice Emitted when the plugin config changes
/// @param newPluginConfig New plugin config
event PluginConfig(uint8 newPluginConfig);
/// @notice Emitted when the fee changes inside the pool
/// @param fee The current fee in hundredths of a bip, i.e. 1e-6
event Fee(uint16 fee);
/// @notice Emitted when the community vault address changes
/// @param newCommunityVault New community vault
event CommunityVault(address newCommunityVault);
/// @notice Emitted when the plugin does skim the excess of tokens
/// @param to THe receiver of tokens (plugin)
/// @param amount0 The amount of token0
/// @param amount1 The amount of token1
event Skim(address indexed to, uint256 amount0, uint256 amount1);
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolImmutables {
/// @notice The Algebra factory contract, which must adhere to the IAlgebraFactory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolPermissionedActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by permissioned addresses
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolPermissionedActions {
/// @notice Set the community's % share of the fees. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newCommunityFee The new community fee percent in thousandths (1e-3)
function setCommunityFee(uint16 newCommunityFee) external;
/// @notice Set the new tick spacing values. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newTickSpacing The new tick spacing value
function setTickSpacing(int24 newTickSpacing) external;
/// @notice Set the new plugin address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newPluginAddress The new plugin address
function setPlugin(address newPluginAddress) external;
/// @notice Set new plugin config. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newConfig In the new configuration of the plugin,
/// each bit of which is responsible for a particular hook.
function setPluginConfig(uint8 newConfig) external;
/// @notice Set new community fee vault address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @dev Community fee vault receives collected community fees.
/// **accumulated but not yet sent to the vault community fees once will be sent to the `newCommunityVault` address**
/// @param newCommunityVault The address of new community fee vault
function setCommunityVault(address newCommunityVault) external;
/// @notice Set new pool fee. Can be called by owner if dynamic fee is disabled.
/// Called by the plugin if dynamic fee is enabled
/// @param newFee The new fee value
function setFee(uint16 newFee) external;
/// @notice Forces balances to match reserves. Excessive tokens will be distributed between active LPs
/// @dev Only plugin can call this function
function sync() external;
/// @notice Forces balances to match reserves. Excessive tokens will be sent to msg.sender
/// @dev Only plugin can call this function
function skim() external;
}
@cryptoalgebra/integral-core/contracts/interfaces/pool/IAlgebraPoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @dev Important security note: when using this data by external contracts, it is necessary to take into account the possibility
/// of manipulation (including read-only reentrancy).
/// This interface is based on the UniswapV3 interface, credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolState {
/// @notice Safely get most important state values of Algebra Integral AMM
/// @dev Several values exposed as a single method to save gas when accessed externally.
/// **Important security note: this method checks reentrancy lock and should be preferred in most cases**.
/// @return sqrtPrice The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return tick The current global tick of the pool. May not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return activeLiquidity The currently in-range liquidity available to the pool
/// @return nextTick The next initialized tick after current global tick
/// @return previousTick The previous initialized tick before (or at) current global tick
function safelyGetStateOfAMM()
external
view
returns (uint160 sqrtPrice, int24 tick, uint16 lastFee, uint8 pluginConfig, uint128 activeLiquidity, int24 nextTick, int24 previousTick);
/// @notice Allows to easily get current reentrancy lock status
/// @dev can be used to prevent read-only reentrancy.
/// This method just returns `globalState.unlocked` value
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function isUnlocked() external view returns (bool unlocked);
// ! IMPORTANT security note: the pool state can be manipulated.
// ! The following methods do not check reentrancy lock themselves.
/// @notice The globalState structure in the pool stores many values but requires only one slot
/// and is exposed as a single method to save gas when accessed externally.
/// @dev **important security note: caller should check `unlocked` flag to prevent read-only reentrancy**
/// @return price The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return 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(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return communityFee The community fee represented as a percent of all collected fee in thousandths, i.e. 1e-3 (so 100 is 10%)
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function globalState() external view returns (uint160 price, int24 tick, uint16 lastFee, uint8 pluginConfig, uint16 communityFee, bool unlocked);
/// @notice Look up information about a specific tick in the pool
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param tick The tick to look up
/// @return liquidityTotal The total amount of position liquidity that uses the pool either as tick lower or tick upper
/// @return liquidityDelta How much liquidity changes when the pool price crosses the tick
/// @return prevTick The previous tick in tick list
/// @return nextTick The next tick in tick list
/// @return outerFeeGrowth0Token The fee growth on the other side of the tick from the current tick in token0
/// @return outerFeeGrowth1Token The fee growth on the other side of the tick from the current tick in token1
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(
int24 tick
)
external
view
returns (
uint256 liquidityTotal,
int128 liquidityDelta,
int24 prevTick,
int24 nextTick,
uint256 outerFeeGrowth0Token,
uint256 outerFeeGrowth1Token
);
/// @notice The timestamp of the last sending of tokens to vault/plugin
/// @return The timestamp truncated to 32 bits
function lastFeeTransferTimestamp() external view returns (uint32);
/// @notice The amounts of token0 and token1 that will be sent to the vault
/// @dev Will be sent FEE_TRANSFER_FREQUENCY after communityFeeLastTimestamp
/// @return communityFeePending0 The amount of token0 that will be sent to the vault
/// @return communityFeePending1 The amount of token1 that will be sent to the vault
function getCommunityFeePending() external view returns (uint128 communityFeePending0, uint128 communityFeePending1);
/// @notice The amounts of token0 and token1 that will be sent to the plugin
/// @dev Will be sent FEE_TRANSFER_FREQUENCY after feeLastTransferTimestamp
/// @return pluginFeePending0 The amount of token0 that will be sent to the plugin
/// @return pluginFeePending1 The amount of token1 that will be sent to the plugin
function getPluginFeePending() external view returns (uint128 pluginFeePending0, uint128 pluginFeePending1);
/// @notice Returns the address of currently used plugin
/// @dev The plugin is subject to change
/// @return pluginAddress The address of currently used plugin
function plugin() external view returns (address pluginAddress);
/// @notice The contract to which community fees are transferred
/// @return communityVaultAddress The communityVault address
function communityVault() external view returns (address communityVaultAddress);
/// @notice Returns 256 packed tick initialized boolean values. See TickTree for more information
/// @param wordPosition Index of 256-bits word with ticks
/// @return The 256-bits word with packed ticks info
function tickTable(int16 wordPosition) external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
/// @return The fee growth accumulator for token0
function totalFeeGrowth0Token() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
/// @return The fee growth accumulator for token1
function totalFeeGrowth1Token() external view returns (uint256);
/// @notice The current pool fee value
/// @dev In case dynamic fee is enabled in the pool, this method will call the plugin to get the current fee.
/// If the plugin implements complex fee logic, this method may return an incorrect value or revert.
/// In this case, see the plugin implementation and related documentation.
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return currentFee The current pool fee value in hundredths of a bip, i.e. 1e-6
function fee() external view returns (uint16 currentFee);
/// @notice The tracked token0 and token1 reserves of pool
/// @dev If at any time the real balance is larger, the excess will be transferred to liquidity providers as additional fee.
/// If the balance exceeds uint128, the excess will be sent to the communityVault.
/// @return reserve0 The last known reserve of token0
/// @return reserve1 The last known reserve of token1
function getReserves() external view returns (uint128 reserve0, uint128 reserve1);
/// @notice Returns the information about a position by the position's key
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param key The position's key is a packed concatenation of the owner address, bottomTick and topTick indexes
/// @return liquidity The amount of liquidity in the position
/// @return innerFeeGrowth0Token Fee growth of token0 inside the tick range as of the last mint/burn/poke
/// @return innerFeeGrowth1Token Fee growth of token1 inside the tick range as of the last mint/burn/poke
/// @return fees0 The computed amount of token0 owed to the position as of the last mint/burn/poke
/// @return fees1 The computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(
bytes32 key
) external view returns (uint256 liquidity, uint256 innerFeeGrowth0Token, uint256 innerFeeGrowth1Token, uint128 fees0, uint128 fees1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks.
/// Returned value cannot exceed type(uint128).max
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The current in range liquidity
function liquidity() external view returns (uint128);
/// @notice The current tick spacing
/// @dev Ticks can only be initialized by new mints at multiples of this value
/// e.g.: a tickSpacing of 60 means ticks can be initialized every 60th tick, i.e., ..., -120, -60, 0, 60, 120, ...
/// However, tickspacing can be changed after the ticks have been initialized.
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The current tick spacing
function tickSpacing() external view returns (int24);
/// @notice The previous initialized tick before (or at) current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The previous initialized tick
function prevTickGlobal() external view returns (int24);
/// @notice The next initialized tick after current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The next initialized tick
function nextTickGlobal() external view returns (int24);
/// @notice The root of tick search tree
/// @dev Each bit corresponds to one node in the second layer of tick tree: '1' if node has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The root of tick search tree as bitmap
function tickTreeRoot() external view returns (uint32);
/// @notice The second layer of tick search tree
/// @dev Each bit in node corresponds to one node in the leafs layer (`tickTable`) of tick tree: '1' if leaf has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The node of tick search tree second layer
function tickTreeSecondLayer(int16) external view returns (uint256);
}
@cryptoalgebra/integral-core/contracts/interfaces/vault/IAlgebraVaultFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Algebra Vault Factory
/// @notice This contract can be used for automatic vaults creation
/// @dev Version: Algebra Integral
interface IAlgebraVaultFactory {
/// @notice returns address of the community fee vault for the pool
/// @param pool the address of Algebra Integral pool
/// @return communityFeeVault the address of community fee vault
function getVaultForPool(address pool) external view returns (address communityFeeVault);
/// @notice creates the community fee vault for the pool if needed
/// @param pool the address of Algebra Integral pool
/// @return communityFeeVault the address of community fee vault
function createVaultForPool(
address pool,
address creator,
address deployer,
address token0,
address token1
) external returns (address communityFeeVault);
}
@cryptoalgebra/integral-farming/contracts/base/IncentiveKey.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.6;
pragma abicoder v2;
import '@cryptoalgebra/integral-core/contracts/interfaces/IERC20Minimal.sol';
import '@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol';
/// @param rewardToken The token being distributed as a reward (token0)
/// @param bonusRewardToken The bonus token being distributed as a reward (token1)
/// @param pool The Algebra pool
/// @param nonce The nonce of incentive
struct IncentiveKey {
IERC20Minimal rewardToken;
IERC20Minimal bonusRewardToken;
IAlgebraPool pool;
uint256 nonce;
}
@cryptoalgebra/integral-farming/contracts/interfaces/IAlgebraEternalFarming.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
import '@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '../base/IncentiveKey.sol';
/// @title Algebra Eternal Farming Interface
/// @notice Allows farming nonfungible liquidity tokens in exchange for reward tokens without locking NFT for incentive time
interface IAlgebraEternalFarming {
/// @notice Details of the incentive to create
struct IncentiveParams {
uint128 reward; // The amount of reward tokens to be distributed
uint128 bonusReward; // The amount of bonus reward tokens to be distributed
uint128 rewardRate; // The rate of reward distribution per second
uint128 bonusRewardRate; // The rate of bonus reward distribution per second
uint24 minimalPositionWidth; // The minimal allowed width of position (tickUpper - tickLower)
}
error farmDoesNotExist();
error tokenAlreadyFarmed();
error incentiveNotExist();
error incentiveStopped();
error anotherFarmingIsActive();
error pluginNotConnected();
error minimalPositionWidthTooWide();
error zeroRewardAmount();
error positionIsTooNarrow();
error zeroLiquidity();
error invalidPool();
error claimToZeroAddress();
error invalidTokenAmount();
error emergencyActivated();
error reentrancyLock();
error poolReentrancyLock();
/// @notice Returns hash of 'INCENTIVE_MAKER_ROLE', used as role for incentive creation
function INCENTIVE_MAKER_ROLE() external view returns (bytes32);
/// @notice Returns hash of 'FARMINGS_ADMINISTRATOR_ROLE', used as role for permissioned actions in farming
function FARMINGS_ADMINISTRATOR_ROLE() external view returns (bytes32);
/// @notice The nonfungible position manager with which this farming contract is compatible
function nonfungiblePositionManager() external view returns (INonfungiblePositionManager);
/// @notice Represents a farming incentive
/// @param incentiveId The ID of the incentive computed from its parameters
function incentives(
bytes32 incentiveId
)
external
view
returns (
uint128 totalReward,
uint128 bonusReward,
address virtualPoolAddress,
uint24 minimalPositionWidth,
bool deactivated,
address pluginAddress
);
/// @notice Check if incentive is deactivated (manually or automatically)
/// @dev Does not check if the incentive is indeed currently connected to the Algebra pool or not
/// @param incentiveId The ID of the incentive computed from its parameters
/// @return True if incentive is deactivated (manually or automatically)
function isIncentiveDeactivated(bytes32 incentiveId) external view returns (bool);
/// @notice Returns address of current farmingCenter
function farmingCenter() external view returns (address);
/// @notice Users can withdraw liquidity without any checks if active.
function isEmergencyWithdrawActivated() external view returns (bool);
/// @notice Detach incentive from the pool and deactivate it
/// @param key The key of the incentive
function deactivateIncentive(IncentiveKey memory key) external;
/// @notice Add rewards for incentive
/// @param key The key of the incentive
/// @param rewardAmount The amount of token0
/// @param bonusRewardAmount The amount of token1
function addRewards(IncentiveKey memory key, uint128 rewardAmount, uint128 bonusRewardAmount) external;
/// @notice Decrease rewards for incentive and withdraw
/// @param key The key of the incentive
/// @param rewardAmount The amount of token0
/// @param bonusRewardAmount The amount of token1
function decreaseRewardsAmount(IncentiveKey memory key, uint128 rewardAmount, uint128 bonusRewardAmount) external;
/// @notice Changes `isEmergencyWithdrawActivated`. Users can withdraw liquidity without any checks if activated.
/// User cannot enter to farmings if activated.
/// _Must_ only be used in emergency situations. Farmings may be unusable after activation.
/// @dev only farmings administrator
/// @param newStatus The new status of `isEmergencyWithdrawActivated`.
function setEmergencyWithdrawStatus(bool newStatus) external;
/// @notice Returns amount of created incentives
function numOfIncentives() external view returns (uint256);
/// @notice Returns amounts of reward tokens owed to a given address according to the last time all farms were updated
/// @param owner The owner for which the rewards owed are checked
/// @param rewardToken The token for which to check rewards
/// @return rewardsOwed The amount of the reward token claimable by the owner
function rewards(address owner, IERC20Minimal rewardToken) external view returns (uint256 rewardsOwed);
/// @notice Updates farming center address
/// @param _farmingCenter The new farming center contract address
function setFarmingCenterAddress(address _farmingCenter) external;
/// @notice enter farming for Algebra LP token
/// @param key The key of the incentive for which to enter farming
/// @param tokenId The ID of the token to enter farming
function enterFarming(IncentiveKey memory key, uint256 tokenId) external;
/// @notice exitFarmings for Algebra LP token
/// @param key The key of the incentive for which to exit farming
/// @param tokenId The ID of the token to exit farming
/// @param _owner Owner of the token
function exitFarming(IncentiveKey memory key, uint256 tokenId, address _owner) external;
/// @notice Transfers `amountRequested` of accrued `rewardToken` (if possible) rewards from the contract to the recipient `to`
/// @param rewardToken The token being distributed as a reward
/// @param to The address where claimed rewards will be sent to
/// @param amountRequested The amount of reward tokens to claim. Claims entire reward amount if set to 0.
/// @return rewardBalanceBefore The total amount of unclaimed reward *before* claim
function claimReward(IERC20Minimal rewardToken, address to, uint256 amountRequested) external returns (uint256 rewardBalanceBefore);
/// @notice Transfers `amountRequested` of accrued `rewardToken` (if possible) rewards from the contract to the recipient `to`
/// @notice only for FarmingCenter
/// @param rewardToken The token being distributed as a reward
/// @param from The address of position owner
/// @param to The address where claimed rewards will be sent to
/// @param amountRequested The amount of reward tokens to claim. Claims entire reward amount if set to 0.
/// @return rewardBalanceBefore The total amount of unclaimed reward *before* claim
function claimRewardFrom(
IERC20Minimal rewardToken,
address from,
address to,
uint256 amountRequested
) external returns (uint256 rewardBalanceBefore);
/// @notice Calculates the reward amount that will be received for the given farm
/// @param key The key of the incentive
/// @param tokenId The ID of the token
/// @return reward The reward accrued to the NFT for the given incentive thus far
/// @return bonusReward The bonus reward accrued to the NFT for the given incentive thus far
function getRewardInfo(IncentiveKey memory key, uint256 tokenId) external returns (uint256 reward, uint256 bonusReward);
/// @notice Returns information about a farmed liquidity NFT
/// @param tokenId The ID of the farmed token
/// @param incentiveId The ID of the incentive for which the token is farmed
/// @return liquidity The amount of liquidity in the NFT as of the last time the rewards were computed,
/// @return tickLower The lower tick of position,
/// @return tickUpper The upper tick of position,
/// @return innerRewardGrowth0 The last saved reward0 growth inside position,
/// @return innerRewardGrowth1 The last saved reward1 growth inside position
function farms(
uint256 tokenId,
bytes32 incentiveId
) external view returns (uint128 liquidity, int24 tickLower, int24 tickUpper, uint256 innerRewardGrowth0, uint256 innerRewardGrowth1);
/// @notice Returns connected to pool incentive key
function incentiveKeys(
address poolAddress
) external view returns (IERC20Minimal rewardToken, IERC20Minimal bonusRewardToken, IAlgebraPool pool, uint256 nonce);
/// @notice Creates a new liquidity farming incentive program
/// @param key Details of the incentive to create
/// @param params Params of incentive
/// @param plugin The address of corresponding plugin
/// @return virtualPool The created virtual pool
function createEternalFarming(IncentiveKey memory key, IncentiveParams memory params, address plugin) external returns (address virtualPool);
/// @notice Change reward rates for incentive
/// @param key The key of incentive
/// @param rewardRate The new rate of main token (token0) distribution per sec
/// @param bonusRewardRate The new rate of bonus token (token1) distribution per sec
function setRates(IncentiveKey memory key, uint128 rewardRate, uint128 bonusRewardRate) external;
/// @notice Collect rewards for tokenId
/// @dev only FarmingCenter
/// @param key The key of incentive
/// @param tokenId The ID of the token to exit farming
/// @param _owner Owner of the token
/// @return reward The amount of main token (token0) collected
/// @param bonusReward The amount of bonus token (token1) collected
function collectRewards(IncentiveKey memory key, uint256 tokenId, address _owner) external returns (uint256 reward, uint256 bonusReward);
/// @notice Event emitted when a liquidity mining incentive has been stopped from the outside
/// @param incentiveId The stopped incentive
event IncentiveDeactivated(bytes32 indexed incentiveId);
/// @notice Event emitted when a Algebra LP token has been farmed
/// @param tokenId The unique identifier of an Algebra LP token
/// @param incentiveId The incentive in which the token is farming
/// @param liquidity The amount of liquidity farmed
event FarmEntered(uint256 indexed tokenId, bytes32 indexed incentiveId, uint128 liquidity);
/// @notice Event emitted when a Algebra LP token exited from farming
/// @param tokenId The unique identifier of an Algebra LP token
/// @param incentiveId The incentive in which the token is farming
/// @param rewardAddress The token being distributed as a reward
/// @param bonusRewardToken The token being distributed as a bonus reward
/// @param owner The address where claimed rewards were sent to
/// @param reward The amount of reward tokens to be claimed
/// @param bonusReward The amount of bonus reward tokens to be claimed
event FarmEnded(
uint256 indexed tokenId,
bytes32 indexed incentiveId,
address indexed rewardAddress,
address bonusRewardToken,
address owner,
uint256 reward,
uint256 bonusReward
);
/// @notice Emitted when the farming center is changed
/// @param farmingCenter The farming center after the address was changed
event FarmingCenter(address indexed farmingCenter);
/// @notice Event emitted when rewards were added
/// @param rewardAmount The additional amount of main token
/// @param bonusRewardAmount The additional amount of bonus token
/// @param incentiveId The ID of the incentive for which rewards were added
event RewardsAdded(uint256 rewardAmount, uint256 bonusRewardAmount, bytes32 incentiveId);
/// @notice Event emitted when rewards were decreased
/// @param rewardAmount The withdrawn amount of main token
/// @param bonusRewardAmount The withdrawn amount of bonus token
/// @param incentiveId The ID of the incentive for which rewards were decreased
event RewardAmountsDecreased(uint256 rewardAmount, uint256 bonusRewardAmount, bytes32 incentiveId);
/// @notice Event emitted when a reward token has been claimed
/// @param to The address where claimed rewards were sent to
/// @param reward The amount of reward tokens claimed
/// @param rewardAddress The token reward address
/// @param owner The address where claimed rewards were claimed from
event RewardClaimed(address indexed to, uint256 reward, address indexed rewardAddress, address indexed owner);
/// @notice Event emitted when reward rates were changed
/// @param rewardRate The new rate of main token (token0) distribution per sec
/// @param bonusRewardRate The new rate of bonus token (token1) distribution per sec
/// @param incentiveId The ID of the incentive for which rates were changed
event RewardsRatesChanged(uint128 rewardRate, uint128 bonusRewardRate, bytes32 incentiveId);
/// @notice Event emitted when rewards were collected
/// @param tokenId The ID of the token for which rewards were collected
/// @param incentiveId The ID of the incentive for which rewards were collected
/// @param rewardAmount Collected amount of reward
/// @param bonusRewardAmount Collected amount of bonus reward
event RewardsCollected(uint256 tokenId, bytes32 incentiveId, uint256 rewardAmount, uint256 bonusRewardAmount);
/// @notice Event emitted when a liquidity mining incentive has been created
/// @param rewardToken The token being distributed as a reward
/// @param bonusRewardToken The token being distributed as a bonus reward
/// @param pool The Algebra pool
/// @param virtualPool The virtual pool address
/// @param nonce The nonce of new farming
/// @param reward The amount of reward tokens to be distributed
/// @param bonusReward The amount of bonus reward tokens to be distributed
/// @param minimalAllowedPositionWidth The minimal allowed position width (tickUpper - tickLower)
event EternalFarmingCreated(
IERC20Minimal indexed rewardToken,
IERC20Minimal indexed bonusRewardToken,
IAlgebraPool indexed pool,
address virtualPool,
uint256 nonce,
uint256 reward,
uint256 bonusReward,
uint24 minimalAllowedPositionWidth
);
/// @notice Emitted when status of `isEmergencyWithdrawActivated` changes
/// @param newStatus New value of `isEmergencyWithdrawActivated`. Users can withdraw liquidity without any checks if active.
event EmergencyWithdraw(bool newStatus);
}
@cryptoalgebra/integral-farming/contracts/interfaces/IFarmingCenter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.6;
pragma abicoder v2;
import '@cryptoalgebra/integral-core/contracts/interfaces/IERC20Minimal.sol';
import '@cryptoalgebra/integral-periphery/contracts/interfaces/IMulticall.sol';
import '@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '@cryptoalgebra/integral-base-plugin/contracts/interfaces/plugins/IFarmingPlugin.sol';
import '../base/IncentiveKey.sol';
import '../interfaces/IAlgebraEternalFarming.sol';
/// @title Algebra main farming contract interface
/// @dev Manages users deposits and performs entry, exit and other actions.
interface IFarmingCenter is IMulticall {
/// @notice Returns current virtual pool address for Algebra pool
function virtualPoolAddresses(address poolAddress) external view returns (address virtualPoolAddresses);
/// @notice The nonfungible position manager with which this farming contract is compatible
function nonfungiblePositionManager() external view returns (INonfungiblePositionManager);
/// @notice The eternal farming contract
function eternalFarming() external view returns (IAlgebraEternalFarming);
/// @notice The Algebra poolDeployer contract
function algebraPoolDeployer() external view returns (address);
/// @notice Returns information about a deposited NFT
/// @param tokenId The ID of the deposit (and token) that is being transferred
/// @return eternalIncentiveId The id of eternal incentive that is active for this NFT
function deposits(uint256 tokenId) external view returns (bytes32 eternalIncentiveId);
/// @notice Returns incentive key for specific incentiveId
/// @param incentiveId The hash of incentive key
function incentiveKeys(
bytes32 incentiveId
) external view returns (IERC20Minimal rewardToken, IERC20Minimal bonusRewardToken, IAlgebraPool pool, uint256 nonce);
/// @notice Used to connect incentive to compatible AlgebraPool plugin
/// @dev only farming can do it
/// Will revert if something is already connected to the plugin
/// @param virtualPool The virtual pool to be connected, must not be zero address
/// @param plugin The Algebra farming plugin
function connectVirtualPoolToPlugin(address virtualPool, IFarmingPlugin plugin) external;
/// @notice Used to disconnect incentive from compatible AlgebraPool plugin
/// @dev only farming can do it.
/// If the specified virtual pool is not connected to the plugin, nothing will happen
/// @param virtualPool The virtual pool to be disconnected, must not be zero address
/// @param plugin The Algebra farming plugin
function disconnectVirtualPoolFromPlugin(address virtualPool, IFarmingPlugin plugin) external;
/// @notice Enters in incentive (eternal farming) with NFT-position token
/// @dev msg.sender must be the owner of NFT
/// @param key The incentive key
/// @param tokenId The id of position NFT
function enterFarming(IncentiveKey memory key, uint256 tokenId) external;
/// @notice Exits from incentive (eternal farming) with NFT-position token
/// @dev msg.sender must be the owner of NFT
/// @param key The incentive key
/// @param tokenId The id of position NFT
function exitFarming(IncentiveKey memory key, uint256 tokenId) external;
/// @notice Used to collect reward from eternal farming. Then reward can be claimed.
/// @param key The incentive key
/// @param tokenId The id of position NFT
/// @return reward The amount of collected reward
/// @return bonusReward The amount of collected bonus reward
function collectRewards(IncentiveKey memory key, uint256 tokenId) external returns (uint256 reward, uint256 bonusReward);
/// @notice Used to claim and send rewards from farming(s)
/// @dev can be used via static call to get current rewards for user
/// @param rewardToken The token that is a reward
/// @param to The address to be rewarded
/// @param amountRequested Amount to claim in eternal farming
/// @return rewardBalanceBefore The total amount of unclaimed reward *before* claim
function claimReward(IERC20Minimal rewardToken, address to, uint256 amountRequested) external returns (uint256 rewardBalanceBefore);
}
@cryptoalgebra/integral-periphery/contracts/interfaces/IERC721Permit.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain separator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
@cryptoalgebra/integral-periphery/contracts/interfaces/IMulticall.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Algebra positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidityDesired The amount by which liquidity for the NFT position was increased
/// @param actualLiquidity the actual liquidity that was added into a pool. Could differ from
/// _liquidity_ when using FeeOnTransfer tokens
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(
uint256 indexed tokenId,
uint128 liquidityDesired,
uint128 actualLiquidity,
uint256 amount0,
uint256 amount1,
address pool
);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Emitted if farming failed in call from NonfungiblePositionManager.
/// @dev Should never be emitted
/// @param tokenId The ID of corresponding token
event FarmingFailed(uint256 indexed tokenId);
/// @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 deployer The address of the custom pool deployer
/// @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 (
uint88 nonce,
address operator,
address token0,
address token1,
address deployer,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
address deployer;
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.
/// @dev If native token is used as input, this function should be accompanied by a `refundNativeToken` in multicall to avoid potential loss of native tokens
/// @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 liquidity delta amount as a result of the increase
/// @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
/// @dev If native token is used as input, this function should be accompanied by a `refundNativeToken` in multicall to avoid potential loss of native tokens
/// @return liquidity The liquidity delta amount as a result of the increase
/// @return amount0 The amount of token0 to achieve resulting liquidity
/// @return amount1 The amount of token1 to achieve 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;
/// @notice Changes approval of token ID for farming.
/// @param tokenId The ID of the token that is being approved / unapproved
/// @param approve New status of approval
/// @param farmingAddress The address of farming: used to prevent tx frontrun
function approveForFarming(uint256 tokenId, bool approve, address farmingAddress) external payable;
/// @notice Changes farming status of token to 'farmed' or 'not farmed'
/// @dev can be called only by farmingCenter
/// @param tokenId The ID of the token
/// @param toActive The new status
function switchFarmingStatus(uint256 tokenId, bool toActive) external;
/// @notice Changes address of farmingCenter
/// @dev can be called only by factory owner or NONFUNGIBLE_POSITION_MANAGER_ADMINISTRATOR_ROLE
/// @param newFarmingCenter The new address of farmingCenter
function setFarmingCenter(address newFarmingCenter) external;
/// @notice Returns whether `spender` is allowed to manage `tokenId`
/// @dev Requirement: `tokenId` must exist
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
/// @notice Returns the address of currently connected farming, if any
/// @return The address of the farming center contract, which handles farmings logic
function farmingCenter() external view returns (address);
/// @notice Returns the address of farming that is approved for this token, if any
function farmingApprovals(uint256 tokenId) external view returns (address);
/// @notice Returns the address of farming in which this token is farmed, if any
function tokenFarmedIn(uint256 tokenId) external view returns (address);
}
@cryptoalgebra/integral-periphery/contracts/interfaces/IPeripheryImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface IPeripheryImmutableState {
/// @return Returns the address of the Algebra factory
function factory() external view returns (address);
/// @return Returns the address of the pool Deployer
function poolDeployer() external view returns (address);
/// @return Returns the address of WNativeToken
function WNativeToken() external view returns (address);
}
@cryptoalgebra/integral-periphery/contracts/interfaces/IPeripheryPayments.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of NativeToken
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface IPeripheryPayments {
/// @notice Unwraps the contract's WNativeToken balance and sends it to recipient as NativeToken.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WNativeToken from users.
/// @param amountMinimum The minimum amount of WNativeToken to unwrap
/// @param recipient The address receiving NativeToken
function unwrapWNativeToken(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any NativeToken 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 refundNativeToken() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
@cryptoalgebra/integral-periphery/contracts/interfaces/IPoolInitializer.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes Algebra Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @param data Data for plugin initialization
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
address deployer,
uint160 sqrtPriceX96,
bytes calldata data
) external payable returns (address pool);
}
@cryptoalgebra/integral-periphery/contracts/interfaces/IQuoterV2.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title QuoterV2 Interface
/// @notice Supports quoting the calculated amounts from exact input or exact output swaps.
/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.
/// @dev These functions are not marked view because they rely on calling non-view functions and reverting
/// to compute the result. They are also not gas efficient and should not be called on-chain.
/// Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface IQuoterV2 {
/// @notice Returns the amount out received for a given exact input swap without executing the swap
/// @param path The path of the swap, i.e. each token pair
/// @param amountInRequired The desired amount of the first token to swap
/// @return amountOutList The amount of the last token that would be received
/// @return amountInList The amount of the last token that should be paid
/// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path
/// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path
/// @return gasEstimate The estimate of the gas that the swap consumes
/// @return feeList List of the fee values used for swaps in the path
function quoteExactInput(
bytes memory path,
uint256 amountInRequired
)
external
returns (
uint256[] memory amountOutList,
uint256[] memory amountInList,
uint160[] memory sqrtPriceX96AfterList,
uint32[] memory initializedTicksCrossedList,
uint256 gasEstimate,
uint16[] memory feeList
);
struct QuoteExactInputSingleParams {
address tokenIn;
address tokenOut;
address deployer;
uint256 amountIn;
uint160 limitSqrtPrice;
}
/// @notice Returns the amount out received for a given exact input but for a swap of a single pool
/// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`
/// tokenIn The token being swapped in
/// tokenOut The token being swapped out
/// amountIn The desired input amount
/// limitSqrtPrice The price limit of the pool that cannot be exceeded by the swap
/// @return amountOut The amount of `tokenOut` that would be received
/// @return amountIn The amount of the `tokenIn` that should be paid
/// @return sqrtPriceX96After The sqrt price of the pool after the swap
/// @return initializedTicksCrossed The number of initialized ticks that the swap crossed
/// @return gasEstimate The estimate of the gas that the swap consumes
/// @return fee The fee value used for swap in the pool
function quoteExactInputSingle(
QuoteExactInputSingleParams memory params
)
external
returns (
uint256 amountOut,
uint256 amountIn,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256 gasEstimate,
uint16 fee
);
/// @notice Returns the amount in required for a given exact output swap without executing the swap
/// @param path The path of the swap, i.e. each token pair. Path must be provided in reverse order
/// @param amountOutRequired The amount of the last token to receive
/// @return amountOutList The amount of the last token that would be received
/// @return amountInList The amount of first token required to be paid
/// @return sqrtPriceX96AfterList List of the sqrt price after the swap for each pool in the path
/// @return initializedTicksCrossedList List of the initialized ticks that the swap crossed for each pool in the path
/// @return gasEstimate The estimate of the gas that the swap consumes
/// @return feeList List of the fee values used for swaps in the path
function quoteExactOutput(
bytes memory path,
uint256 amountOutRequired
)
external
returns (
uint256[] memory amountOutList,
uint256[] memory amountInList,
uint160[] memory sqrtPriceX96AfterList,
uint32[] memory initializedTicksCrossedList,
uint256 gasEstimate,
uint16[] memory feeList
);
struct QuoteExactOutputSingleParams {
address tokenIn;
address tokenOut;
address deployer;
uint256 amount;
uint160 limitSqrtPrice;
}
/// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool
/// @param params The params for the quote, encoded as `QuoteExactOutputSingleParams`
/// tokenIn The token being swapped in
/// tokenOut The token being swapped out
/// amountOut The desired output amount
/// limitSqrtPrice The price limit of the pool that cannot be exceeded by the swap
/// @return amountOut The amount of the last token that would be received
/// @return amountIn The amount required as the input for the swap in order to receive `amountOut`
/// @return sqrtPriceX96After The sqrt price of the pool after the swap
/// @return initializedTicksCrossed The number of initialized ticks that the swap crossed
/// @return gasEstimate The estimate of the gas that the swap consumes
/// @return fee The fee value used for swap in the pool
function quoteExactOutputSingle(
QuoteExactOutputSingleParams memory params
)
external
returns (
uint256 amountOut,
uint256 amountIn,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256 gasEstimate,
uint16 fee
);
}
@cryptoalgebra/integral-periphery/contracts/interfaces/ISwapRouter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@cryptoalgebra/integral-core/contracts/interfaces/callback/IAlgebraSwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Algebra
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface ISwapRouter is IAlgebraSwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
address deployer;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 limitSqrtPrice;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
address deployer;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 limitSqrtPrice;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @dev If native token is used as input, this function should be accompanied by a `refundNativeToken` in multicall to avoid potential loss of native tokens
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @dev If native token is used as input, this function should be accompanied by a `refundNativeToken` in multicall to avoid potential loss of native tokens
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @dev Unlike standard swaps, handles transferring from user before the actual swap.
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingleSupportingFeeOnTransferTokens(
ExactInputSingleParams calldata params
) external payable returns (uint256 amountOut);
}
@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@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);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@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);
}
contracts/interfaces/IAlgebraPoolAPIStorage.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
interface IAlgebraPoolAPIStorage {
function pairToDeployer(address) external view returns (address);
function setDeployerForPair(address _pair) external;
function customDeployers(uint256 i) external view returns(address);
function setDeployerForPair(address _pair, address _deployer) external;
}
contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
interface IERC20 {
function totalSupply() external view returns (uint256);
function transfer(address recipient, uint amount) external returns (bool);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function balanceOf(address) external view returns (uint);
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contracts/interfaces/IGaugeCL.sol
// SPDX-License-Identifier: MIT OR GPL-3.0-or-later
pragma solidity 0.8.13;
import '@cryptoalgebra/integral-farming/contracts/base/IncentiveKey.sol';
interface IGaugeCL {
function notifyRewardAmount(address token, uint amount) external returns (IncentiveKey memory incentivekey, uint256 rewardRate, uint128 bonusRewardRate);
function claimFees() external returns (uint claimed0, uint claimed1);
function balanceOf(uint256 tokenId) external view returns (uint256);
function emergency() external returns (bool);
function earned(uint256 tokenId) external view returns (uint256 reward, uint256 bonusReward);
function totalActiveSupply() external view returns (uint);
function rewardRate() external view returns (uint);
function rewardForDuration() external view returns (uint256);
function stakedFees() external view returns (uint256, uint256);
function deposit(uint256 tokenId) external;
function activateEmergencyMode() external;
function stopEmergencyMode() external;
}contracts/interfaces/IGaugeManager.sol
// SPDX-License-Identifier: MIT OR GPL-3.0-or-later
pragma solidity 0.8.13;
interface IGaugeManager {
struct FarmingParam {
address farmingCenter;
address algebraEternalFarming;
address nfpm;
}
function fetchInternalBribeFromPool(address _pool) external returns (address);
function fetchExternalBribeFromPool(address _pool) external returns (address);
function isGaugeAliveForPool(address _pool) external returns (bool);
function notifyRewardAmount(uint amount) external;
function minter() external view returns(address);
function createGauge(address _pool, uint256 _gaugeType) external returns (address _gauge, address _internal_bribe, address _external_bribe);
function gauges(address _pair) external view returns (address);
function isGauge(address _gauge) external view returns (bool);
function isAlive(address _gauge) external view returns (bool);
function poolForGauge(address _gauge) external view returns (address);
function internal_bribes(address _gauge) external view returns (address);
function external_bribes(address _gauge) external view returns (address);
function pools(uint256 i) external view returns(address);
function getBlackGovernor() external view returns (address);
function setBlackGovernor(address _blackGovernor) external;
function acceptAlgebraFeeChangeProposal (address _pool, uint16 newAlgebraFee) external;
function length() external view returns(uint);
}contracts/interfaces/IPair.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
interface IPair {
function metadata() external view returns (uint dec0, uint dec1, uint r0, uint r1, bool st, address t0, address t1);
function claimFees() external returns (uint, uint);
function tokens() external view returns (address, address);
function token0() external view returns (address);
function token1() external view returns (address);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function burn(address to) external returns (uint amount0, uint amount1);
function mint(address to) external returns (uint liquidity);
function getReserves() external view returns (uint _reserve0, uint _reserve1, uint _blockTimestampLast);
function getAmountOut(uint, address) external view returns (uint);
function name() external view returns(string memory);
function symbol() external view returns(string memory);
function totalSupply() external view returns (uint);
function decimals() external view returns (uint8);
function claimable0(address _user) external view returns (uint);
function claimable1(address _user) external view returns (uint);
function isStable() external view returns(bool);
function allowance(address owner, address spender) external view returns (uint);
}
contracts/interfaces/IPairFactory.sol
// SPDX-License-Identifier: MIT OR GPL-3.0-or-later
pragma solidity 0.8.13;
interface IPairFactory {
function allPairsLength() external view returns (uint);
function isPair(address pair) external view returns (bool);
function allPairs(uint index) external view returns (address);
function pairCodeHash() external view returns (bytes32);
function pairGenerator() external view returns (address);
function getPair(address tokenA, address token, bool stable) external view returns (address);
function createPair(address tokenA, address tokenB, bool stable) external returns (address pair);
function getFee(address _pairAddress, bool _stable) external view returns(uint256);
function dibs() external view returns (address);
function getReferralFee(address _pairAddress) external view returns (uint256);
function isPaused() external view returns (bool);
}
contracts/interfaces/IRouter.sol
// SPDX-License-Identifier: MIT OR GPL-3.0-or-later
pragma solidity 0.8.13;
interface IRouter {
struct route {
address pair;
address from;
address to;
bool stable;
bool concentrated;
address receiver;
}
function factory() external view returns (address);
function wETH() external view returns (address);
function routerHelper() external view returns (address);
function pairFor(address tokenA, address tokenB, bool stable) external view returns (address pair);
function swapExactTokensForTokens(uint amountIn,uint amountOutMin,route[] calldata routes,address to,uint deadline) external returns (uint[] memory amounts);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
IRouter.route[] calldata routes,
address to,
uint deadline
) external;
function addLiquidity(address tokenA,address tokenB,bool stable,uint amountADesired,uint amountBDesired,uint amountAMin,uint amountBMin,address to,uint deadline) external returns (uint amountA, uint amountB, uint liquidity);
function removeLiquidity(address tokenA,address tokenB,bool stable,uint liquidity,uint amountAMin,uint amountBMin,address to,uint deadline) external returns (uint amountA, uint amountB);
function getReserves(address tokenA, address tokenB, bool stable) external view returns (uint reserveA, uint reserveB);
function getPoolAmountOut(uint amountIn, address tokenIn, address pair) external view returns (uint amount);
}contracts/interfaces/IRouterHelper.sol
// SPDX-License-Identifier: MIT OR GPL-3.0-or-later
pragma solidity 0.8.13;
import "./IRouter.sol";
import '@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol';
interface IRouterHelper {
function getAmountsOut(uint amountIn, IRouter.route[] memory routes) external returns (uint[] memory amounts, uint[] memory priceBeforeSwap, uint[] memory priceAfterSwap);
function getAmountOut(uint amountIn, address tokenIn, address tokenOut) external view returns (uint amount, bool stable);
function getAmountOutForFeeOnTransfer(uint amountIn, address tokenIn, address tokenOut) external view returns (uint amount, bool stable);
// Add liquidity calculation
function calculateAddLiquidity(
address tokenA,
address tokenB,
bool stable,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) external view returns (uint amountA, uint amountB);
function quoteLiquidity(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function quoteAddLiquidity(
address tokenA,
address tokenB,
bool stable,
uint amountADesired,
uint amountBDesired
) external view returns (uint amountA, uint amountB, uint liquidity);
function quoteRemoveLiquidity(
address tokenA,
address tokenB,
bool stable,
uint liquidity
) external view returns (uint amountA, uint amountB);
function swap(
uint[] memory amounts,
IRouter.route[] memory routes,
uint deadline,
address sender
) external;
function swapSupportingFeeOnTransferTokens(
IRouter.route[] memory routes,
address to,
address sender
) external;
function mintCLAndStake(
INonfungiblePositionManager.MintParams calldata params,
address sender
) external returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
function unstakeAndWithdraw(
uint256 tokenId,
uint128 liquidity,
uint256 amount0Min,
uint256 amount1Min,
address recipient,
address sender,
uint256 deadline
) external;
function version() external pure returns (string memory);
}contracts/libraries/Errors.sol
// SPDX-License-Identifier: MIT OR GPL-3.0-or-later
pragma solidity 0.8.13;
// Shared custom errors across router, helpers, and zap library
error EXP(); // Expired
error IA(); // Invalid Address/Amount
error INL(); // Insufficient Liquidity
error DLMA(); // Desired Liquidity More than Allowed
error IAA(); // Insufficient Amount A
error ITFM(); // TransferFrom failed
error IR(address recipient); // Invalid recipient/route receiver
error IOA(uint256 required, uint256 available); // Insufficient output amount
error INP(); // Invalid Path
error ZA(); // Zero Amount
error ETF(uint256 amount); // ETH transfer failed
error CODELEN(); // Code length zero
error ZERO_LIQUIDITY_MINTED(); // Mint returned zero liquidity
error NOT_AUTHORIZED(); // Caller not authorized
error NA(); // Not Allowed / Genesis guard
error IST(); // Insufficient transfer
error ISTF(); // Insufficient transferFrom
error NS(); // No swaps provided
error ER(); // Empty routes
error IOT(); // Incomplete output tokens list
error CF(); // Callback failed
error CL(); // Code length
error IIT(address token); // Invalid input token
error ALM(uint256 expected, uint256 actual); // Array length mismatch
error BE(uint256 required, uint256 available); // Bad ETH provided
error ISTK(address token); // Invalid swap token
error MSFT(address token); // Missing swap for token
error CC(); // Invalid callback caller
error IB(uint256 required, uint256 available); // Insufficient balance
error NNS(); // NFPM not set
error IT(address expected0, address actual0, address expected1, address actual1); // Invalid tokenscontracts/libraries/FarmingExitLib.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.13;
import "@cryptoalgebra/integral-core/contracts/interfaces/IERC20Minimal.sol";
import "@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol";
import "@cryptoalgebra/integral-farming/contracts/interfaces/IFarmingCenter.sol";
import "@cryptoalgebra/integral-farming/contracts/base/IncentiveKey.sol";
import "@cryptoalgebra/integral-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
library FarmingExitLib {
function _claimRewardsAndExitIfRequired(
IFarmingCenter farmingCenter,
uint256 tokenId,
address recipient,
bool shouldExit
) internal {
bytes32 incentiveId = farmingCenter.deposits(tokenId);
if (incentiveId == bytes32(0)) return;
(IERC20Minimal rewardToken, IERC20Minimal bonusToken, IAlgebraPool pool, uint256 nonce) =
farmingCenter.incentiveKeys(incentiveId);
IncentiveKey memory key = IncentiveKey(rewardToken, bonusToken, pool, nonce);
(uint256 reward, uint256 bonusReward) = farmingCenter.collectRewards(key, tokenId);
if (shouldExit) {
farmingCenter.exitFarming(key, tokenId);
}
farmingCenter.claimReward(rewardToken, recipient, reward);
if (address(bonusToken) != address(0) && bonusReward > 0) {
farmingCenter.claimReward(bonusToken, recipient, bonusReward);
}
}
/// @notice Claims farming rewards to `sender` and, for full withdrawals, exits farming; then decreases liquidity,
/// collects tokens, and finally burns or returns the NFT depending on remaining liquidity.
/// @param sender The address that sent the NFT to the contract. Emissions are claimed to this address;
/// @param recipient The address that receives the tokens and will receive the NFT back after rebalance when liquidity remains.
function unstakeAndWithdraw(
IFarmingCenter farmingCenter,
INonfungiblePositionManager nfpm,
uint256 tokenId,
uint128 liquidity,
uint256 amount0Min,
uint256 amount1Min,
address recipient,
address sender,
uint256 deadline
) internal {
uint128 addedLiquidity;
(,,,,,,, addedLiquidity,,,,) = nfpm.positions(tokenId);
_claimRewardsAndExitIfRequired(farmingCenter, tokenId, sender, addedLiquidity == liquidity);
decreaseLiquidityCollectAndFinalize(nfpm, tokenId, liquidity, amount0Min, amount1Min, recipient, sender, deadline);
}
/// @notice Decreases liquidity, collects tokens, then burns the NFT if no liquidity left or transfers it to nftReturnTo.
/// @return token0 The position's token0 address (from positions() before decrease).
/// @return token1 The position's token1 address (from positions() before decrease).
function decreaseLiquidityCollectAndFinalize(
INonfungiblePositionManager nfpm,
uint256 tokenId,
uint128 liquidity,
uint256 amount0Min,
uint256 amount1Min,
address recipient,
address nftReturnTo,
uint256 deadline
) internal returns (address token0, address token1) {
(,, token0, token1,,,,,,,,) = nfpm.positions(tokenId);
nfpm.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: tokenId,
liquidity: liquidity,
amount0Min: amount0Min,
amount1Min: amount1Min,
deadline: deadline
})
);
nfpm.collect(
INonfungiblePositionManager.CollectParams({
tokenId: tokenId,
recipient: recipient,
amount0Max: type(uint128).max,
amount1Max: type(uint128).max
})
);
uint128 liquidityPositionAfter;
(,,,,,,, liquidityPositionAfter,,,,) = nfpm.positions(tokenId);
if (liquidityPositionAfter == 0) {
nfpm.burn(tokenId);
} else if (nftReturnTo != address(0)) {
nfpm.safeTransferFrom(address(this), nftReturnTo, tokenId);
}
}
}contracts/libraries/Math.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
library Math {
function max(uint a, uint b) internal pure returns (uint) {
return a >= b ? a : b;
}
function min(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function cbrt(uint256 n) internal pure returns (uint256) { unchecked {
uint256 x = 0;
for (uint256 y = 1 << 255; y > 0; y >>= 3) {
x <<= 1;
uint256 z = 3 * x * (x + 1) + 1;
if (n / y >= z) {
n -= y * z;
x += 1;
}
}
return x;
}}
}
Compiler settingsShow
{
"metadata": {
"useLiteralContent": true
},
"optimizer": {
"runs": 200,
"enabled": true
}
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.