// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
import './Constants.sol';
/// @title AdaptiveFee
/// @notice Calculates fee based on combination of sigmoids
library AdaptiveFee {
// alpha1 + alpha2 + baseFee must be <= type(uint16).max
struct Configuration {
uint16 alpha1; // max value of the first sigmoid
uint16 alpha2; // max value of the second sigmoid
uint32 beta1; // shift along the x-axis for the first sigmoid
uint32 beta2; // shift along the x-axis for the second sigmoid
uint16 gamma1; // horizontal stretch factor for the first sigmoid
uint16 gamma2; // horizontal stretch factor for the second sigmoid
uint32 volumeBeta; // shift along the x-axis for the outer volume-sigmoid
uint16 volumeGamma; // horizontal stretch factor the outer volume-sigmoid
uint16 baseFee; // minimum possible fee
}
/// @notice Calculates fee based on formula:
/// baseFee + sigmoidVolume(sigmoid1(volatility, volumePerLiquidity) + sigmoid2(volatility, volumePerLiquidity))
/// maximum value capped by baseFee + alpha1 + alpha2
function getFee(
uint88 volatility,
uint256 volumePerLiquidity,
Configuration memory config
) internal pure returns (uint16 fee) {
uint256 sumOfSigmoids = sigmoid(volatility, config.gamma1, config.alpha1, config.beta1) +
sigmoid(volatility, config.gamma2, config.alpha2, config.beta2);
if (sumOfSigmoids > type(uint16).max) {
// should be impossible, just in case
sumOfSigmoids = type(uint16).max;
}
return uint16(config.baseFee + sigmoid(volumePerLiquidity, config.volumeGamma, uint16(sumOfSigmoids), config.volumeBeta)); // safe since alpha1 + alpha2 + baseFee _must_ be <= type(uint16).max
}
/// @notice calculates α / (1 + e^( (β-x) / γ))
/// that is a sigmoid with a maximum value of α, x-shifted by β, and stretched by γ
/// @dev returns uint256 for fuzzy testing. Guaranteed that the result is not greater than alpha
function sigmoid(
uint256 x,
uint16 g,
uint16 alpha,
uint256 beta
) internal pure returns (uint256 res) {
if (x > beta) {
x = x - beta;
if (x >= 6 * uint256(g)) return alpha; // so x < 19 bits
uint256 g8 = uint256(g)**8; // < 128 bits (8*16)
uint256 ex = exp(x, g, g8); // < 155 bits
res = (alpha * ex) / (g8 + ex); // in worst case: (16 + 155 bits) / 155 bits
// so res <= alpha
} else {
x = beta - x;
if (x >= 6 * uint256(g)) return 0; // so x < 19 bits
uint256 g8 = uint256(g)**8; // < 128 bits (8*16)
uint256 ex = g8 + exp(x, g, g8); // < 156 bits
res = (alpha * g8) / ex; // in worst case: (16 + 128 bits) / 156 bits
// g8 <= ex, so res <= alpha
}
}
/// @notice calculates e^(x/g) * g^8 in a series, since (around zero):
/// e^x = 1 + x + x^2/2 + ... + x^n/n! + ...
/// e^(x/g) = 1 + x/g + x^2/(2*g^2) + ... + x^(n)/(g^n * n!) + ...
function exp(
uint256 x,
uint16 g,
uint256 gHighestDegree
) internal pure returns (uint256 res) {
// calculating:
// g**8 + x * g**7 + (x**2 * g**6) / 2 + (x**3 * g**5) / 6 + (x**4 * g**4) / 24 + (x**5 * g**3) / 120 + (x**6 * g^2) / 720 + x**7 * g / 5040 + x**8 / 40320
// x**8 < 152 bits (19*8) and g**8 < 128 bits (8*16)
// so each summand < 152 bits and res < 155 bits
uint256 xLowestDegree = x;
res = gHighestDegree; // g**8
gHighestDegree /= g; // g**7
res += xLowestDegree * gHighestDegree;
gHighestDegree /= g; // g**6
xLowestDegree *= x; // x**2
res += (xLowestDegree * gHighestDegree) / 2;
gHighestDegree /= g; // g**5
xLowestDegree *= x; // x**3
res += (xLowestDegree * gHighestDegree) / 6;
gHighestDegree /= g; // g**4
xLowestDegree *= x; // x**4
res += (xLowestDegree * gHighestDegree) / 24;
gHighestDegree /= g; // g**3
xLowestDegree *= x; // x**5
res += (xLowestDegree * gHighestDegree) / 120;
gHighestDegree /= g; // g**2
xLowestDegree *= x; // x**6
res += (xLowestDegree * gHighestDegree) / 720;
xLowestDegree *= x; // x**7
res += (xLowestDegree * g) / 5040 + (xLowestDegree * x) / (40320);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import './interfaces/IAlgebraEternalFarming.sol';
import './interfaces/IAlgebraEternalVirtualPool.sol';
import '../../libraries/IncentiveId.sol';
import './EternalVirtualPool.sol';
import '@cryptoalgebra/core/contracts/libraries/SafeCast.sol';
import '@cryptoalgebra/core/contracts/libraries/FullMath.sol';
import '@cryptoalgebra/core/contracts/libraries/Constants.sol';
import '../AlgebraFarming.sol';
/// @title Algebra eternal (v2-like) farming
contract AlgebraEternalFarming is AlgebraFarming, IAlgebraEternalFarming {
using SafeCast for int256;
/// @notice Represents the farm for nft
struct Farm {
uint128 liquidity;
int24 tickLower;
int24 tickUpper;
uint256 innerRewardGrowth0;
uint256 innerRewardGrowth1;
}
/// @dev farms[tokenId][incentiveHash] => Farm
/// @inheritdoc IAlgebraEternalFarming
mapping(uint256 => mapping(bytes32 => Farm)) public override farms;
/// @param _deployer pool deployer contract address
/// @param _nonfungiblePositionManager the NFT position manager contract address
constructor(IAlgebraPoolDeployer _deployer, INonfungiblePositionManager _nonfungiblePositionManager)
AlgebraFarming(_deployer, _nonfungiblePositionManager)
{
// just initialize AlgebraFarming
}
/// @inheritdoc IAlgebraEternalFarming
function createEternalFarming(
IncentiveKey memory key,
IncentiveParams memory params,
Tiers calldata tiers
) external override onlyIncentiveMaker returns (address virtualPool) {
(, address _incentive) = _getCurrentVirtualPools(key.pool);
require(_incentive == address(0), 'Farming already exists');
virtualPool = address(new EternalVirtualPool(address(farmingCenter), address(this), address(key.pool)));
bytes32 incentiveId;
(incentiveId, params.reward, params.bonusReward) = _createFarming(
virtualPool,
key,
params.reward,
params.bonusReward,
params.minimalPositionWidth,
params.multiplierToken,
tiers
);
emit EternalFarmingCreated(
key.rewardToken,
key.bonusRewardToken,
key.pool,
virtualPool,
key.startTime,
key.endTime,
params.reward,
params.bonusReward,
tiers,
params.multiplierToken,
params.minimalPositionWidth
);
IAlgebraEternalVirtualPool(virtualPool).addRewards(params.reward, params.bonusReward);
IAlgebraEternalVirtualPool(virtualPool).setRates(params.rewardRate, params.bonusRewardRate);
emit RewardsAdded(params.reward, params.bonusReward, incentiveId);
emit RewardsRatesChanged(params.rewardRate, params.bonusRewardRate, incentiveId);
}
/// @inheritdoc IAlgebraFarming
function detachIncentive(IncentiveKey memory key) external override onlyIncentiveMaker {
(, address _eternalVirtualPool) = _getCurrentVirtualPools(key.pool);
_detachIncentive(key, _eternalVirtualPool);
}
/// @inheritdoc IAlgebraFarming
function attachIncentive(IncentiveKey memory key) external override onlyIncentiveMaker {
(, address _eternalVirtualPool) = _getCurrentVirtualPools(key.pool);
_attachIncentive(key, _eternalVirtualPool);
}
/// @inheritdoc IAlgebraEternalFarming
function addRewards(
IncentiveKey memory key,
uint256 rewardAmount,
uint256 bonusRewardAmount
) external override {
bytes32 incentiveId = IncentiveId.compute(key);
Incentive storage incentive = incentives[incentiveId];
require(incentive.totalReward > 0, 'non-existent incentive');
(rewardAmount, bonusRewardAmount) = _receiveRewards(key, rewardAmount, bonusRewardAmount, incentive);
if (rewardAmount | bonusRewardAmount > 0) {
IAlgebraEternalVirtualPool virtualPool = IAlgebraEternalVirtualPool(incentive.virtualPoolAddress);
virtualPool.addRewards(rewardAmount, bonusRewardAmount);
emit RewardsAdded(rewardAmount, bonusRewardAmount, incentiveId);
}
}
/// @inheritdoc IAlgebraEternalFarming
function setRates(
IncentiveKey memory key,
uint128 rewardRate,
uint128 bonusRewardRate
) external override onlyIncentiveMaker {
bytes32 incentiveId = IncentiveId.compute(key);
IAlgebraEternalVirtualPool virtualPool = IAlgebraEternalVirtualPool(incentives[incentiveId].virtualPoolAddress);
virtualPool.setRates(rewardRate, bonusRewardRate);
emit RewardsRatesChanged(rewardRate, bonusRewardRate, incentiveId);
}
/// @inheritdoc IAlgebraFarming
function enterFarming(
IncentiveKey memory key,
uint256 tokenId,
uint256 tokensLocked
) external override onlyFarmingCenter {
(
bytes32 incentiveId,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address virtualPoolAddress
) = _enterFarming(key, tokenId, tokensLocked);
mapping(bytes32 => Farm) storage farmsForToken = farms[tokenId];
require(farmsForToken[incentiveId].liquidity == 0, 'token already farmed');
(uint256 innerRewardGrowth0, uint256 innerRewardGrowth1) = IAlgebraEternalVirtualPool(virtualPoolAddress)
.getInnerRewardsGrowth(tickLower, tickUpper);
farmsForToken[incentiveId] = Farm({
liquidity: liquidity,
tickLower: tickLower,
tickUpper: tickUpper,
innerRewardGrowth0: innerRewardGrowth0,
innerRewardGrowth1: innerRewardGrowth1
});
emit FarmEntered(tokenId, incentiveId, liquidity, tokensLocked);
}
/// @inheritdoc IAlgebraFarming
function exitFarming(
IncentiveKey memory key,
uint256 tokenId,
address _owner
) external override onlyFarmingCenter {
bytes32 incentiveId = IncentiveId.compute(key);
Farm memory farm = farms[tokenId][incentiveId];
require(farm.liquidity != 0, 'farm does not exist');
Incentive storage incentive = incentives[incentiveId];
IAlgebraEternalVirtualPool virtualPool = IAlgebraEternalVirtualPool(incentive.virtualPoolAddress);
uint256 reward;
uint256 bonusReward;
{
(, int24 tick, , , , , ) = key.pool.globalState();
// update rewards, as ticks may be cleared when liquidity decreases
virtualPool.applyLiquidityDeltaToPosition(uint32(block.timestamp), farm.tickLower, farm.tickUpper, 0, tick);
(uint256 innerRewardGrowth0, uint256 innerRewardGrowth1) = virtualPool.getInnerRewardsGrowth(
farm.tickLower,
farm.tickUpper
);
virtualPool.applyLiquidityDeltaToPosition(
uint32(block.timestamp),
farm.tickLower,
farm.tickUpper,
-int256(farm.liquidity).toInt128(),
tick
);
(reward, bonusReward) = (
FullMath.mulDiv(innerRewardGrowth0 - farm.innerRewardGrowth0, farm.liquidity, Constants.Q128),
FullMath.mulDiv(innerRewardGrowth1 - farm.innerRewardGrowth1, farm.liquidity, Constants.Q128)
);
}
mapping(IERC20Minimal => uint256) storage rewardBalances = rewards[_owner];
if (reward != 0) {
rewardBalances[key.rewardToken] += reward; // user must claim before overflow
}
if (bonusReward != 0) {
rewardBalances[key.bonusRewardToken] += bonusReward; // user must claim before overflow
}
delete farms[tokenId][incentiveId];
emit FarmEnded(
tokenId,
incentiveId,
address(key.rewardToken),
address(key.bonusRewardToken),
_owner,
reward,
bonusReward
);
}
/// @notice reward amounts can be outdated, actual amounts could be obtained via static call of `collectRewards` in FarmingCenter
/// @inheritdoc IAlgebraFarming
function getRewardInfo(IncentiveKey memory key, uint256 tokenId)
external
view
override
returns (uint256 reward, uint256 bonusReward)
{
bytes32 incentiveId = IncentiveId.compute(key);
Farm memory farm = farms[tokenId][incentiveId];
require(farm.liquidity > 0, 'farm does not exist');
IAlgebraEternalVirtualPool virtualPool = IAlgebraEternalVirtualPool(incentives[incentiveId].virtualPoolAddress);
(uint256 innerRewardGrowth0, uint256 innerRewardGrowth1) = virtualPool.getInnerRewardsGrowth(
farm.tickLower,
farm.tickUpper
);
(reward, bonusReward) = (
FullMath.mulDiv(innerRewardGrowth0 - farm.innerRewardGrowth0, farm.liquidity, Constants.Q128),
FullMath.mulDiv(innerRewardGrowth1 - farm.innerRewardGrowth1, farm.liquidity, Constants.Q128)
);
}
/// @notice reward amounts should be updated before calling this method
/// @inheritdoc IAlgebraEternalFarming
function collectRewards(
IncentiveKey memory key,
uint256 tokenId,
address _owner
) external override onlyFarmingCenter returns (uint256 reward, uint256 bonusReward) {
bytes32 incentiveId = IncentiveId.compute(key);
Incentive storage incentive = incentives[incentiveId];
require(incentive.totalReward > 0, 'non-existent incentive');
IAlgebraEternalVirtualPool virtualPool = IAlgebraEternalVirtualPool(incentive.virtualPoolAddress);
Farm memory farm = farms[tokenId][incentiveId];
require(farm.liquidity != 0, 'farm does not exist');
(uint256 innerRewardGrowth0, uint256 innerRewardGrowth1) = virtualPool.getInnerRewardsGrowth(
farm.tickLower,
farm.tickUpper
);
(reward, bonusReward) = (
FullMath.mulDiv(innerRewardGrowth0 - farm.innerRewardGrowth0, farm.liquidity, Constants.Q128),
FullMath.mulDiv(innerRewardGrowth1 - farm.innerRewardGrowth1, farm.liquidity, Constants.Q128)
);
farms[tokenId][incentiveId].innerRewardGrowth0 = innerRewardGrowth0;
farms[tokenId][incentiveId].innerRewardGrowth1 = innerRewardGrowth1;
mapping(IERC20Minimal => uint256) storage rewardBalances = rewards[_owner];
if (reward != 0) {
rewardBalances[key.rewardToken] += reward; // user must claim before overflow
}
if (bonusReward != 0) {
rewardBalances[key.bonusRewardToken] += bonusReward; // user must claim before overflow
}
emit RewardsCollected(tokenId, incentiveId, reward, bonusReward);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '../interfaces/IAlgebraFarming.sol';
import '../interfaces/IFarmingCenter.sol';
import './IAlgebraVirtualPoolBase.sol';
import '../libraries/IncentiveId.sol';
import '../libraries/NFTPositionInfo.sol';
import '../libraries/LiquidityTier.sol';
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraPoolDeployer.sol';
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraPool.sol';
import '@cryptoalgebra/core/contracts/interfaces/IERC20Minimal.sol';
import '@cryptoalgebra/core/contracts/libraries/SafeCast.sol';
import '@cryptoalgebra/core/contracts/libraries/TickMath.sol';
import '@cryptoalgebra/core/contracts/libraries/Constants.sol';
import '@cryptoalgebra/core/contracts/libraries/LowGasSafeMath.sol';
import '@cryptoalgebra/core/contracts/libraries/FullMath.sol';
import '@cryptoalgebra/periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '@cryptoalgebra/periphery/contracts/libraries/TransferHelper.sol';
/// @title Abstract base contract for Algebra farmings
abstract contract AlgebraFarming is IAlgebraFarming {
using SafeCast for int256;
using LowGasSafeMath for uint256;
/// @notice Represents a farming incentive
struct Incentive {
uint256 totalReward;
uint256 bonusReward;
address virtualPoolAddress;
uint24 minimalPositionWidth;
uint224 totalLiquidity;
address multiplierToken;
Tiers tiers;
}
/// @inheritdoc IAlgebraFarming
INonfungiblePositionManager public immutable override nonfungiblePositionManager;
/// @inheritdoc IAlgebraFarming
IAlgebraPoolDeployer public immutable override deployer;
IFarmingCenter public farmingCenter;
/// @dev bytes32 refers to the return value of IncentiveId.compute
/// @inheritdoc IAlgebraFarming
mapping(bytes32 => Incentive) public override incentives;
address internal incentiveMaker;
address internal owner;
/// @dev rewards[owner][rewardToken] => uint256
/// @inheritdoc IAlgebraFarming
mapping(address => mapping(IERC20Minimal => uint256)) public override rewards;
modifier onlyIncentiveMaker() {
require(msg.sender == incentiveMaker);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyFarmingCenter() {
require(msg.sender == address(farmingCenter));
_;
}
/// @param _deployer pool deployer contract address
/// @param _nonfungiblePositionManager the NFT position manager contract address
constructor(IAlgebraPoolDeployer _deployer, INonfungiblePositionManager _nonfungiblePositionManager) {
owner = msg.sender;
deployer = _deployer;
nonfungiblePositionManager = _nonfungiblePositionManager;
}
/// @inheritdoc IAlgebraFarming
function setIncentiveMaker(address _incentiveMaker) external override onlyOwner {
require(incentiveMaker != _incentiveMaker);
incentiveMaker = _incentiveMaker;
emit IncentiveMaker(_incentiveMaker);
}
/// @inheritdoc IAlgebraFarming
function setOwner(address _owner) external override onlyOwner {
require(_owner != owner);
owner = _owner;
emit Owner(_owner);
}
/// @inheritdoc IAlgebraFarming
function setFarmingCenterAddress(address _farmingCenter) external override onlyOwner {
require(_farmingCenter != address(farmingCenter));
farmingCenter = IFarmingCenter(_farmingCenter);
emit FarmingCenter(_farmingCenter);
}
/// @inheritdoc IAlgebraFarming
function claimReward(
IERC20Minimal rewardToken,
address to,
uint256 amountRequested
) external override returns (uint256 reward) {
return _claimReward(rewardToken, msg.sender, to, amountRequested);
}
/// @inheritdoc IAlgebraFarming
function claimRewardFrom(
IERC20Minimal rewardToken,
address from,
address to,
uint256 amountRequested
) external override onlyFarmingCenter returns (uint256 reward) {
return _claimReward(rewardToken, from, to, amountRequested);
}
function _connectPoolToVirtualPool(IAlgebraPool pool, address virtualPool) private {
farmingCenter.connectVirtualPool(pool, virtualPool);
}
function _getCurrentVirtualPools(IAlgebraPool pool) internal view returns (address incentive, address eternal) {
return farmingCenter.virtualPoolAddresses(address(pool));
}
function _receiveRewards(
IncentiveKey memory key,
uint256 reward,
uint256 bonusReward,
Incentive storage incentive
) internal returns (uint256 receivedReward, uint256 receivedBonusReward) {
if (reward > 0) {
IERC20Minimal rewardToken = key.rewardToken;
uint256 balanceBefore = rewardToken.balanceOf(address(this));
TransferHelper.safeTransferFrom(address(rewardToken), msg.sender, address(this), reward);
require((receivedReward = rewardToken.balanceOf(address(this))) > balanceBefore);
receivedReward -= balanceBefore;
incentive.totalReward = incentive.totalReward.add(receivedReward);
}
if (bonusReward > 0) {
IERC20Minimal bonusRewardToken = key.bonusRewardToken;
uint256 balanceBefore = bonusRewardToken.balanceOf(address(this));
TransferHelper.safeTransferFrom(address(bonusRewardToken), msg.sender, address(this), bonusReward);
require((receivedBonusReward = bonusRewardToken.balanceOf(address(this))) > balanceBefore);
receivedBonusReward -= balanceBefore;
incentive.bonusReward = incentive.bonusReward.add(receivedBonusReward);
}
}
function _createFarming(
address virtualPool,
IncentiveKey memory key,
uint256 reward,
uint256 bonusReward,
uint24 minimalPositionWidth,
address multiplierToken,
Tiers calldata tiers
)
internal
returns (
bytes32 incentiveId,
uint256 receivedReward,
uint256 receivedBonusReward
)
{
_connectPoolToVirtualPool(key.pool, virtualPool);
incentiveId = IncentiveId.compute(key);
Incentive storage newIncentive = incentives[incentiveId];
(receivedReward, receivedBonusReward) = _receiveRewards(key, reward, bonusReward, newIncentive);
require(
minimalPositionWidth <=
((int256(TickMath.MAX_TICK) / Constants.TICK_SPACING) *
Constants.TICK_SPACING -
(int256(TickMath.MIN_TICK) / Constants.TICK_SPACING) *
Constants.TICK_SPACING),
'minimalPositionWidth too wide'
);
newIncentive.virtualPoolAddress = virtualPool;
newIncentive.minimalPositionWidth = minimalPositionWidth;
require(
tiers.tier1Multiplier <= LiquidityTier.MAX_MULTIPLIER &&
tiers.tier2Multiplier <= LiquidityTier.MAX_MULTIPLIER &&
tiers.tier3Multiplier <= LiquidityTier.MAX_MULTIPLIER,
'Multiplier cant be greater than MAX_MULTIPLIER'
);
require(
tiers.tier1Multiplier >= LiquidityTier.DENOMINATOR &&
tiers.tier2Multiplier >= LiquidityTier.DENOMINATOR &&
tiers.tier3Multiplier >= LiquidityTier.DENOMINATOR,
'Multiplier cant be less than DENOMINATOR'
);
newIncentive.tiers = tiers;
newIncentive.multiplierToken = multiplierToken;
}
function _detachIncentive(IncentiveKey memory key, address currentVirtualPool) internal {
require(currentVirtualPool != address(0), 'Farming do not exist');
require(
incentives[IncentiveId.compute(key)].virtualPoolAddress == currentVirtualPool,
'Another farming is active'
);
_connectPoolToVirtualPool(key.pool, address(0));
emit IncentiveDetached(
key.rewardToken,
key.bonusRewardToken,
key.pool,
currentVirtualPool,
key.startTime,
key.endTime
);
}
function _attachIncentive(IncentiveKey memory key, address currentVirtualPool) internal {
require(currentVirtualPool == address(0), 'Farming already exists');
address virtualPoolAddress = incentives[IncentiveId.compute(key)].virtualPoolAddress;
require(virtualPoolAddress != address(0), 'Invalid farming');
_connectPoolToVirtualPool(key.pool, virtualPoolAddress);
emit IncentiveAttached(
key.rewardToken,
key.bonusRewardToken,
key.pool,
virtualPoolAddress,
key.startTime,
key.endTime
);
}
function _enterFarming(
IncentiveKey memory key,
uint256 tokenId,
uint256 tokensLocked
)
internal
returns (
bytes32 incentiveId,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address virtualPool
)
{
incentiveId = IncentiveId.compute(key);
Incentive storage incentive = incentives[incentiveId];
require(incentive.totalReward > 0, 'non-existent incentive');
IAlgebraPool pool;
(pool, tickLower, tickUpper, liquidity) = NFTPositionInfo.getPositionInfo(
deployer,
nonfungiblePositionManager,
tokenId
);
require(pool == key.pool, 'invalid pool for token');
require(liquidity > 0, 'cannot farm token with 0 liquidity');
(, int24 tick, , , , , ) = pool.globalState();
uint32 multiplier = LiquidityTier.getLiquidityMultiplier(tokensLocked, incentive.tiers);
uint256 liquidityAmountWithMultiplier = FullMath.mulDiv(liquidity, multiplier, LiquidityTier.DENOMINATOR);
require(liquidityAmountWithMultiplier <= type(uint128).max);
liquidity = uint128(liquidityAmountWithMultiplier);
virtualPool = incentive.virtualPoolAddress;
uint24 minimalAllowedTickWidth = incentive.minimalPositionWidth;
require(int256(tickUpper) - int256(tickLower) >= int256(minimalAllowedTickWidth), 'position too narrow');
IAlgebraVirtualPoolBase(virtualPool).applyLiquidityDeltaToPosition(
uint32(block.timestamp),
tickLower,
tickUpper,
int256(liquidity).toInt128(),
tick
);
}
function _claimReward(
IERC20Minimal rewardToken,
address from,
address to,
uint256 amountRequested
) internal returns (uint256 reward) {
reward = rewards[from][rewardToken];
if (amountRequested == 0 || amountRequested > reward) {
amountRequested = reward;
}
rewards[from][rewardToken] = reward - amountRequested;
TransferHelper.safeTransfer(address(rewardToken), to, amountRequested);
emit RewardClaimed(to, amountRequested, address(rewardToken), from);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
import '@cryptoalgebra/core/contracts/libraries/TickManager.sol';
import '@cryptoalgebra/core/contracts/libraries/TickTable.sol';
import '@cryptoalgebra/core/contracts/libraries/LiquidityMath.sol';
import './IAlgebraVirtualPoolBase.sol';
/// @title Abstract base contract for Algebra virtual pools
abstract contract AlgebraVirtualPoolBase is IAlgebraVirtualPoolBase {
using TickTable for mapping(int16 => uint256);
address public immutable farmingCenterAddress;
address public immutable farmingAddress;
address public immutable pool;
/// @inheritdoc IAlgebraVirtualPoolBase
mapping(int24 => TickManager.Tick) public override ticks;
mapping(int16 => uint256) internal tickTable;
/// @inheritdoc IAlgebraVirtualPoolBase
uint128 public override currentLiquidity;
/// @inheritdoc IAlgebraVirtualPoolBase
int24 public override globalTick;
/// @inheritdoc IAlgebraVirtualPoolBase
uint32 public override timeOutside;
/// @inheritdoc IAlgebraVirtualPoolBase
uint160 public override globalSecondsPerLiquidityCumulative;
/// @inheritdoc IAlgebraVirtualPoolBase
uint32 public override prevTimestamp;
/// @notice only pool (or FarmingCenter as "proxy") can call
modifier onlyFromPool() {
require(msg.sender == farmingCenterAddress || msg.sender == pool, 'only pool can call this function');
_;
}
modifier onlyFarming() {
require(msg.sender == farmingAddress, 'only farming can call this function');
_;
}
constructor(
address _farmingCenterAddress,
address _farmingAddress,
address _pool
) {
farmingCenterAddress = _farmingCenterAddress;
farmingAddress = _farmingAddress;
pool = _pool;
}
/// @notice get seconds per liquidity inside range
function getInnerSecondsPerLiquidity(int24 bottomTick, int24 topTick)
external
view
override
returns (uint160 innerSecondsSpentPerLiquidity)
{
uint160 lowerSecondsPerLiquidity = ticks[bottomTick].outerSecondsPerLiquidity;
uint160 upperSecondsPerLiquidity = ticks[topTick].outerSecondsPerLiquidity;
if (globalTick < bottomTick) {
return (lowerSecondsPerLiquidity - upperSecondsPerLiquidity);
} else if (globalTick < topTick) {
return (globalSecondsPerLiquidityCumulative - lowerSecondsPerLiquidity - upperSecondsPerLiquidity);
} else {
return (upperSecondsPerLiquidity - lowerSecondsPerLiquidity);
}
}
/// @dev logic of tick crossing differs in virtual pools
function _crossTick(int24 nextTick) internal virtual returns (int128 liquidityDelta);
/// @inheritdoc IAlgebraVirtualPool
function cross(int24 nextTick, bool zeroToOne) external override onlyFromPool {
if (ticks[nextTick].initialized) {
int128 liquidityDelta = _crossTick(nextTick);
if (zeroToOne) liquidityDelta = -liquidityDelta;
currentLiquidity = LiquidityMath.addDelta(currentLiquidity, liquidityDelta);
}
globalTick = zeroToOne ? nextTick - 1 : nextTick;
}
/// @dev logic of cumulatives differs in virtual pools
function _increaseCumulative(uint32 currentTimestamp) internal virtual returns (Status);
/// @inheritdoc IAlgebraVirtualPool
function increaseCumulative(uint32 currentTimestamp) external override onlyFromPool returns (Status) {
return _increaseCumulative(currentTimestamp);
}
/// @dev logic of tick updating differs in virtual pools
function _updateTick(
int24 tick,
int24 currentTick,
int128 liquidityDelta,
bool isTopTick
) internal virtual returns (bool updated);
/// @inheritdoc IAlgebraVirtualPoolBase
function applyLiquidityDeltaToPosition(
uint32 currentTimestamp,
int24 bottomTick,
int24 topTick,
int128 liquidityDelta,
int24 currentTick
) external override onlyFarming {
globalTick = currentTick;
if (currentTimestamp > prevTimestamp) {
_increaseCumulative(currentTimestamp);
}
if (liquidityDelta != 0) {
// if we need to update the ticks, do it
bool flippedBottom;
bool flippedTop;
if (_updateTick(bottomTick, currentTick, liquidityDelta, false)) {
flippedBottom = true;
tickTable.toggleTick(bottomTick);
}
if (_updateTick(topTick, currentTick, liquidityDelta, true)) {
flippedTop = true;
tickTable.toggleTick(topTick);
}
if (currentTick >= bottomTick && currentTick < topTick) {
currentLiquidity = LiquidityMath.addDelta(currentLiquidity, liquidityDelta);
}
// clear any tick data that is no longer needed
if (liquidityDelta < 0) {
if (flippedBottom) {
delete ticks[bottomTick];
}
if (flippedTop) {
delete ticks[topTick];
}
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
library Constants {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
// fee value in hundredths of a bip, i.e. 1e-6
uint16 internal constant BASE_FEE = 100;
int24 internal constant TICK_SPACING = 60;
// max(uint128) / ( (MAX_TICK - MIN_TICK) / TICK_SPACING )
uint128 internal constant MAX_LIQUIDITY_PER_TICK = 11505743598341114571880798222544994;
uint32 internal constant MAX_LIQUIDITY_COOLDOWN = 1 days;
uint8 internal constant MAX_COMMUNITY_FEE = 250;
uint256 internal constant COMMUNITY_FEE_DENOMINATOR = 1000;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
import '@cryptoalgebra/core/contracts/libraries/TickManager.sol';
import '@cryptoalgebra/core/contracts/libraries/FullMath.sol';
import '@cryptoalgebra/core/contracts/libraries/Constants.sol';
import '@cryptoalgebra/core/contracts/libraries/LowGasSafeMath.sol';
import './interfaces/IAlgebraEternalVirtualPool.sol';
import '../AlgebraVirtualPoolBase.sol';
contract EternalVirtualPool is AlgebraVirtualPoolBase, IAlgebraEternalVirtualPool {
using TickManager for mapping(int24 => TickManager.Tick);
using LowGasSafeMath for uint256;
uint128 public rewardRate0;
uint128 public rewardRate1;
uint256 public rewardReserve0;
uint256 public rewardReserve1;
uint256 public totalRewardGrowth0;
uint256 public totalRewardGrowth1;
constructor(
address _farmingCenterAddress,
address _farmingAddress,
address _pool
) AlgebraVirtualPoolBase(_farmingCenterAddress, _farmingAddress, _pool) {
prevTimestamp = uint32(block.timestamp);
}
function addRewards(uint256 token0Amount, uint256 token1Amount) external override onlyFarming {
_increaseCumulative(uint32(block.timestamp));
if (token0Amount > 0) rewardReserve0 = rewardReserve0.add(token0Amount);
if (token1Amount > 0) rewardReserve1 = rewardReserve1.add(token1Amount);
}
// @inheritdoc IAlgebraEternalVirtualPool
function setRates(uint128 rate0, uint128 rate1) external override onlyFarming {
_increaseCumulative(uint32(block.timestamp));
(rewardRate0, rewardRate1) = (rate0, rate1);
}
// @inheritdoc IAlgebraEternalVirtualPool
function getInnerRewardsGrowth(int24 bottomTick, int24 topTick)
external
view
override
returns (uint256 rewardGrowthInside0, uint256 rewardGrowthInside1)
{
return ticks.getInnerFeeGrowth(bottomTick, topTick, globalTick, totalRewardGrowth0, totalRewardGrowth1);
}
function _crossTick(int24 nextTick) internal override returns (int128 liquidityDelta) {
return ticks.cross(nextTick, totalRewardGrowth0, totalRewardGrowth1, globalSecondsPerLiquidityCumulative, 0, 0);
}
function _increaseCumulative(uint32 currentTimestamp) internal override returns (Status) {
uint256 timeDelta = currentTimestamp - prevTimestamp; // safe until timedelta > 136 years
if (timeDelta == 0) return Status.ACTIVE; // only once per block
uint256 _currentLiquidity = currentLiquidity; // currentLiquidity is uint128
if (_currentLiquidity > 0) {
(uint256 _rewardRate0, uint256 _rewardRate1) = (rewardRate0, rewardRate1);
uint256 _rewardReserve0 = _rewardRate0 > 0 ? rewardReserve0 : 0;
uint256 _rewardReserve1 = _rewardRate1 > 0 ? rewardReserve1 : 0;
if (_rewardReserve0 > 0) {
uint256 reward0 = _rewardRate0 * timeDelta;
if (reward0 > _rewardReserve0) reward0 = _rewardReserve0;
rewardReserve0 = _rewardReserve0 - reward0;
totalRewardGrowth0 += FullMath.mulDiv(reward0, Constants.Q128, _currentLiquidity);
}
if (_rewardReserve1 > 0) {
uint256 reward1 = _rewardRate1 * timeDelta;
if (reward1 > _rewardReserve1) reward1 = _rewardReserve1;
rewardReserve1 = _rewardReserve1 - reward1;
totalRewardGrowth1 += FullMath.mulDiv(reward1, Constants.Q128, _currentLiquidity);
}
globalSecondsPerLiquidityCumulative += (uint160(timeDelta) << 128) / uint160(_currentLiquidity);
prevTimestamp = currentTimestamp; // duplicated for gas optimization
} else {
timeOutside += uint32(timeDelta);
prevTimestamp = currentTimestamp; // duplicated for gas optimization
}
return Status.ACTIVE;
}
function _updateTick(
int24 tick,
int24 currentTick,
int128 liquidityDelta,
bool isTopTick
) internal override returns (bool updated) {
return
ticks.update(tick, currentTick, liquidityDelta, totalRewardGrowth0, totalRewardGrowth1, 0, 0, 0, isTopTick);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.4.0 || ^0.5.0 || ^0.6.0 || ^0.7.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
// Subtract 256 bit remainder from 512 bit number
assembly {
let remainder := mulmod(a, b, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the preconditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
if (a == 0 || ((result = a * b) / a == b)) {
require(denominator > 0);
assembly {
result := add(div(result, denominator), gt(mod(result, denominator), 0))
}
} else {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
/// @notice Returns ceil(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '../../../interfaces/IAlgebraFarming.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 is IAlgebraFarming {
struct IncentiveParams {
uint256 reward; // The amount of reward tokens to be distributed
uint256 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)
address multiplierToken; // The address of token which can be locked to get liquidity multiplier
}
/// @notice Event emitted when reward rates were changed
/// @param rewardRate The new rate of main token distribution per sec
/// @param bonusRewardRate The new rate of bonus token 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 added
/// @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 Returns information about a farmd liquidity NFT
/// @param tokenId The ID of the farmd token
/// @param incentiveId The ID of the incentive for which the token is farmd
/// @return liquidity The amount of liquidity in the NFT as of the last time the rewards were computed,
/// tickLower The lower tick of position,
/// tickUpper The upper tick of position,
/// innerRewardGrowth0 The last saved reward0 growth inside position,
/// 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 Creates a new liquidity mining incentive program
/// @param key Details of the incentive to create
/// @param params Params of incentive
/// @param tiers The amounts of locked token for liquidity multipliers
/// @return virtualPool The virtual pool
function createEternalFarming(
IncentiveKey memory key,
IncentiveParams memory params,
Tiers calldata tiers
) external returns (address virtualPool);
function addRewards(
IncentiveKey memory key,
uint256 rewardAmount,
uint256 bonusRewardAmount
) external;
function setRates(
IncentiveKey memory key,
uint128 rewardRate,
uint128 bonusRewardRate
) external;
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 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 startTime The time when the incentive program begins
/// @param endTime The time when rewards stop accruing
/// @param reward The amount of reward tokens to be distributed
/// @param bonusReward The amount of bonus reward tokens to be distributed
/// @param tiers The amounts of locked token for liquidity multipliers
/// @param multiplierToken The address of token which can be locked to get liquidity multiplier
/// @param minimalAllowedPositionWidth The minimal allowed position width (tickUpper - tickLower)
event EternalFarmingCreated(
IERC20Minimal indexed rewardToken,
IERC20Minimal indexed bonusRewardToken,
IAlgebraPool indexed pool,
address virtualPool,
uint256 startTime,
uint256 endTime,
uint256 reward,
uint256 bonusReward,
Tiers tiers,
address multiplierToken,
uint24 minimalAllowedPositionWidth
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '../../IAlgebraVirtualPoolBase.sol';
interface IAlgebraEternalVirtualPool is IAlgebraVirtualPoolBase {
/// @notice Change reward rates
/// @param rate0 The new rate of main token distribution per sec
/// @param rate1 The new rate of bonus token distribution per sec
function setRates(uint128 rate0, uint128 rate1) external;
function addRewards(uint256 token0Amount, uint256 token1Amount) external;
function getInnerRewardsGrowth(int24 bottomTick, int24 topTick)
external
view
returns (uint256 rewardGrowthInside0, uint256 rewardGrowthInside1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/**
* @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 the owner of the factory is changed
* @param newOwner The owner after the owner was changed
*/
event Owner(address indexed newOwner);
/**
* @notice Emitted when the vault address is changed
* @param newVaultAddress The vault address after the address was changed
*/
event VaultAddress(address indexed newVaultAddress);
/**
* @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 the farming address is changed
* @param newFarmingAddress The farming address after the address was changed
*/
event FarmingAddress(address indexed newFarmingAddress);
event FeeConfiguration(
uint16 alpha1,
uint16 alpha2,
uint32 beta1,
uint32 beta2,
uint16 gamma1,
uint16 gamma2,
uint32 volumeBeta,
uint16 volumeGamma,
uint16 baseFee
);
/**
* @notice Returns the current owner of the factory
* @dev Can be changed by the current owner via setOwner
* @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);
/**
* @dev Is retrieved from the pools to restrict calling
* certain functions not by a tokenomics contract
* @return The tokenomics contract address
*/
function farmingAddress() external view returns (address);
function vaultAddress() external view returns (address);
/**
* @notice Returns the pool address for a given pair of tokens and a fee, 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 Creates a pool for the given two tokens and fee
* @param tokenA One of the two tokens in the desired pool
* @param tokenB The other of the two tokens in the desired pool
* @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
* from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
* are invalid.
* @return pool The address of the newly created pool
*/
function createPool(address tokenA, address tokenB) external returns (address pool);
/**
* @notice Updates the owner of the factory
* @dev Must be called by the current owner
* @param _owner The new owner of the factory
*/
function setOwner(address _owner) external;
/**
* @dev updates tokenomics address on the factory
* @param _farmingAddress The new tokenomics contract address
*/
function setFarmingAddress(address _farmingAddress) external;
/**
* @dev updates vault address on the factory
* @param _vaultAddress The new vault contract address
*/
function setVaultAddress(address _vaultAddress) external;
/**
* @notice Changes initial fee configuration for new pools
* @dev changes coefficients for sigmoids: α / (1 + e^( (β-x) / γ))
* alpha1 + alpha2 + baseFee (max possible fee) must be <= type(uint16).max
* gammas must be > 0
* @param alpha1 max value of the first sigmoid
* @param alpha2 max value of the second sigmoid
* @param beta1 shift along the x-axis for the first sigmoid
* @param beta2 shift along the x-axis for the second sigmoid
* @param gamma1 horizontal stretch factor for the first sigmoid
* @param gamma2 horizontal stretch factor for the second sigmoid
* @param volumeBeta shift along the x-axis for the outer volume-sigmoid
* @param volumeGamma horizontal stretch factor the outer volume-sigmoid
* @param baseFee minimum possible fee
*/
function setBaseFeeConfiguration(
uint16 alpha1,
uint16 alpha2,
uint32 beta1,
uint32 beta2,
uint16 gamma1,
uint16 gamma2,
uint32 volumeBeta,
uint16 volumeGamma,
uint16 baseFee
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraPoolDeployer.sol';
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraPool.sol';
import '@cryptoalgebra/core/contracts/interfaces/IERC20Minimal.sol';
import '@cryptoalgebra/periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import './IIncentiveKey.sol';
/// @title Algebra Farming Interface
/// @notice Allows farming nonfungible liquidity tokens in exchange for reward tokens
interface IAlgebraFarming is IIncentiveKey {
/// @notice The nonfungible position manager with which this farming contract is compatible
function nonfungiblePositionManager() external view returns (INonfungiblePositionManager);
/// @notice The pool deployer
function deployer() external returns (IAlgebraPoolDeployer);
/// @notice Updates the incentive maker
/// @param _incentiveMaker The new incentive maker address
function setIncentiveMaker(address _incentiveMaker) external;
/// @notice Updates the owner address
/// @param owner The new owner address
function setOwner(address owner) external;
struct Tiers {
// amount of token to reach the tier
uint256 tokenAmountForTier1;
uint256 tokenAmountForTier2;
uint256 tokenAmountForTier3;
// 1 = 0.01%
uint32 tier1Multiplier;
uint32 tier2Multiplier;
uint32 tier3Multiplier;
}
/// @notice Represents a farming incentive
/// @param incentiveId The ID of the incentive computed from its parameters
function incentives(bytes32 incentiveId)
external
view
returns (
uint256 totalReward,
uint256 bonusReward,
address virtualPoolAddress,
uint24 minimalPositionWidth,
uint224 totalLiquidity,
address multiplierToken,
Tiers memory tiers
);
/// @notice Detach incentive from the pool
/// @param key The key of the incentive
function detachIncentive(IncentiveKey memory key) external;
/// @notice Attach incentive to the pool
/// @param key The key of the incentive
function attachIncentive(IncentiveKey memory key) external;
/// @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 enterFarming the NFT
/// @param tokenId The ID of the token to exitFarming
/// @param tokensLocked The amount of tokens locked for boost
function enterFarming(
IncentiveKey memory key,
uint256 tokenId,
uint256 tokensLocked
) external;
/// @notice exitFarmings for Algebra LP token
/// @param key The key of the incentive for which to exitFarming the NFT
/// @param tokenId The ID of the token to exitFarming
/// @param _owner Owner of the token
function exitFarming(
IncentiveKey memory key,
uint256 tokenId,
address _owner
) external;
/// @notice Transfers `amountRequested` of accrued `rewardToken` 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 reward The amount of reward tokens claimed
function claimReward(
IERC20Minimal rewardToken,
address to,
uint256 amountRequested
) external returns (uint256 reward);
/// @notice Transfers `amountRequested` of accrued `rewardToken` 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 reward The amount of reward tokens claimed
function claimRewardFrom(
IERC20Minimal rewardToken,
address from,
address to,
uint256 amountRequested
) external returns (uint256 reward);
/// @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 Event emitted when a liquidity mining incentive has been stopped from the outside
/// @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 detached virtual pool address
/// @param startTime The time when the incentive program begins
/// @param endTime The time when rewards stop accruing
event IncentiveDetached(
IERC20Minimal indexed rewardToken,
IERC20Minimal indexed bonusRewardToken,
IAlgebraPool indexed pool,
address virtualPool,
uint256 startTime,
uint256 endTime
);
/// @notice Event emitted when a liquidity mining incentive has been runned again from the outside
/// @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 attached virtual pool address
/// @param startTime The time when the incentive program begins
/// @param endTime The time when rewards stop accruing
event IncentiveAttached(
IERC20Minimal indexed rewardToken,
IERC20Minimal indexed bonusRewardToken,
IAlgebraPool indexed pool,
address virtualPool,
uint256 startTime,
uint256 endTime
);
/// @notice Event emitted when a Algebra LP token has been farmd
/// @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 farmd
/// @param tokensLocked The amount of tokens locked for multiplier
event FarmEntered(uint256 indexed tokenId, bytes32 indexed incentiveId, uint128 liquidity, uint256 tokensLocked);
/// @notice Event emitted when a Algebra LP token has been exitFarmingd
/// @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 distributed
/// @param bonusReward The amount of bonus reward tokens to be distributed
event FarmEnded(
uint256 indexed tokenId,
bytes32 indexed incentiveId,
address indexed rewardAddress,
address bonusRewardToken,
address owner,
uint256 reward,
uint256 bonusReward
);
/// @notice Emitted when the incentive maker is changed
/// @param incentiveMaker The incentive maker after the address was changed
event IncentiveMaker(address indexed incentiveMaker);
/// @notice Emitted when owner is changed
/// @param owner The owner after the address was changed
event Owner(address indexed owner);
/// @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 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 sent to
event RewardClaimed(address indexed to, uint256 reward, address indexed rewardAddress, address indexed owner);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '../../../interfaces/IAlgebraFarming.sol';
/// @title Algebra Farming Interface
/// @notice Allows farming nonfungible liquidity tokens in exchange for reward tokens
interface IAlgebraLimitFarming is IAlgebraFarming {
struct IncentiveParams {
uint256 reward; // The amount of reward tokens to be distributed
uint256 bonusReward; // The amount of bonus reward tokens to be distributed
uint24 minimalPositionWidth; // The minimal allowed width of position (tickUpper - tickLower)
address multiplierToken; // The address of token which can be locked to get liquidity multiplier
uint32 enterStartTime; // The time when enter should become possible
}
/// @notice The max duration of an incentive in seconds
function maxIncentiveDuration() external view returns (uint256);
/// @notice The max amount of seconds into the future the incentive startTime can be set
function maxIncentiveStartLeadTime() external view returns (uint256);
/// @notice Returns information about a farmd liquidity NFT
/// @param tokenId The ID of the farmd token
/// @param incentiveId The ID of the incentive for which the token is farmd
/// @return liquidity The amount of liquidity in the NFT as of the last time the rewards were computed,
/// tickLower The lower end of the tick range for the position,
/// tickUpper The upper end of the tick range for the position
function farms(uint256 tokenId, bytes32 incentiveId)
external
view
returns (
uint128 liquidity,
int24 tickLower,
int24 tickUpper
);
function createLimitFarming(
IncentiveKey memory key,
Tiers calldata tiers,
IncentiveParams memory params
) external returns (address virtualPool);
function addRewards(
IncentiveKey memory key,
uint256 reward,
uint256 bonusReward
) external;
function decreaseRewardsAmount(
IncentiveKey memory key,
uint256 rewardAmount,
uint256 bonusRewardAmount
) external;
/// @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 startTime The time when the incentive program begins
/// @param endTime The time when rewards stop accruing
/// @param reward The amount of reward tokens to be distributed
/// @param bonusReward The amount of bonus reward tokens to be distributed
/// @param tiers The amounts of locked token for liquidity multipliers
/// @param multiplierToken The address of token which can be locked to get liquidity multiplier
/// @param minimalAllowedPositionWidth The minimal allowed position width (tickUpper - tickLower)
/// @param enterStartTime The time when enter becomes possible
event LimitFarmingCreated(
IERC20Minimal indexed rewardToken,
IERC20Minimal indexed bonusRewardToken,
IAlgebraPool indexed pool,
uint256 startTime,
uint256 endTime,
uint256 reward,
uint256 bonusReward,
Tiers tiers,
address multiplierToken,
uint24 minimalAllowedPositionWidth,
uint32 enterStartTime
);
event RewardAmountsDecreased(uint256 reward, uint256 bonusReward, bytes32 incentiveId);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IAlgebraPoolImmutables.sol';
import './pool/IAlgebraPoolState.sol';
import './pool/IAlgebraPoolDerivedState.sol';
import './pool/IAlgebraPoolActions.sol';
import './pool/IAlgebraPoolPermissionedActions.sol';
import './pool/IAlgebraPoolEvents.sol';
/**
* @title The interface for a Algebra Pool
* @dev The pool interface is broken up into many smaller pieces.
* 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,
IAlgebraPoolDerivedState,
IAlgebraPoolActions,
IAlgebraPoolPermissionedActions,
IAlgebraPoolEvents
{
// used only for combining interfaces
}
// 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
* @param price the initial sqrt price of the pool as a Q64.96
*/
function initialize(uint160 price) 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 sender 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 amount 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 sender,
address recipient,
int24 bottomTick,
int24 topTick,
uint128 amount,
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
* @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
) 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 amountSpecified 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 amountSpecified,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/**
* @notice Swap token0 for token1, or token1 for token0 (tokens that have fee on transfer)
* @dev The caller of this method receives a callback in the form of I AlgebraSwapCallback# AlgebraSwapCallback
* @param sender The address called this function (Comes from the Router)
* @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 amountSpecified 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 swapSupportingFeeOnInputTokens(
address sender,
address recipient,
bool zeroToOne,
int256 amountSpecified,
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 liquidity providers as an additional fee. So this method can be used
* to donate underlying tokens to currently in-range liquidity providers by calling with 0 amount{0,1} and sending
* the donation amount(s) from the callback
* @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;
}
// 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 Pools
* @notice A contract that constructs a pool must implement this to pass arguments to the pool
* @dev This is used to avoid having constructor arguments in the pool contract, which results in the init code hash
* of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain.
* Credit to Uniswap Labs under GPL-2.0-or-later license:
* https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
*/
interface IAlgebraPoolDeployer {
/**
* @notice Emitted when the factory address is changed
* @param factory The factory address after the address was changed
*/
event Factory(address indexed factory);
/**
* @notice Get the parameters to be used in constructing the pool, set transiently during pool creation.
* @dev Called by the pool constructor to fetch the parameters of the pool
* Returns dataStorage The pools associated dataStorage
* Returns factory The factory address
* Returns token0 The first token of the pool by address sort order
* Returns token1 The second token of the pool by address sort order
*/
function parameters()
external
view
returns (
address dataStorage,
address factory,
address token0,
address token1
);
/**
* @dev Deploys a pool with the given parameters by transiently setting the parameters storage slot and then
* clearing it after deploying the pool.
* @param dataStorage The pools associated dataStorage
* @param factory The contract address of the Algebra factory
* @param token0 The first token of the pool by address sort order
* @param token1 The second token of the pool by address sort order
* @return pool The deployed pool's address
*/
function deploy(
address dataStorage,
address factory,
address token0,
address token1
) external returns (address pool);
/**
* @dev Sets the factory address to the poolDeployer for permissioned actions
* @param factory The address of the Algebra factory
*/
function setFactory(address factory) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/**
* @title Pool state that is not stored
* @notice Contains view functions to provide information about the pool that is computed rather than stored on the
* blockchain. The functions here may have variable gas costs.
* @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
* https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
*/
interface IAlgebraPoolDerivedState {
/**
* @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
* @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
* the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
* you must call it with secondsAgos = [3600, 0].
* @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
* log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
* @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
* @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
* @return secondsPerLiquidityCumulatives Cumulative seconds per liquidity-in-range value as of each `secondsAgos`
* from the current block timestamp
* @return volatilityCumulatives Cumulative standard deviation as of each `secondsAgos`
* @return volumePerAvgLiquiditys Cumulative swap volume per liquidity as of each `secondsAgos`
*/
function getTimepoints(uint32[] calldata secondsAgos)
external
view
returns (
int56[] memory tickCumulatives,
uint160[] memory secondsPerLiquidityCumulatives,
uint112[] memory volatilityCumulatives,
uint256[] memory volumePerAvgLiquiditys
);
/**
* @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
* @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
* I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
* snapshot is taken and the second snapshot is taken.
* @param bottomTick The lower tick of the range
* @param topTick The upper tick of the range
* @return innerTickCumulative The snapshot of the tick accumulator for the range
* @return innerSecondsSpentPerLiquidity The snapshot of seconds per liquidity for the range
* @return innerSecondsSpent The snapshot of the number of seconds during which the price was in this range
*/
function getInnerCumulatives(int24 bottomTick, int24 topTick)
external
view
returns (
int56 innerTickCumulative,
uint160 innerSecondsSpentPerLiquidity,
uint32 innerSecondsSpent
);
}
// 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/Swap 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
* @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
* @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 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 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 community fee is changed by the pool
* @param communityFee0New The updated value of the token0 community fee percent
* @param communityFee1New The updated value of the token1 community fee percent
*/
event CommunityFee(uint8 communityFee0New, uint8 communityFee1New);
/**
* @notice Emitted when new activeIncentive is set
* @param virtualPoolAddress The address of a virtual pool associated with the current active incentive
*/
event Incentive(address indexed virtualPoolAddress);
/**
* @notice Emitted when the fee changes
* @param fee The value of the token fee
*/
event Fee(uint16 fee);
/**
* @notice Emitted when the LiquidityCooldown changes
* @param liquidityCooldown The value of locktime for added liquidity
*/
event LiquidityCooldown(uint32 liquidityCooldown);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '../IDataStorageOperator.sol';
/// @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 contract that stores all the timepoints and can perform actions with them
* @return The operator address
*/
function dataStorageOperator() external view returns (address);
/**
* @notice The contract that deployed the pool, 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 pool tick spacing
* @dev Ticks can only be used 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, ...
* This value is an int24 to avoid casting even though it is always positive.
* @return The tick spacing
*/
function tickSpacing() external view returns (int24);
/**
* @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);
}
// 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 the factory owner or tokenomics
* @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. Cannot exceed 25% (250)
* @param communityFee0 new community fee percent for token0 of the pool in thousandths (1e-3)
* @param communityFee1 new community fee percent for token1 of the pool in thousandths (1e-3)
*/
function setCommunityFee(uint8 communityFee0, uint8 communityFee1) external;
/**
* @notice Sets an active incentive
* @param virtualPoolAddress The address of a virtual pool associated with the incentive
*/
function setIncentive(address virtualPoolAddress) external;
/**
* @notice Sets new lock time for added liquidity
* @param newLiquidityCooldown The time in seconds
*/
function setLiquidityCooldown(uint32 newLiquidityCooldown) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolState {
/**
* @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.
* @return price The current price of the pool as a sqrt(token1/token0) Q64.96 value;
* Returns tick The current tick of the pool, i.e. according to the last tick transition that was run;
* Returns This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick
* boundary;
* Returns fee The last pool fee value in hundredths of a bip, i.e. 1e-6;
* Returns timepointIndex The index of the last written timepoint;
* Returns communityFeeToken0 The community fee percentage of the swap fee in thousandths (1e-3) for token0;
* Returns communityFeeToken1 The community fee percentage of the swap fee in thousandths (1e-3) for token1;
* Returns unlocked Whether the pool is currently locked to reentrancy;
*/
function globalState()
external
view
returns (
uint160 price,
int24 tick,
uint16 fee,
uint16 timepointIndex,
uint8 communityFeeToken0,
uint8 communityFeeToken1,
bool unlocked
);
/**
* @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
*/
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
*/
function totalFeeGrowth1Token() external view returns (uint256);
/**
* @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
*/
function liquidity() external view returns (uint128);
/**
* @notice Look up information about a specific tick in the pool
* @dev This is a public structure, so the `return` natspec tags are omitted.
* @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;
* Returns liquidityDelta how much liquidity changes when the pool price crosses the tick;
* Returns outerFeeGrowth0Token the fee growth on the other side of the tick from the current tick in token0;
* Returns outerFeeGrowth1Token the fee growth on the other side of the tick from the current tick in token1;
* Returns outerTickCumulative the cumulative tick value on the other side of the tick from the current tick;
* Returns outerSecondsPerLiquidity the seconds spent per liquidity on the other side of the tick from the current tick;
* Returns outerSecondsSpent the seconds spent on the other side of the tick from the current tick;
* Returns initialized Set to true if the tick is initialized, i.e. liquidityTotal is greater than 0
* otherwise equal to false. Outside values can only be used if the tick is initialized.
* 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 (
uint128 liquidityTotal,
int128 liquidityDelta,
uint256 outerFeeGrowth0Token,
uint256 outerFeeGrowth1Token,
int56 outerTickCumulative,
uint160 outerSecondsPerLiquidity,
uint32 outerSecondsSpent,
bool initialized
);
/** @notice Returns 256 packed tick initialized boolean values. See TickTable for more information */
function tickTable(int16 wordPosition) external view returns (uint256);
/**
* @notice Returns the information about a position by the position's key
* @dev This is a public mapping of structures, so the `return` natspec tags are omitted.
* @param key The position's key is a hash of a preimage composed by the owner, bottomTick and topTick
* @return liquidityAmount The amount of liquidity in the position;
* Returns lastLiquidityAddTimestamp Timestamp of last adding of liquidity;
* Returns innerFeeGrowth0Token Fee growth of token0 inside the tick range as of the last mint/burn/poke;
* Returns innerFeeGrowth1Token Fee growth of token1 inside the tick range as of the last mint/burn/poke;
* Returns fees0 The computed amount of token0 owed to the position as of the last mint/burn/poke;
* Returns fees1 The computed amount of token1 owed to the position as of the last mint/burn/poke
*/
function positions(bytes32 key)
external
view
returns (
uint128 liquidityAmount,
uint32 lastLiquidityAddTimestamp,
uint256 innerFeeGrowth0Token,
uint256 innerFeeGrowth1Token,
uint128 fees0,
uint128 fees1
);
/**
* @notice Returns data about a specific timepoint index
* @param index The element of the timepoints array to fetch
* @dev You most likely want to use #getTimepoints() instead of this method to get an timepoint as of some amount of time
* ago, rather than at a specific index in the array.
* This is a public mapping of structures, so the `return` natspec tags are omitted.
* @return initialized whether the timepoint has been initialized and the values are safe to use;
* Returns blockTimestamp The timestamp of the timepoint;
* Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the timepoint timestamp;
* Returns secondsPerLiquidityCumulative the seconds per in range liquidity for the life of the pool as of the timepoint timestamp;
* Returns volatilityCumulative Cumulative standard deviation for the life of the pool as of the timepoint timestamp;
* Returns averageTick Time-weighted average tick;
* Returns volumePerLiquidityCumulative Cumulative swap volume per liquidity for the life of the pool as of the timepoint timestamp;
*/
function timepoints(uint256 index)
external
view
returns (
bool initialized,
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulative,
uint88 volatilityCumulative,
int24 averageTick,
uint144 volumePerLiquidityCumulative
);
/**
* @notice Returns the information about active incentive
* @dev if there is no active incentive at the moment, virtualPool,endTimestamp,startTimestamp would be equal to 0
* @return virtualPool The address of a virtual pool associated with the current active incentive
*/
function activeIncentive() external view returns (address virtualPool);
/**
* @notice Returns the lock time for added liquidity
*/
function liquidityCooldown() external view returns (uint32 cooldownInSeconds);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
interface IAlgebraVirtualPool {
enum Status {
NOT_EXIST,
ACTIVE,
NOT_STARTED
}
/**
* @dev This function is called by the main pool when an initialized tick is crossed there.
* If the tick is also initialized in a virtual pool it should be crossed too
* @param nextTick The crossed tick
* @param zeroToOne The direction
*/
function cross(int24 nextTick, bool zeroToOne) external;
/**
* @dev This function is called from the main pool before every swap To increase seconds per liquidity
* cumulative considering previous timestamp and liquidity. The liquidity is stored in a virtual pool
* @param currentTimestamp The timestamp of the current swap
* @return Status The status of virtual pool
*/
function increaseCumulative(uint32 currentTimestamp) external returns (Status);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraVirtualPool.sol';
/// @title Base interface for virtual pools
interface IAlgebraVirtualPoolBase is IAlgebraVirtualPool {
// returns how much time the price was out of any farmd liquidity
function timeOutside() external view returns (uint32);
// returns data associated with a tick
function ticks(int24 tickId)
external
view
returns (
uint128 liquidityTotal,
int128 liquidityDelta,
uint256 outerFeeGrowth0Token,
uint256 outerFeeGrowth1Token,
int56 outerTickCumulative,
uint160 outerSecondsPerLiquidity,
uint32 outerSecondsSpent,
bool initialized
);
// returns the current liquidity in virtual pool
function currentLiquidity() external view returns (uint128);
// returns the current tick in virtual pool
function globalTick() external view returns (int24);
// returns total seconds per farmd liquidity from the moment of initialization of the virtual pool
function globalSecondsPerLiquidityCumulative() external view returns (uint160);
// returns the timestamp after previous swap (like the last timepoint in a default pool)
function prevTimestamp() external view returns (uint32);
/// @notice This function is used to calculate the seconds per liquidity inside a certain position
/// @param bottomTick The bottom tick of a position
/// @param topTick The top tick of a position
/// @return innerSecondsSpentPerLiquidity The seconds per liquidity inside the position
function getInnerSecondsPerLiquidity(int24 bottomTick, int24 topTick)
external
view
returns (uint160 innerSecondsSpentPerLiquidity);
/**
* @dev This function is called when anyone farms their liquidity. The position in a virtual pool
* should be changed accordingly
* @param currentTimestamp The timestamp of current block
* @param bottomTick The bottom tick of a position
* @param topTick The top tick of a position
* @param liquidityDelta The amount of liquidity in a position
* @param currentTick The current tick in the main pool
*/
function applyLiquidityDeltaToPosition(
uint32 currentTimestamp,
int24 bottomTick,
int24 topTick,
int128 liquidityDelta,
int24 currentTick
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
import '../libraries/AdaptiveFee.sol';
interface IDataStorageOperator {
event FeeConfiguration(AdaptiveFee.Configuration feeConfig);
/**
* @notice Returns data belonging to a certain timepoint
* @param index The index of timepoint in the array
* @dev There is more convenient function to fetch a timepoint: getTimepoints(). Which requires not an index but seconds
* @return initialized Whether the timepoint has been initialized and the values are safe to use,
* blockTimestamp The timestamp of the observation,
* tickCumulative The tick multiplied by seconds elapsed for the life of the pool as of the timepoint timestamp,
* secondsPerLiquidityCumulative The seconds per in range liquidity for the life of the pool as of the timepoint timestamp,
* volatilityCumulative Cumulative standard deviation for the life of the pool as of the timepoint timestamp,
* averageTick Time-weighted average tick,
* volumePerLiquidityCumulative Cumulative swap volume per liquidity for the life of the pool as of the timepoint timestamp
*/
function timepoints(uint256 index)
external
view
returns (
bool initialized,
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulative,
uint88 volatilityCumulative,
int24 averageTick,
uint144 volumePerLiquidityCumulative
);
/// @notice Initialize the dataStorage array by writing the first slot. Called once for the lifecycle of the timepoints array
/// @param time The time of the dataStorage initialization, via block.timestamp truncated to uint32
/// @param tick Initial tick
function initialize(uint32 time, int24 tick) external;
/// @dev Reverts if an timepoint at or before the desired timepoint timestamp does not exist.
/// 0 may be passed as `secondsAgo' to return the current cumulative values.
/// If called with a timestamp falling between two timepoints, returns the counterfactual accumulator values
/// at exactly the timestamp between the two timepoints.
/// @param time The current block timestamp
/// @param secondsAgo The amount of time to look back, in seconds, at which point to return an timepoint
/// @param tick The current tick
/// @param index The index of the timepoint that was most recently written to the timepoints array
/// @param liquidity The current in-range pool liquidity
/// @return tickCumulative The cumulative tick since the pool was first initialized, as of `secondsAgo`
/// @return secondsPerLiquidityCumulative The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of `secondsAgo`
/// @return volatilityCumulative The cumulative volatility value since the pool was first initialized, as of `secondsAgo`
/// @return volumePerAvgLiquidity The cumulative volume per liquidity value since the pool was first initialized, as of `secondsAgo`
function getSingleTimepoint(
uint32 time,
uint32 secondsAgo,
int24 tick,
uint16 index,
uint128 liquidity
)
external
view
returns (
int56 tickCumulative,
uint160 secondsPerLiquidityCumulative,
uint112 volatilityCumulative,
uint256 volumePerAvgLiquidity
);
/// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
/// @dev Reverts if `secondsAgos` > oldest timepoint
/// @param time The current block.timestamp
/// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an timepoint
/// @param tick The current tick
/// @param index The index of the timepoint that was most recently written to the timepoints array
/// @param liquidity The current in-range pool liquidity
/// @return tickCumulatives The cumulative tick since the pool was first initialized, as of each `secondsAgo`
/// @return secondsPerLiquidityCumulatives The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`
/// @return volatilityCumulatives The cumulative volatility values since the pool was first initialized, as of each `secondsAgo`
/// @return volumePerAvgLiquiditys The cumulative volume per liquidity values since the pool was first initialized, as of each `secondsAgo`
function getTimepoints(
uint32 time,
uint32[] memory secondsAgos,
int24 tick,
uint16 index,
uint128 liquidity
)
external
view
returns (
int56[] memory tickCumulatives,
uint160[] memory secondsPerLiquidityCumulatives,
uint112[] memory volatilityCumulatives,
uint256[] memory volumePerAvgLiquiditys
);
/// @notice Returns average volatility in the range from time-WINDOW to time
/// @param time The current block.timestamp
/// @param tick The current tick
/// @param index The index of the timepoint that was most recently written to the timepoints array
/// @param liquidity The current in-range pool liquidity
/// @return TWVolatilityAverage The average volatility in the recent range
/// @return TWVolumePerLiqAverage The average volume per liquidity in the recent range
function getAverages(
uint32 time,
int24 tick,
uint16 index,
uint128 liquidity
) external view returns (uint112 TWVolatilityAverage, uint256 TWVolumePerLiqAverage);
/// @notice Writes an dataStorage timepoint to the array
/// @dev Writable at most once per block. Index represents the most recently written element. index must be tracked externally.
/// @param index The index of the timepoint that was most recently written to the timepoints array
/// @param blockTimestamp The timestamp of the new timepoint
/// @param tick The active tick at the time of the new timepoint
/// @param liquidity The total in-range liquidity at the time of the new timepoint
/// @param volumePerLiquidity The gmean(volumes)/liquidity at the time of the new timepoint
/// @return indexUpdated The new index of the most recently written element in the dataStorage array
function write(
uint16 index,
uint32 blockTimestamp,
int24 tick,
uint128 liquidity,
uint128 volumePerLiquidity
) external returns (uint16 indexUpdated);
/// @notice Changes fee configuration for the pool
function changeFeeConfiguration(AdaptiveFee.Configuration calldata feeConfig) external;
/// @notice Calculates gmean(volume/liquidity) for block
/// @param liquidity The current in-range pool liquidity
/// @param amount0 Total amount of swapped token0
/// @param amount1 Total amount of swapped token1
/// @return volumePerLiquidity gmean(volume/liquidity) capped by 100000 << 64
function calculateVolumePerLiquidity(
uint128 liquidity,
int256 amount0,
int256 amount1
) external pure returns (uint128 volumePerLiquidity);
/// @return windowLength Length of window used to calculate averages
function window() external view returns (uint32 windowLength);
/// @notice Calculates fee based on combination of sigmoids
/// @param time The current block.timestamp
/// @param tick The current tick
/// @param index The index of the timepoint that was most recently written to the timepoints array
/// @param liquidity The current in-range pool liquidity
/// @return fee The fee in hundredths of a bip, i.e. 1e-6
function getFee(
uint32 time,
int24 tick,
uint16 index,
uint128 liquidity
) external view returns (uint16 fee);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, 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 `sender` to `recipient` 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 sender, address recipient, uint256 amount) external returns (bool);
/**
* @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);
}
// 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../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`, 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 be 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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* 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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 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);
/**
* @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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 tokenId);
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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);
}
// 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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraPool.sol';
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraVirtualPool.sol';
import '@cryptoalgebra/core/contracts/interfaces/IERC20Minimal.sol';
import '@cryptoalgebra/periphery/contracts/interfaces/IMulticall.sol';
import '@cryptoalgebra/periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '@cryptoalgebra/periphery/contracts/interfaces/IPeripheryPayments.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '../farmings/limitFarming/interfaces/IAlgebraLimitFarming.sol';
import '../farmings/eternalFarming/interfaces/IAlgebraEternalFarming.sol';
import './IFarmingCenterVault.sol';
import './IIncentiveKey.sol';
interface IFarmingCenter is
IAlgebraVirtualPool,
IERC721Receiver,
IIncentiveKey,
IMulticall,
IERC721Permit,
IPeripheryPayments
{
struct VirtualPoolAddresses {
address eternalVirtualPool;
address limitVirtualPool;
}
function virtualPoolAddresses(address) external view returns (address, address);
/// @notice The nonfungible position manager with which this farming contract is compatible
function nonfungiblePositionManager() external view returns (INonfungiblePositionManager);
function limitFarming() external view returns (IAlgebraLimitFarming);
function eternalFarming() external view returns (IAlgebraEternalFarming);
function farmingCenterVault() external view returns (IFarmingCenterVault);
function l2Nfts(uint256)
external
view
returns (
uint96 nonce,
address operator,
uint256 tokenId
);
/// @notice Returns information about a deposited NFT
/// @param tokenId The ID of the deposit (and token) that is being transferred
/// @return L2TokenId The nft layer2 id,
/// numberOfFarms The number of farms,
/// inLimitFarming The parameter showing if the token is in the limit farm,
/// owner The owner of deposit
function deposits(uint256 tokenId)
external
view
returns (
uint256 L2TokenId,
uint32 numberOfFarms,
bool inLimitFarming,
address owner
);
/// @notice Updates activeIncentive in AlgebraPool
/// @dev only farming can do it
/// @param pool The AlgebraPool for which farming was created
/// @param virtualPool The virtual pool to be connected
function connectVirtualPool(IAlgebraPool pool, address virtualPool) external;
/// @notice Enters in incentive (time-limited or eternal farming) with NFT-position token
/// @dev token must be deposited in FarmingCenter
/// @param key The incentive event key
/// @param tokenId The id of position NFT
/// @param tokensLocked Amount of tokens to lock for liquidity multiplier (if tiers are used)
/// @param isLimit Is incentive time-limited or eternal
function enterFarming(
IncentiveKey memory key,
uint256 tokenId,
uint256 tokensLocked,
bool isLimit
) external;
/// @notice Exits from incentive (time-limited or eternal farming) with NFT-position token
/// @param key The incentive event key
/// @param tokenId The id of position NFT
/// @param isLimit Is incentive time-limited or eternal
function exitFarming(
IncentiveKey memory key,
uint256 tokenId,
bool isLimit
) external;
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @dev "proxies" to NonfungiblePositionManager
/// @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(INonfungiblePositionManager.CollectParams calldata params)
external
returns (uint256 amount0, uint256 amount1);
/// @notice Used to collect reward from eternal farming. Then reward can be claimed.
/// @param key The incentive event 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 amountRequestedIncentive Amount to claim in incentive (limit) farming
/// @param amountRequestedEternal Amount to claim in eternal farming
/// @return reward The summary amount of claimed rewards
function claimReward(
IERC20Minimal rewardToken,
address to,
uint256 amountRequestedIncentive,
uint256 amountRequestedEternal
) external returns (uint256 reward);
/// @notice Withdraw Algebra NFT-position token
/// @dev can be used via static call to get current rewards for user
/// @param tokenId The id of position NFT
/// @param to New owner of position NFT
/// @param data The additional data for NonfungiblePositionManager
function withdrawToken(
uint256 tokenId,
address to,
bytes memory data
) external;
/// @notice Emitted when ownership of a deposit changes
/// @param tokenId The ID of the deposit (and token) that is being transferred
/// @param oldOwner The owner before the deposit was transferred
/// @param newOwner The owner after the deposit was transferred
event DepositTransferred(uint256 indexed tokenId, address indexed oldOwner, address indexed newOwner);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.7.6;
interface IFarmingCenterVault {
function claimTokens(
address token,
address to,
uint256 tokenId,
bytes32 incentiveId
) external;
function setFarmingCenter(address farming) external;
function lockTokens(
uint256 tokenId,
bytes32 incentiveId,
uint256 tokenAmount
) external;
function balances(uint256 tokenId, bytes32 incentiveId) external view returns (uint256 balance);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import '@cryptoalgebra/core/contracts/interfaces/IERC20Minimal.sol';
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraPool.sol';
interface IIncentiveKey {
/// @param rewardToken The token being distributed as a reward
/// @param bonusRewardToken The bonus token being distributed as a reward
/// @param pool The Algebra pool
/// @param startTime The time when the incentive program begins
/// @param endTime The time when rewards stop accruing
struct IncentiveKey {
IERC20Minimal rewardToken;
IERC20Minimal bonusRewardToken;
IAlgebraPool pool;
uint256 startTime;
uint256 endTime;
}
}
// 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);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.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 liquidity 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 liquidity,
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 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 tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to 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;
}
// 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);
}
// 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;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 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
/// @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,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '../interfaces/IIncentiveKey.sol';
library IncentiveId {
/// @notice Calculate the key for a staking incentive
/// @param key The components used to compute the incentive identifier
/// @return incentiveId The identifier for the incentive
function compute(IIncentiveKey.IncentiveKey memory key) internal pure returns (bytes32 incentiveId) {
return keccak256(abi.encode(key));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for liquidity
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
if (y < 0) {
require((z = x - uint128(-y)) < x, 'LS');
} else {
require((z = x + uint128(y)) >= x, 'LA');
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import '../interfaces/IAlgebraFarming.sol';
/// @title Functions for liquidity attraction programs with liquidity multipliers
/// @notice Allows computing liquidity multiplier based on locked tokens amount
library LiquidityTier {
uint32 constant DENOMINATOR = 10000;
uint32 constant MAX_MULTIPLIER = 50000;
/// @notice Get the multiplier by tokens locked amount
/// @param tokenAmount The amount of locked tokens
/// @param tiers The structure showing the dependence of the multiplier on the amount of locked tokens
/// @return multiplier The value represent percent of liquidity in ten thousands(1 = 0.01%)
function getLiquidityMultiplier(uint256 tokenAmount, IAlgebraFarming.Tiers memory tiers)
internal
pure
returns (uint32 multiplier)
{
if (tokenAmount >= tiers.tokenAmountForTier3) {
return tiers.tier3Multiplier;
} else if (tokenAmount >= tiers.tokenAmountForTier2) {
return tiers.tier2Multiplier;
} else if (tokenAmount >= tiers.tokenAmountForTier1) {
return tiers.tier1Multiplier;
} else {
return DENOMINATOR;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add128(uint128 x, uint128 y) internal pure returns (uint128 z) {
require((z = x + y) >= x);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import '@cryptoalgebra/periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraFactory.sol';
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraPool.sol';
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraPoolDeployer.sol';
import '@cryptoalgebra/periphery/contracts/libraries/PoolAddress.sol';
/// @notice Encapsulates the logic for getting info about a NFT token ID
library NFTPositionInfo {
/// @param deployer The address of the Algebra Deployer used in computing the pool address
/// @param nonfungiblePositionManager The address of the nonfungible position manager to query
/// @param tokenId The unique identifier of an Algebra LP token
/// @return pool The address of the Algebra pool
/// @return tickLower The lower tick of the Algebra position
/// @return tickUpper The upper tick of the Algebra position
/// @return liquidity The amount of liquidity farmd
function getPositionInfo(
IAlgebraPoolDeployer deployer,
INonfungiblePositionManager nonfungiblePositionManager,
uint256 tokenId
)
internal
view
returns (
IAlgebraPool pool,
int24 tickLower,
int24 tickUpper,
uint128 liquidity
)
{
address token0;
address token1;
(, , token0, token1, tickLower, tickUpper, liquidity, , , , ) = nonfungiblePositionManager.positions(tokenId);
pool = IAlgebraPool(
PoolAddress.computeAddress(address(deployer), PoolAddress.PoolKey({token0: token0, token1: token1}))
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0x6ec6c9c8091d160c0aa74b2b14ba9c1717e95093bd3ac085cee99a49aab294a4;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(address tokenA, address tokenB) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Algebra factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
import './LowGasSafeMath.sol';
import './SafeCast.sol';
import './LiquidityMath.sol';
import './Constants.sol';
/// @title TickManager
/// @notice Contains functions for managing tick processes and relevant calculations
library TickManager {
using LowGasSafeMath for int256;
using SafeCast for int256;
// info stored for each initialized individual tick
struct Tick {
uint128 liquidityTotal; // the total position liquidity that references this tick
int128 liquidityDelta; // amount of net liquidity added (subtracted) when tick is crossed left-right (right-left),
// fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
// only has relative meaning, not absolute — the value depends on when the tick is initialized
uint256 outerFeeGrowth0Token;
uint256 outerFeeGrowth1Token;
int56 outerTickCumulative; // the cumulative tick value on the other side of the tick
uint160 outerSecondsPerLiquidity; // the seconds per unit of liquidity on the _other_ side of current tick, (relative meaning)
uint32 outerSecondsSpent; // the seconds spent on the other side of the current tick, only has relative meaning
bool initialized; // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks
}
/// @notice Retrieves fee growth data
/// @param self The mapping containing all tick information for initialized ticks
/// @param bottomTick The lower tick boundary of the position
/// @param topTick The upper tick boundary of the position
/// @param currentTick The current tick
/// @param totalFeeGrowth0Token The all-time global fee growth, per unit of liquidity, in token0
/// @param totalFeeGrowth1Token The all-time global fee growth, per unit of liquidity, in token1
/// @return innerFeeGrowth0Token The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
/// @return innerFeeGrowth1Token The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
function getInnerFeeGrowth(
mapping(int24 => Tick) storage self,
int24 bottomTick,
int24 topTick,
int24 currentTick,
uint256 totalFeeGrowth0Token,
uint256 totalFeeGrowth1Token
) internal view returns (uint256 innerFeeGrowth0Token, uint256 innerFeeGrowth1Token) {
Tick storage lower = self[bottomTick];
Tick storage upper = self[topTick];
if (currentTick < topTick) {
if (currentTick >= bottomTick) {
innerFeeGrowth0Token = totalFeeGrowth0Token - lower.outerFeeGrowth0Token;
innerFeeGrowth1Token = totalFeeGrowth1Token - lower.outerFeeGrowth1Token;
} else {
innerFeeGrowth0Token = lower.outerFeeGrowth0Token;
innerFeeGrowth1Token = lower.outerFeeGrowth1Token;
}
innerFeeGrowth0Token -= upper.outerFeeGrowth0Token;
innerFeeGrowth1Token -= upper.outerFeeGrowth1Token;
} else {
innerFeeGrowth0Token = upper.outerFeeGrowth0Token - lower.outerFeeGrowth0Token;
innerFeeGrowth1Token = upper.outerFeeGrowth1Token - lower.outerFeeGrowth1Token;
}
}
/// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa
/// @param self The mapping containing all tick information for initialized ticks
/// @param tick The tick that will be updated
/// @param currentTick The current tick
/// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)
/// @param totalFeeGrowth0Token The all-time global fee growth, per unit of liquidity, in token0
/// @param totalFeeGrowth1Token The all-time global fee growth, per unit of liquidity, in token1
/// @param secondsPerLiquidityCumulative The all-time seconds per max(1, liquidity) of the pool
/// @param tickCumulative The all-time global cumulative tick
/// @param time The current block timestamp cast to a uint32
/// @param upper true for updating a position's upper tick, or false for updating a position's lower tick
/// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa
function update(
mapping(int24 => Tick) storage self,
int24 tick,
int24 currentTick,
int128 liquidityDelta,
uint256 totalFeeGrowth0Token,
uint256 totalFeeGrowth1Token,
uint160 secondsPerLiquidityCumulative,
int56 tickCumulative,
uint32 time,
bool upper
) internal returns (bool flipped) {
Tick storage data = self[tick];
int128 liquidityDeltaBefore = data.liquidityDelta;
uint128 liquidityTotalBefore = data.liquidityTotal;
uint128 liquidityTotalAfter = LiquidityMath.addDelta(liquidityTotalBefore, liquidityDelta);
require(liquidityTotalAfter < Constants.MAX_LIQUIDITY_PER_TICK + 1, 'LO');
// when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)
data.liquidityDelta = upper
? int256(liquidityDeltaBefore).sub(liquidityDelta).toInt128()
: int256(liquidityDeltaBefore).add(liquidityDelta).toInt128();
data.liquidityTotal = liquidityTotalAfter;
flipped = (liquidityTotalAfter == 0);
if (liquidityTotalBefore == 0) {
flipped = !flipped;
// by convention, we assume that all growth before a tick was initialized happened _below_ the tick
if (tick <= currentTick) {
data.outerFeeGrowth0Token = totalFeeGrowth0Token;
data.outerFeeGrowth1Token = totalFeeGrowth1Token;
data.outerSecondsPerLiquidity = secondsPerLiquidityCumulative;
data.outerTickCumulative = tickCumulative;
data.outerSecondsSpent = time;
}
data.initialized = true;
}
}
/// @notice Transitions to next tick as needed by price movement
/// @param self The mapping containing all tick information for initialized ticks
/// @param tick The destination tick of the transition
/// @param totalFeeGrowth0Token The all-time global fee growth, per unit of liquidity, in token0
/// @param totalFeeGrowth1Token The all-time global fee growth, per unit of liquidity, in token1
/// @param secondsPerLiquidityCumulative The current seconds per liquidity
/// @param tickCumulative The all-time global cumulative tick
/// @param time The current block.timestamp
/// @return liquidityDelta The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)
function cross(
mapping(int24 => Tick) storage self,
int24 tick,
uint256 totalFeeGrowth0Token,
uint256 totalFeeGrowth1Token,
uint160 secondsPerLiquidityCumulative,
int56 tickCumulative,
uint32 time
) internal returns (int128 liquidityDelta) {
Tick storage data = self[tick];
data.outerSecondsSpent = time - data.outerSecondsSpent;
data.outerSecondsPerLiquidity = secondsPerLiquidityCumulative - data.outerSecondsPerLiquidity;
data.outerTickCumulative = tickCumulative - data.outerTickCumulative;
data.outerFeeGrowth1Token = totalFeeGrowth1Token - data.outerFeeGrowth1Token;
data.outerFeeGrowth0Token = totalFeeGrowth0Token - data.outerFeeGrowth0Token;
return data.liquidityDelta;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return price A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 price) {
// get abs value
int24 mask = tick >> (24 - 1);
uint256 absTick = uint256((tick ^ mask) - mask);
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
price = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case price < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param price The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 price) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(price >= MIN_SQRT_RATIO && price < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(price) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= price ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
import './Constants.sol';
import './TickMath.sol';
/// @title Packed tick initialized state library
/// @notice Stores a packed mapping of tick index to its initialized state
/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
library TickTable {
/// @notice Toggles the initialized state for a given tick from false to true, or vice versa
/// @param self The mapping in which to toggle the tick
/// @param tick The tick to toggle
function toggleTick(mapping(int16 => uint256) storage self, int24 tick) internal {
require(tick % Constants.TICK_SPACING == 0, 'tick is not spaced'); // ensure that the tick is spaced
tick /= Constants.TICK_SPACING; // compress tick
int16 rowNumber;
uint8 bitNumber;
assembly {
bitNumber := and(tick, 0xFF)
rowNumber := shr(8, tick)
}
self[rowNumber] ^= 1 << bitNumber;
}
/// @notice get position of single 1-bit
/// @dev it is assumed that word contains exactly one 1-bit, otherwise the result will be incorrect
/// @param word The word containing only one 1-bit
function getSingleSignificantBit(uint256 word) internal pure returns (uint8 singleBitPos) {
assembly {
singleBitPos := iszero(and(word, 0x5555555555555555555555555555555555555555555555555555555555555555))
singleBitPos := or(singleBitPos, shl(7, iszero(and(word, 0x00000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))))
singleBitPos := or(singleBitPos, shl(6, iszero(and(word, 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF))))
singleBitPos := or(singleBitPos, shl(5, iszero(and(word, 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF))))
singleBitPos := or(singleBitPos, shl(4, iszero(and(word, 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF))))
singleBitPos := or(singleBitPos, shl(3, iszero(and(word, 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF))))
singleBitPos := or(singleBitPos, shl(2, iszero(and(word, 0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F))))
singleBitPos := or(singleBitPos, shl(1, iszero(and(word, 0x3333333333333333333333333333333333333333333333333333333333333333))))
}
}
/// @notice get position of most significant 1-bit (leftmost)
/// @dev it is assumed that before the call, a check will be made that the argument (word) is not equal to zero
/// @param word The word containing at least one 1-bit
function getMostSignificantBit(uint256 word) internal pure returns (uint8 mostBitPos) {
assembly {
word := or(word, shr(1, word))
word := or(word, shr(2, word))
word := or(word, shr(4, word))
word := or(word, shr(8, word))
word := or(word, shr(16, word))
word := or(word, shr(32, word))
word := or(word, shr(64, word))
word := or(word, shr(128, word))
word := sub(word, shr(1, word))
}
return (getSingleSignificantBit(word));
}
/// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
/// to the left (less than or equal to) or right (greater than) of the given tick
/// @param self The mapping in which to compute the next initialized tick
/// @param tick The starting tick
/// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
/// @return nextTick The next initialized or uninitialized tick up to 256 ticks away from the current tick
/// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
function nextTickInTheSameRow(
mapping(int16 => uint256) storage self,
int24 tick,
bool lte
) internal view returns (int24 nextTick, bool initialized) {
{
int24 tickSpacing = Constants.TICK_SPACING;
// compress and round towards negative infinity if negative
assembly {
tick := sub(sdiv(tick, tickSpacing), and(slt(tick, 0), not(iszero(smod(tick, tickSpacing)))))
}
}
if (lte) {
// unpacking not made into a separate function for gas and contract size savings
int16 rowNumber;
uint8 bitNumber;
assembly {
bitNumber := and(tick, 0xFF)
rowNumber := shr(8, tick)
}
uint256 _row = self[rowNumber] << (255 - bitNumber); // all the 1s at or to the right of the current bitNumber
if (_row != 0) {
tick -= int24(255 - getMostSignificantBit(_row));
return (uncompressAndBoundTick(tick), true);
} else {
tick -= int24(bitNumber);
return (uncompressAndBoundTick(tick), false);
}
} else {
// start from the word of the next tick, since the current tick state doesn't matter
tick += 1;
int16 rowNumber;
uint8 bitNumber;
assembly {
bitNumber := and(tick, 0xFF)
rowNumber := shr(8, tick)
}
// all the 1s at or to the left of the bitNumber
uint256 _row = self[rowNumber] >> (bitNumber);
if (_row != 0) {
tick += int24(getSingleSignificantBit(-_row & _row)); // least significant bit
return (uncompressAndBoundTick(tick), true);
} else {
tick += int24(255 - bitNumber);
return (uncompressAndBoundTick(tick), false);
}
}
}
function uncompressAndBoundTick(int24 tick) private pure returns (int24 boundedTick) {
boundedTick = tick * Constants.TICK_SPACING;
if (boundedTick < TickMath.MIN_TICK) {
boundedTick = TickMath.MIN_TICK;
} else if (boundedTick > TickMath.MAX_TICK) {
boundedTick = TickMath.MAX_TICK;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev Errors with 'SA' if transfer fails
/// @param token The contract address of the token to be approved
/// @param to The target of the approval
/// @param value The amount of the given token the target will be allowed to spend
function safeApprove(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
}
/// @notice Transfers NativeToken to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferNative(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
{
"compilationTarget": {
"contracts/farmings/eternalFarming/AlgebraEternalFarming.sol": "AlgebraEternalFarming"
},
"evmVersion": "istanbul",
"libraries": {},
"metadata": {
"bytecodeHash": "none"
},
"optimizer": {
"enabled": true,
"runs": 99999999
},
"remappings": []
}
[{"inputs":[{"internalType":"contract IAlgebraPoolDeployer","name":"_deployer","type":"address"},{"internalType":"contract INonfungiblePositionManager","name":"_nonfungiblePositionManager","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"indexed":true,"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"indexed":true,"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"indexed":false,"internalType":"address","name":"virtualPool","type":"address"},{"indexed":false,"internalType":"uint256","name":"startTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"endTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusReward","type":"uint256"},{"components":[{"internalType":"uint256","name":"tokenAmountForTier1","type":"uint256"},{"internalType":"uint256","name":"tokenAmountForTier2","type":"uint256"},{"internalType":"uint256","name":"tokenAmountForTier3","type":"uint256"},{"internalType":"uint32","name":"tier1Multiplier","type":"uint32"},{"internalType":"uint32","name":"tier2Multiplier","type":"uint32"},{"internalType":"uint32","name":"tier3Multiplier","type":"uint32"}],"indexed":false,"internalType":"struct IAlgebraFarming.Tiers","name":"tiers","type":"tuple"},{"indexed":false,"internalType":"address","name":"multiplierToken","type":"address"},{"indexed":false,"internalType":"uint24","name":"minimalAllowedPositionWidth","type":"uint24"}],"name":"EternalFarmingCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"rewardAddress","type":"address"},{"indexed":false,"internalType":"address","name":"bonusRewardToken","type":"address"},{"indexed":false,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusReward","type":"uint256"}],"name":"FarmEnded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"tokensLocked","type":"uint256"}],"name":"FarmEntered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"farmingCenter","type":"address"}],"name":"FarmingCenter","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"indexed":true,"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"indexed":true,"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"indexed":false,"internalType":"address","name":"virtualPool","type":"address"},{"indexed":false,"internalType":"uint256","name":"startTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"endTime","type":"uint256"}],"name":"IncentiveAttached","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"indexed":true,"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"indexed":true,"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"indexed":false,"internalType":"address","name":"virtualPool","type":"address"},{"indexed":false,"internalType":"uint256","name":"startTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"endTime","type":"uint256"}],"name":"IncentiveDetached","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"incentiveMaker","type":"address"}],"name":"IncentiveMaker","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"}],"name":"Owner","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"},{"indexed":true,"internalType":"address","name":"rewardAddress","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"}],"name":"RewardClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"rewardAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusRewardAmount","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"incentiveId","type":"bytes32"}],"name":"RewardsAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"incentiveId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"rewardAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusRewardAmount","type":"uint256"}],"name":"RewardsCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint128","name":"rewardRate","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"bonusRewardRate","type":"uint128"},{"indexed":false,"internalType":"bytes32","name":"incentiveId","type":"bytes32"}],"name":"RewardsRatesChanged","type":"event"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"}],"internalType":"struct IIncentiveKey.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"rewardAmount","type":"uint256"},{"internalType":"uint256","name":"bonusRewardAmount","type":"uint256"}],"name":"addRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"}],"internalType":"struct IIncentiveKey.IncentiveKey","name":"key","type":"tuple"}],"name":"attachIncentive","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amountRequested","type":"uint256"}],"name":"claimReward","outputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amountRequested","type":"uint256"}],"name":"claimRewardFrom","outputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"}],"internalType":"struct IIncentiveKey.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"_owner","type":"address"}],"name":"collectRewards","outputs":[{"internalType":"uint256","name":"reward","type":"uint256"},{"internalType":"uint256","name":"bonusReward","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"}],"internalType":"struct IIncentiveKey.IncentiveKey","name":"key","type":"tuple"},{"components":[{"internalType":"uint256","name":"reward","type":"uint256"},{"internalType":"uint256","name":"bonusReward","type":"uint256"},{"internalType":"uint128","name":"rewardRate","type":"uint128"},{"internalType":"uint128","name":"bonusRewardRate","type":"uint128"},{"internalType":"uint24","name":"minimalPositionWidth","type":"uint24"},{"internalType":"address","name":"multiplierToken","type":"address"}],"internalType":"struct IAlgebraEternalFarming.IncentiveParams","name":"params","type":"tuple"},{"components":[{"internalType":"uint256","name":"tokenAmountForTier1","type":"uint256"},{"internalType":"uint256","name":"tokenAmountForTier2","type":"uint256"},{"internalType":"uint256","name":"tokenAmountForTier3","type":"uint256"},{"internalType":"uint32","name":"tier1Multiplier","type":"uint32"},{"internalType":"uint32","name":"tier2Multiplier","type":"uint32"},{"internalType":"uint32","name":"tier3Multiplier","type":"uint32"}],"internalType":"struct IAlgebraFarming.Tiers","name":"tiers","type":"tuple"}],"name":"createEternalFarming","outputs":[{"internalType":"address","name":"virtualPool","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"deployer","outputs":[{"internalType":"contract IAlgebraPoolDeployer","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"}],"internalType":"struct IIncentiveKey.IncentiveKey","name":"key","type":"tuple"}],"name":"detachIncentive","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"}],"internalType":"struct IIncentiveKey.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"tokensLocked","type":"uint256"}],"name":"enterFarming","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"}],"internalType":"struct IIncentiveKey.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"_owner","type":"address"}],"name":"exitFarming","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"farmingCenter","outputs":[{"internalType":"contract IFarmingCenter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"farms","outputs":[{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint256","name":"innerRewardGrowth0","type":"uint256"},{"internalType":"uint256","name":"innerRewardGrowth1","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"}],"internalType":"struct IIncentiveKey.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getRewardInfo","outputs":[{"internalType":"uint256","name":"reward","type":"uint256"},{"internalType":"uint256","name":"bonusReward","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"incentives","outputs":[{"internalType":"uint256","name":"totalReward","type":"uint256"},{"internalType":"uint256","name":"bonusReward","type":"uint256"},{"internalType":"address","name":"virtualPoolAddress","type":"address"},{"internalType":"uint24","name":"minimalPositionWidth","type":"uint24"},{"internalType":"uint224","name":"totalLiquidity","type":"uint224"},{"internalType":"address","name":"multiplierToken","type":"address"},{"components":[{"internalType":"uint256","name":"tokenAmountForTier1","type":"uint256"},{"internalType":"uint256","name":"tokenAmountForTier2","type":"uint256"},{"internalType":"uint256","name":"tokenAmountForTier3","type":"uint256"},{"internalType":"uint32","name":"tier1Multiplier","type":"uint32"},{"internalType":"uint32","name":"tier2Multiplier","type":"uint32"},{"internalType":"uint32","name":"tier3Multiplier","type":"uint32"}],"internalType":"struct IAlgebraFarming.Tiers","name":"tiers","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nonfungiblePositionManager","outputs":[{"internalType":"contract INonfungiblePositionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"contract IERC20Minimal","name":"","type":"address"}],"name":"rewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_farmingCenter","type":"address"}],"name":"setFarmingCenterAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_incentiveMaker","type":"address"}],"name":"setIncentiveMaker","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"setOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Minimal","name":"rewardToken","type":"address"},{"internalType":"contract IERC20Minimal","name":"bonusRewardToken","type":"address"},{"internalType":"contract IAlgebraPool","name":"pool","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"}],"internalType":"struct IIncentiveKey.IncentiveKey","name":"key","type":"tuple"},{"internalType":"uint128","name":"rewardRate","type":"uint128"},{"internalType":"uint128","name":"bonusRewardRate","type":"uint128"}],"name":"setRates","outputs":[],"stateMutability":"nonpayable","type":"function"}]