Contract Source Code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IAccessHub} from "./interfaces/IAccessHub.sol";
import {Errors} from "contracts/libraries/Errors.sol";
import {
AccessControlEnumerableUpgradeable,
Initializable
} from "@openzeppelin-contracts-upgradeable/access/extensions/AccessControlEnumerableUpgradeable.sol";
import {ILauncherPlugin} from "./interfaces/ILauncherPlugin.sol";
import {IXShadow} from "./interfaces/IXShadow.sol";
import {IX33} from "./interfaces/IX33.sol";
import {IShadowV3Factory} from "./CL/core/interfaces/IShadowV3Factory.sol";
import {IShadowV3Pool} from "./CL/core/interfaces/IShadowV3Pool.sol";
import {IGaugeV3} from "./CL/gauge/interfaces/IGaugeV3.sol";
import {IFeeCollector} from "./CL/gauge/interfaces/IFeeCollector.sol";
import {INonfungiblePositionManager} from "./CL/periphery/interfaces/INonfungiblePositionManager.sol";
import {IPairFactory} from "./interfaces/IPairFactory.sol";
import {IFeeRecipientFactory} from "./interfaces/IFeeRecipientFactory.sol";
import {IVoter} from "./interfaces/IVoter.sol";
import {IMinter} from "./interfaces/IMinter.sol";
import {IMarbleMinter} from "./interfaces/IMarbleMinter.sol";
import {IVoteModule} from "./interfaces/IVoteModule.sol";
import {IFeeDistributor} from "./interfaces/IFeeDistributor.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
contract AccessHub is IAccessHub, Initializable, AccessControlEnumerableUpgradeable {
/**
* Start of Storage Slots
*/
/// @notice role that can call changing fee splits and swap fees
bytes32 public constant SWAP_FEE_SETTER = keccak256("SWAP_FEE_SETTER");
/// @notice operator role
bytes32 public constant PROTOCOL_OPERATOR = keccak256("PROTOCOL_OPERATOR");
/// @notice central voter contract
IVoter public constant oldVoter = IVoter(0x3aF1dD7A2755201F8e2D6dCDA1a61d9f54838f4f);
/// @notice weekly emissions minter
IMinter public constant oldMinter = IMinter(0xc7022F359cD1bDa8aB8a19d1F19d769cbf7F3765);
/// @inheritdoc IAccessHub
address public timelock;
/// @inheritdoc IAccessHub
address public treasury;
/**
* "nice-to-have" addresses for quickly finding contracts within the system
*/
/// @inheritdoc IAccessHub
address public clGaugeFactory;
/// @inheritdoc IAccessHub
address public gaugeFactory;
/// @inheritdoc IAccessHub
address public feeDistributorFactory;
/**
* core contracts
*/
/// @notice central voter contract
IVoter public voter;
/// @notice weekly emissions minter
IMarbleMinter public minter;
/// @notice launchpad plugin for augmenting feeshare
ILauncherPlugin public launcherPlugin;
/// @notice xShadow contract
IXShadow public xShadow;
/// @notice X33 contract
IX33 public x33;
/// @notice CL V3 factory
IShadowV3Factory public shadowV3PoolFactory;
/// @notice legacy pair factory
IPairFactory public poolFactory;
/// @notice legacy fees holder contract
IFeeRecipientFactory public feeRecipientFactory;
/// @notice fee collector contract
IFeeCollector public feeCollector;
/// @notice voteModule contract
IVoteModule public voteModule;
/// @notice NFPManager contract
INonfungiblePositionManager public nfpManager;
/**
* End of Storage Slots
*/
modifier timelocked() {
require(msg.sender == timelock, Errors.NOT_TIMELOCK(msg.sender));
_;
}
constructor() {
_disableInitializers();
}
/// @inheritdoc IAccessHub
function initialize(InitParams calldata params) external initializer {
/// @dev initialize all external interfaces
timelock = params.timelock;
treasury = params.treasury;
voter = IVoter(params.voter);
minter = IMarbleMinter(params.minter);
launcherPlugin = ILauncherPlugin(params.launcherPlugin);
xShadow = IXShadow(params.xShadow);
x33 = IX33(params.x33);
shadowV3PoolFactory = IShadowV3Factory(params.shadowV3PoolFactory);
poolFactory = IPairFactory(params.poolFactory);
feeRecipientFactory = IFeeRecipientFactory(params.feeRecipientFactory);
feeCollector = IFeeCollector(params.feeCollector);
voteModule = IVoteModule(params.voteModule);
/// @dev reference addresses
clGaugeFactory = params.clGaugeFactory;
gaugeFactory = params.gaugeFactory;
feeDistributorFactory = params.feeDistributorFactory;
/// @dev fee setter role given to treasury
_grantRole(SWAP_FEE_SETTER, params.treasury);
/// @dev operator role given to treasury
_grantRole(PROTOCOL_OPERATOR, params.treasury);
/// @dev initially give admin role to treasury
_grantRole(DEFAULT_ADMIN_ROLE, params.treasury);
/// @dev give timelock the admin role
_grantRole(DEFAULT_ADMIN_ROLE, params.timelock);
}
function reinit(InitParams calldata params) external timelocked {
voter = IVoter(params.voter);
minter = IMarbleMinter(params.minter);
launcherPlugin = ILauncherPlugin(params.launcherPlugin);
xShadow = IXShadow(params.xShadow);
x33 = IX33(params.x33);
shadowV3PoolFactory = IShadowV3Factory(params.shadowV3PoolFactory);
poolFactory = IPairFactory(params.poolFactory);
feeRecipientFactory = IFeeRecipientFactory(params.feeRecipientFactory);
feeCollector = IFeeCollector(params.feeCollector);
voteModule = IVoteModule(params.voteModule);
/// @dev reference addresses
clGaugeFactory = params.clGaugeFactory;
gaugeFactory = params.gaugeFactory;
feeDistributorFactory = params.feeDistributorFactory;
}
/// @inheritdoc IAccessHub
function initializeVoter(IVoter.InitializationParams memory inputs) external timelocked {
voter.initialize(inputs);
}
/**
* Fee Setting Logic
*/
/// @inheritdoc IAccessHub
function setSwapFees(address[] calldata _pools, uint24[] calldata _swapFees, bool[] calldata _concentrated)
external
onlyRole(SWAP_FEE_SETTER)
{
/// @dev ensure continuity of length
require(_pools.length == _swapFees.length && _swapFees.length == _concentrated.length, Errors.LENGTH_MISMATCH());
for (uint256 i; i < _pools.length; ++i) {
/// @dev we check if the pool is v3 or legacy and set their fees accordingly
if (_concentrated[i]) {
shadowV3PoolFactory.setFee(_pools[i], _swapFees[i]);
} else {
poolFactory.setPairFee(_pools[i], _swapFees[i]);
}
}
}
/// @inheritdoc IAccessHub
function setFeeSplitCL(address[] calldata _pools, uint8[] calldata _feeProtocol)
external
onlyRole(SWAP_FEE_SETTER)
{
/// @dev ensure continuity of length
require(_pools.length == _feeProtocol.length, Errors.LENGTH_MISMATCH());
for (uint256 i; i < _pools.length; ++i) {
shadowV3PoolFactory.setPoolFeeProtocol(_pools[i], _feeProtocol[i]);
}
}
/// @inheritdoc IAccessHub
function setFeeSplitLegacy(address[] calldata _pools, uint256[] calldata _feeSplits)
external
onlyRole(SWAP_FEE_SETTER)
{
/// @dev ensure continuity of length
require(_pools.length == _feeSplits.length, Errors.LENGTH_MISMATCH());
for (uint256 i; i < _pools.length; ++i) {
poolFactory.setPairFeeSplit(_pools[i], _feeSplits[i]);
}
}
/**
* Voter governance
*/
/// @inheritdoc IAccessHub
function setNewGovernorInVoter(address _newGovernor) external onlyRole(PROTOCOL_OPERATOR) {
/// @dev no checks are needed as the voter handles this already
voter.setGovernor(_newGovernor);
}
/// @inheritdoc IAccessHub
function governanceWhitelist(address[] calldata _token, bool[] calldata _whitelisted)
external
onlyRole(PROTOCOL_OPERATOR)
{
/// @dev ensure continuity of length
require(_token.length == _whitelisted.length, Errors.LENGTH_MISMATCH());
for (uint256 i; i < _token.length; ++i) {
/// @dev if adding to the whitelist
if (_whitelisted[i]) {
/// @dev call the voter's whitelist function
voter.whitelist(_token[i]);
}
/// @dev remove the token's whitelist
else {
voter.revokeWhitelist(_token[i]);
}
}
}
/// @inheritdoc IAccessHub
function killGauge(address[] calldata _pairs) external onlyRole(PROTOCOL_OPERATOR) {
for (uint256 i; i < _pairs.length; ++i) {
/// @dev store pair
address pair = _pairs[i];
/// @dev collect fees from the pair
feeCollector.collectProtocolFees(pair);
/// @dev kill the gauge
voter.killGauge(voter.gaugeForPool(pair));
/// @dev set the new fees in the pair to 95/5
shadowV3PoolFactory.setPoolFeeProtocol(pair, 5);
}
}
/// @inheritdoc IAccessHub
function reviveGauge(address[] calldata _pairs) external onlyRole(PROTOCOL_OPERATOR) {
for (uint256 i; i < _pairs.length; ++i) {
address pair = _pairs[i];
/// @dev collect fees from the pair
feeCollector.collectProtocolFees(pair);
/// @dev revive the pair
voter.reviveGauge(voter.gaugeForPool(pair));
/// @dev set fee to the factory default
shadowV3PoolFactory.setPoolFeeProtocol(pair, shadowV3PoolFactory.feeProtocol());
}
}
/// @inheritdoc IAccessHub
function setNfpManager(address _nfpManager) external onlyRole(PROTOCOL_OPERATOR) {
voter.setNfpManager(_nfpManager);
}
/// @inheritdoc IAccessHub
function syncNfpManager(address[] calldata gauges) external onlyRole(PROTOCOL_OPERATOR) {
for (uint256 i; i < gauges.length; ++i) {
IGaugeV3(gauges[i]).syncNfpManager();
}
}
/// @inheritdoc IAccessHub
function setEmissionsRatioInVoter(uint256 _pct) external onlyRole(PROTOCOL_OPERATOR) {
voter.setGlobalRatio(_pct);
}
/// @inheritdoc IAccessHub
function retrieveStuckEmissionsToGovernance(address _gauge, uint256 _period) external onlyRole(PROTOCOL_OPERATOR) {
voter.stuckEmissionsRecovery(_gauge, _period);
}
/// @inheritdoc IAccessHub
function setMainGaugeForClPair(address tokenA, address tokenB, address gauge)
external
onlyRole(PROTOCOL_OPERATOR)
{
voter.redirectEmissions(tokenA, tokenB, gauge);
}
function createGaugeForPool(address _pool) external onlyRole(PROTOCOL_OPERATOR) {
bool isCl = shadowV3PoolFactory.isPairV3(_pool);
if (isCl) {
IShadowV3Pool poolv3 = IShadowV3Pool(_pool);
(address token0, address token1, int24 tickSpacing) =
(poolv3.token0(), poolv3.token1(), poolv3.tickSpacing());
voter.createCLGauge(token0, token1, tickSpacing);
} else {
voter.createGauge(_pool);
}
}
/// @inheritdoc IAccessHub
function resetVotesOnBehalfOf(address _user) external timelocked {
voter.reset(_user);
}
/**
* xShadow Functions
*/
/// @inheritdoc IAccessHub
function transferWhitelistInXShadow(address[] calldata _who, bool[] calldata _whitelisted)
external
onlyRole(PROTOCOL_OPERATOR)
{
/// @dev ensure continuity of length
require(_who.length == _whitelisted.length, Errors.LENGTH_MISMATCH());
xShadow.setExemption(_who, _whitelisted);
}
/// @inheritdoc IAccessHub
function transferToWhitelistInXShadow(address[] calldata _who, bool[] calldata _whitelisted)
external
onlyRole(PROTOCOL_OPERATOR)
{
/// @dev ensure continuity of length
require(_who.length == _whitelisted.length, Errors.LENGTH_MISMATCH());
xShadow.setExemptionTo(_who, _whitelisted);
}
/// @inheritdoc IAccessHub
function toggleXShadowGovernance(bool enable) external onlyRole(PROTOCOL_OPERATOR) {
/// @dev if enabled we call unpause otherwise we pause to disable
enable ? xShadow.unpause() : xShadow.pause();
}
/// @inheritdoc IAccessHub
function operatorRedeemXShadow(uint256 _amount) external onlyRole(PROTOCOL_OPERATOR) {
xShadow.operatorRedeem(_amount);
}
/// @inheritdoc IAccessHub
function migrateOperator(address _operator) external onlyRole(PROTOCOL_OPERATOR) {
xShadow.migrateOperator(_operator);
}
/// @inheritdoc IAccessHub
function rescueTrappedTokens(address[] calldata _tokens, uint256[] calldata _amounts)
external
onlyRole(PROTOCOL_OPERATOR)
{
xShadow.rescueTrappedTokens(_tokens, _amounts);
}
/// @inheritdoc IAccessHub
function setRebaseThreshold(uint256 _newThreshold) external onlyRole(PROTOCOL_OPERATOR) {
xShadow.setRebaseThreshold(_newThreshold);
}
/**
* X33 Functions
*/
/// @inheritdoc IAccessHub
function transferOperatorInX33(address _newOperator) external onlyRole(PROTOCOL_OPERATOR) {
x33.transferOperator(_newOperator);
}
/**
* Minter Functions
*/
/// @inheritdoc IAccessHub
function setEmissionsMultiplierInMinter(uint256 _multiplier) external onlyRole(PROTOCOL_OPERATOR) {
minter.updateEmissionsMultiplier(_multiplier);
}
/**
* Reward List Functions
*/
/// @inheritdoc IAccessHub
function removeFeeDistributorRewards(address[] calldata _pools, address[] calldata _rewards)
external
onlyRole(PROTOCOL_OPERATOR)
{
require(_pools.length == _rewards.length, Errors.LENGTH_MISMATCH());
for (uint256 i; i < _pools.length; ++i) {
voter.removeFeeDistributorReward(voter.feeDistributorForGauge(voter.gaugeForPool(_pools[i])), _rewards[i]);
}
}
function clawbackRewards(address feeDistributor, address token, address destination)
external
onlyRole(PROTOCOL_OPERATOR)
{
IFeeDistributor(feeDistributor).clawbackRewards(token, destination);
}
/**
* LauncherPlugin specific functions
*/
/// @inheritdoc IAccessHub
function migratePoolInLauncherPlugin(address _oldPool, address _newPool) external onlyRole(PROTOCOL_OPERATOR) {
launcherPlugin.migratePool(_oldPool, _newPool);
}
/// @inheritdoc IAccessHub
function setConfigsInLauncherPlugin(address _pool, uint256 _take, address _recipient)
external
onlyRole(PROTOCOL_OPERATOR)
{
launcherPlugin.setConfigs(_pool, _take, _recipient);
}
/// @inheritdoc IAccessHub
function enablePoolInLauncherPlugin(address _pool) external onlyRole(PROTOCOL_OPERATOR) {
launcherPlugin.enablePool(_pool);
}
/// @inheritdoc IAccessHub
function disablePoolInLauncherPlugin(address _pool) external onlyRole(PROTOCOL_OPERATOR) {
launcherPlugin.disablePool(_pool);
}
/// @inheritdoc IAccessHub
function setOperatorInLauncherPlugin(address _newOperator) external onlyRole(PROTOCOL_OPERATOR) {
launcherPlugin.setOperator(_newOperator);
}
/// @inheritdoc IAccessHub
function grantAuthorityInLauncherPlugin(address _newAuthority, string calldata _label)
external
onlyRole(PROTOCOL_OPERATOR)
{
launcherPlugin.grantAuthority(_newAuthority, _label);
}
/// @inheritdoc IAccessHub
function labelAuthorityInLauncherPlugin(address _authority, string calldata _label)
external
onlyRole(PROTOCOL_OPERATOR)
{
launcherPlugin.label(_authority, _label);
}
/// @inheritdoc IAccessHub
function revokeAuthorityInLauncherPlugin(address _oldAuthority) external onlyRole(PROTOCOL_OPERATOR) {
launcherPlugin.revokeAuthority(_oldAuthority);
}
/**
* FeeCollector functions
*/
/// @inheritdoc IAccessHub
function setTreasuryInFeeCollector(address newTreasury) external onlyRole(PROTOCOL_OPERATOR) {
feeCollector.setTreasury(newTreasury);
}
/// @inheritdoc IAccessHub
function setTreasuryFeesInFeeCollector(uint256 _treasuryFees) external onlyRole(PROTOCOL_OPERATOR) {
feeCollector.setTreasuryFees(_treasuryFees);
}
/**
* FeeRecipientFactory functions
*/
/// @inheritdoc IAccessHub
function setFeeToTreasuryInFeeRecipientFactory(uint256 _feeToTreasury) external onlyRole(PROTOCOL_OPERATOR) {
feeRecipientFactory.setFeeToTreasury(_feeToTreasury);
}
/// @inheritdoc IAccessHub
function setTreasuryInFeeRecipientFactory(address _treasury) external onlyRole(PROTOCOL_OPERATOR) {
feeRecipientFactory.setTreasury(_treasury);
}
/**
* CL Pool Factory functions
*/
/// @inheritdoc IAccessHub
function enableTickSpacing(int24 tickSpacing, uint24 initialFee) external onlyRole(PROTOCOL_OPERATOR) {
shadowV3PoolFactory.enableTickSpacing(tickSpacing, initialFee);
}
/// @inheritdoc IAccessHub
function setGlobalClFeeProtocol(uint8 _feeProtocolGlobal) external onlyRole(PROTOCOL_OPERATOR) {
shadowV3PoolFactory.setFeeProtocol(_feeProtocolGlobal);
}
/// @inheritdoc IAccessHub
/// @notice sets the address of the voter in the v3 factory for gauge fee setting
function setVoterAddressInFactoryV3(address _voter) external timelocked {
shadowV3PoolFactory.setVoter(_voter);
}
/// @inheritdoc IAccessHub
function setFeeCollectorInFactoryV3(address _newFeeCollector) external timelocked {
shadowV3PoolFactory.setFeeCollector(_newFeeCollector);
}
/**
* Legacy Pool Factory functions
*/
/// @inheritdoc IAccessHub
function setTreasuryInLegacyFactory(address _treasury) external onlyRole(PROTOCOL_OPERATOR) {
poolFactory.setTreasury(_treasury);
}
/// @inheritdoc IAccessHub
function setFeeSplitWhenNoGauge(bool status) external onlyRole(PROTOCOL_OPERATOR) {
poolFactory.setFeeSplitWhenNoGauge(status);
}
/// @inheritdoc IAccessHub
function setLegacyFeeSplitGlobal(uint256 _feeSplit) external onlyRole(PROTOCOL_OPERATOR) {
poolFactory.setFeeSplit(_feeSplit);
}
/// @inheritdoc IAccessHub
function setLegacyFeeRecipient(address _pair, address _feeRecipient) external onlyRole(PROTOCOL_OPERATOR) {
poolFactory.setFeeRecipient(_pair, _feeRecipient);
}
/// @inheritdoc IAccessHub
function setLegacyFeeGlobal(uint256 _fee) external onlyRole(PROTOCOL_OPERATOR) {
poolFactory.setFee(_fee);
}
/// @inheritdoc IAccessHub
function setSkimEnabledLegacy(address _pair, bool _status) external onlyRole(PROTOCOL_OPERATOR) {
poolFactory.setSkimEnabled(_pair, _status);
}
/**
* VoteModule Functions
*/
/// @inheritdoc IAccessHub
function setCooldownExemption(address[] calldata _candidates, bool[] calldata _exempt) external timelocked {
for (uint256 i; i < _candidates.length; ++i) {
voteModule.setCooldownExemption(_candidates[i], _exempt[i]);
}
}
/// @inheritdoc IAccessHub
function setNewVoteModuleCooldown(uint256 _newCooldown) external timelocked {
voteModule.setNewCooldown(_newCooldown);
}
/// @inheritdoc IAccessHub
function kickInactive(address[] calldata _nonparticipants) external onlyRole(PROTOCOL_OPERATOR) {
IVoter voterContract = IVoter(voter);
uint256 nextPeriod = voterContract.getPeriod() + 1;
/// @dev loop through all input addresses to check status of vote
for (uint256 i; i < _nonparticipants.length; ++i) {
/// @dev store for use
address nonparticipant = _nonparticipants[i];
/// @dev fetch data on current voting period (nextPeriod votes)
(address[] memory _pools, uint256[] memory _weights) = voterContract.getVotes(nonparticipant, nextPeriod);
/// @dev require the user has not voted this epoch
require(_pools.length == 0 && _weights.length == 0, Errors.KICK_FORBIDDEN(nonparticipant));
/// @dev reset the user's votes
voterContract.reset(nonparticipant);
}
}
/**
* Timelock specific functions
*/
/// @inheritdoc IAccessHub
function execute(address _target, bytes calldata _payload) external timelocked {
(bool success,) = _target.call(_payload);
require(success, Errors.MANUAL_EXECUTION_FAILURE(_payload));
}
/// @inheritdoc IAccessHub
function setNewTimelock(address _timelock) external timelocked {
require(timelock != _timelock, Errors.SAME_ADDRESS());
timelock = _timelock;
}
/// backup distribute method
function backupDistribute() external onlyRole(PROTOCOL_OPERATOR) {
backupDistributeBatch(0, type(uint256).max);
}
function backupDistributeBatch(uint256 startIndex, uint256 batchSize) public onlyRole(PROTOCOL_OPERATOR) {
address SHADOW = address(xShadow.SHADOW());
/// force unpause xshadow if its already paused
if (Pausable(address(xShadow)).paused()) {
xShadow.unpause();
}
minter.updatePeriod();
uint256 currentPeriod = voter.getPeriod();
address[] memory gauges = voter.getAllGauges();
uint256 totalRewardPerPeriod = voter.totalRewardPerPeriod(currentPeriod);
uint256 totalVotesPerPeriod = voter.totalVotesPerPeriod(currentPeriod);
uint256 endIndex = startIndex + batchSize;
if (endIndex > gauges.length) {
endIndex = gauges.length;
}
for (uint256 i = startIndex; i < endIndex; i++) {
uint256 lastDistro = voter.lastDistro(gauges[i]);
if (lastDistro == currentPeriod) {
continue;
}
uint256 balanceInVoter = IERC20(SHADOW).balanceOf(address(voter));
address pool = voter.poolForGauge(gauges[i]);
uint256 poolVotes = voter.poolTotalVotesPerPeriod(pool, currentPeriod);
uint256 numerator = totalRewardPerPeriod * poolVotes * 1e18;
uint256 balanceNeeded = numerator == 0 ? 0 : numerator / totalVotesPerPeriod / 1e18;
if (balanceNeeded > balanceInVoter) {
IERC20(SHADOW).transfer(address(voter), balanceNeeded - balanceInVoter);
}
if (voter.isAlive(gauges[i])) {
voter.killGauge(gauges[i]);
voter.reviveGauge(gauges[i]);
} else {
voter.stuckEmissionsRecovery(gauges[i], currentPeriod);
}
}
}
/// @dev allow distributing emissions via the accessHub
function notifyEmissions(address[] calldata pools, uint256[] calldata emissions)
external
onlyRole(PROTOCOL_OPERATOR)
{
IERC20 SHADOW = IERC20(xShadow.SHADOW());
SHADOW.approve(address(xShadow), SHADOW.balanceOf(address(this)));
xShadow.convertEmissionsToken(SHADOW.balanceOf(address(this)));
for (uint256 i; i < pools.length; ++i) {
address pool = pools[i];
address gauge = voter.gaugeForPool(pool);
uint256 amount = emissions[i];
xShadow.approve(gauge, amount);
/// @dev both CL and legacy gauges have the same function so we can reuse the interface regardless
IGaugeV3(gauge).notifyRewardAmount(address(xShadow), amount);
}
}
function rescue(address token) external onlyRole(PROTOCOL_OPERATOR) {
IERC20(token).transfer(treasury, IERC20(token).balanceOf(address(this)));
}
function rescueFromX33(address _token, uint256 _amount) external onlyRole(PROTOCOL_OPERATOR) {
x33.rescue(_token, _amount);
}
function updateLegacyPairWithGaugesFeeSplit(uint256 start, uint256 batchSize)
external
onlyRole(PROTOCOL_OPERATOR)
{
uint256 end = start + batchSize;
uint256 length = voter.getGaugesLength();
end = end > length ? length : end;
for (uint256 i = start; i < end; ++i) {
address gauge = voter.getGauge(i);
address pair = voter.poolForGauge(gauge);
if (voter.isAlive(gauge)) {
poolFactory.setPairFeeSplit(pair, 10_000);
} else {
poolFactory.setPairFeeSplit(pair, 500);
}
}
}
function migrateGauges(address[] calldata gauges) external onlyRole(PROTOCOL_OPERATOR) {
uint256 length = gauges.length;
IVoter _voter = voter;
for (uint256 i = 0; i < length; ++i) {
address gauge = gauges[i];
if (oldVoter.isLegacyGauge(gauge)) {
address pair = oldVoter.poolForGauge(gauge);
_voter.createGauge(pair);
} else {
IShadowV3Pool pool = IShadowV3Pool(oldVoter.poolForGauge(gauge));
address token0 = pool.token0();
address token1 = pool.token0();
int24 tickSpacing = pool.tickSpacing();
_voter.createCLGauge(token0, token1, tickSpacing);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IVoteModule} from "contracts/interfaces/IVoteModule.sol";
import {IVoter} from "contracts/interfaces/IVoter.sol";
interface IAccessHub {
/// @dev Struct to hold initialization parameters
struct InitParams {
address timelock;
address treasury;
address voter;
address minter;
address launcherPlugin;
address xShadow;
address x33;
address shadowV3PoolFactory;
address poolFactory;
address clGaugeFactory;
address gaugeFactory;
address feeRecipientFactory;
address feeDistributorFactory;
address feeCollector;
address voteModule;
}
/// @notice protocol timelock address
function timelock() external view returns (address timelock);
/// @notice protocol treasury address
function treasury() external view returns (address treasury);
/// @notice vote module
function voteModule() external view returns (IVoteModule voteModule);
/// @notice voter
function voter() external view returns (IVoter voter);
/// @notice concentrated (v3) gauge factory
function clGaugeFactory() external view returns (address _clGaugeFactory);
/// @notice legacy gauge factory address
function gaugeFactory() external view returns (address _gaugeFactory);
/// @notice the feeDistributor factory address
function feeDistributorFactory() external view returns (address _feeDistributorFactory);
/// @notice initializing function for setting values in the AccessHub
function initialize(InitParams calldata params) external;
/// @notice function for reinitializing values in the AccessHub
function reinit(InitParams calldata params) external;
/// @notice sets the swap fees for multiple pairs
function setSwapFees(address[] calldata _pools, uint24[] calldata _swapFees, bool[] calldata _concentrated)
external;
/// @notice sets the split of fees between LPs and voters
function setFeeSplitCL(address[] calldata _pools, uint8[] calldata _feeProtocol) external;
/// @notice sets the split of fees between LPs and voters for legacy pools
function setFeeSplitLegacy(address[] calldata _pools, uint256[] calldata _feeSplits) external;
/**
* Voter governance
*/
/// @notice sets a new governor address in the voter.sol contract
function setNewGovernorInVoter(address _newGovernor) external;
/// @notice whitelists a token for governance, or removes if boolean is set to false
function governanceWhitelist(address[] calldata _token, bool[] calldata _whitelisted) external;
/// @notice kills active gauges, removing them from earning further emissions, and claims their fees prior
function killGauge(address[] calldata _pairs) external;
/// @notice revives inactive/killed gauges
function reviveGauge(address[] calldata _pairs) external;
/// @notice sets a new NFP Manager
function setNfpManager(address _nfpManager) external;
/// @notice syncs NFP Managers for gauges
function syncNfpManager(address[] calldata gauges) external;
/// @notice sets the ratio of xShadow/Shadow awarded globally to LPs
function setEmissionsRatioInVoter(uint256 _pct) external;
/// @notice allows governance to retrieve emissions in the voter contract that will not be distributed due to the gauge being inactive
/// @dev allows per-period retrieval for granularity
function retrieveStuckEmissionsToGovernance(address _gauge, uint256 _period) external;
/// @notice allows governance to designate a gauge as the "main" one, to prevent governance spam and confusion
function setMainGaugeForClPair(address tokenA, address tokenB, address gauge) external;
function createGaugeForPool(address _pool) external;
function resetVotesOnBehalfOf(address _user) external;
/**
* xShadow Functions
*/
/// @notice enables or disables the transfer whitelist in xShadow
function transferWhitelistInXShadow(address[] calldata _who, bool[] calldata _whitelisted) external;
/// @notice enables or disables the transfer TO whitelists in xShadow
function transferToWhitelistInXShadow(address[] calldata _who, bool[] calldata _whitelisted) external;
/// @notice enables or disables the governance in xShadow
function toggleXShadowGovernance(bool enable) external;
/// @notice allows redemption from the operator
function operatorRedeemXShadow(uint256 _amount) external;
/// @notice migrates the xShadow operator
function migrateOperator(address _operator) external;
/// @notice rescues any trapped tokens in xShadow
function rescueTrappedTokens(address[] calldata _tokens, uint256[] calldata _amounts) external;
/// @notice set dust threshold before a rebase can happen
function setRebaseThreshold(uint256 _newThreshold) external;
/**
* X33 Functions
*/
/// @notice transfers the x33 operator address
function transferOperatorInX33(address _newOperator) external;
/**
* Minter Functions
*/
/// @notice sets the inflation multiplier
/// @param _multiplier the multiplier
function setEmissionsMultiplierInMinter(uint256 _multiplier) external;
/**
* Reward List Functions
*/
/// @notice function for removing rewards for feeDistributors
function removeFeeDistributorRewards(address[] calldata _pools, address[] calldata _rewards) external;
/**
* LauncherPlugin specific functions
*/
/// @notice allows migrating the parameters from one pool to the other
/// @param _oldPool the current address of the pair
/// @param _newPool the new pool's address
function migratePoolInLauncherPlugin(address _oldPool, address _newPool) external;
/// @notice set launcher configurations for a pool
/// @param _pool address of the pool
/// @param _take the fee that goes to the designated recipient
/// @param _recipient the address that receives the fees
function setConfigsInLauncherPlugin(address _pool, uint256 _take, address _recipient) external;
/// @notice enables the pool for LauncherConfigs
/// @param _pool address of the pool
function enablePoolInLauncherPlugin(address _pool) external;
/// @notice disables the pool for LauncherConfigs
/// @dev clears mappings
/// @param _pool address of the pool
function disablePoolInLauncherPlugin(address _pool) external;
/// @notice sets a new operator address
/// @param _newOperator new operator address
function setOperatorInLauncherPlugin(address _newOperator) external;
/// @notice gives authority to a new contract/address
/// @param _newAuthority the suggested new authority
function grantAuthorityInLauncherPlugin(address _newAuthority, string calldata _label) external;
/// @notice governance ability to label each authority in the system with an arbitrary string
function labelAuthorityInLauncherPlugin(address _authority, string calldata _label) external;
/// @notice removes authority from a contract/address
/// @param _oldAuthority the to-be-removed authority
function revokeAuthorityInLauncherPlugin(address _oldAuthority) external;
/**
* FeeCollector functions
*/
/// @notice Sets the treasury address to a new value.
/// @param newTreasury The new address to set as the treasury.
function setTreasuryInFeeCollector(address newTreasury) external;
/// @notice Sets the value of treasury fees to a new amount.
/// @param _treasuryFees The new amount of treasury fees to be set.
function setTreasuryFeesInFeeCollector(uint256 _treasuryFees) external;
/**
* FeeRecipientFactory functions
*/
/// @notice set the fee % to be sent to the treasury
/// @param _feeToTreasury the fee % to be sent to the treasury
function setFeeToTreasuryInFeeRecipientFactory(uint256 _feeToTreasury) external;
/// @notice set a new treasury address
/// @param _treasury the new address
function setTreasuryInFeeRecipientFactory(address _treasury) external;
/**
* CL Pool Factory functions
*/
/// @notice enables a tickSpacing with the given initialFee amount
/// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
/// @dev tickSpacings may never be removed once enabled
/// @param tickSpacing The spacing between ticks to be enforced for all pools created
/// @param initialFee The initial fee amount, denominated in hundredths of a bip (i.e. 1e-6)
function enableTickSpacing(int24 tickSpacing, uint24 initialFee) external;
/// @notice sets the feeProtocol (feeSplit) for new CL pools and stored in the factory
function setGlobalClFeeProtocol(uint8 _feeProtocolGlobal) external;
/// @notice sets the address of the voter in the v3 factory for gauge fee setting
function setVoterAddressInFactoryV3(address _voter) external;
/// @notice sets the address of the feeCollector in the v3 factory for fee routing
function setFeeCollectorInFactoryV3(address _newFeeCollector) external;
/**
* Legacy Pool Factory functions
*/
/// @notice sets the treasury address in the legacy factory
function setTreasuryInLegacyFactory(address _treasury) external;
/// @notice enables or disables if there is a feeSplit when no gauge for legacy pairs
function setFeeSplitWhenNoGauge(bool status) external;
/// @notice set the default feeSplit in the legacy factory
function setLegacyFeeSplitGlobal(uint256 _feeSplit) external;
/// @notice set the fee recipient for legacy pairs
function setLegacyFeeRecipient(address _pair, address _feeRecipient) external;
/// @notice set the default swap fee for legacy pools
function setLegacyFeeGlobal(uint256 _fee) external;
/// @notice sets whether a pair can have skim() called or not for rebasing purposes
function setSkimEnabledLegacy(address _pair, bool _status) external;
/**
* VoteModule Functions
*/
/// @notice sets addresses as exempt or removes their exemption
function setCooldownExemption(address[] calldata _candidates, bool[] calldata _exempt) external;
/// @notice function to change the cooldown in the voteModule
function setNewVoteModuleCooldown(uint256 _newCooldown) external;
/// @notice allows resetting of inactive votes to prevent dead votes
function kickInactive(address[] calldata _nonparticipants) external;
/**
* Timelock gated functions
*/
/// @notice timelock gated payload execution in case tokens get stuck or other unexpected behaviors
function execute(address _target, bytes calldata _payload) external;
/// @notice timelock gated function to change the timelock
function setNewTimelock(address _timelock) external;
/// @notice function for initializing the voter contract with its dependencies
function initializeVoter(IVoter.InitializationParams memory inputs) external;
function backupDistribute() external;
function backupDistributeBatch(uint256 startIndex, uint256 batchSize) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Central Errors Library
/// @notice Contains all custom errors used across the protocol
/// @dev Centralized error definitions to prevent redundancy
library Errors {
/*//////////////////////////////////////////////////////////////
VOTER ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when attempting to interact with an already active gauge
/// @param gauge The address of the gauge
error ACTIVE_GAUGE(address gauge);
/// @notice Thrown when attempting to interact with an inactive gauge
/// @param gauge The address of the gauge
error GAUGE_INACTIVE(address gauge);
/// @notice Thrown when attempting to whitelist an already whitelisted token
/// @param token The address of the token
error ALREADY_WHITELISTED(address token);
/// @notice Thrown when caller is not authorized to perform an action
/// @param caller The address of the unauthorized caller
error NOT_AUTHORIZED(address caller);
/// @notice Thrown when token is not whitelisted
/// @param token The address of the non-whitelisted token
error NOT_WHITELISTED(address token);
/// @notice Thrown when both tokens in a pair are not whitelisted
error BOTH_NOT_WHITELISTED();
/// @notice Thrown when address is not a valid pool
/// @param pool The invalid pool address
error NOT_POOL(address pool);
/// @notice Thrown when pool is not seeded in PoolUpdater
/// @param pool The invalid pool address
error NOT_SEEDED(address pool);
/// @notice Thrown when contract is not initialized
error NOT_INIT();
/// @notice Thrown when array lengths don't match
error LENGTH_MISMATCH();
/// @notice Thrown when pool doesn't have an associated gauge
/// @param pool The address of the pool
error NO_GAUGE(address pool);
/// @notice Thrown when rewards are already distributed for a period
/// @param gauge The gauge address
/// @param period The distribution period
error ALREADY_DISTRIBUTED(address gauge, uint256 period);
/// @notice Thrown when attempting to vote with zero amount
/// @param pool The pool address
error ZERO_VOTE(address pool);
/// @notice Thrown when ratio exceeds maximum allowed
/// @param _xRatio The excessive ratio value
error RATIO_TOO_HIGH(uint256 _xRatio);
/// @notice Thrown when vote operation fails
error VOTE_UNSUCCESSFUL();
/*//////////////////////////////////////////////////////////////
GAUGE V3 ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when the pool already has a gauge
/// @param pool The address of the pool
error GAUGE_EXISTS(address pool);
/// @notice Thrown when caller is not the voter
/// @param caller The address of the invalid caller
error NOT_VOTER(address caller);
/// @notice Thrown when amount is not greater than zero
/// @param amt The invalid amount
error NOT_GT_ZERO(uint256 amt);
/// @notice Thrown when attempting to claim future rewards
error CANT_CLAIM_FUTURE();
/// @notice Throw when gauge can't determine if using secondsInRange from the pool is safe
error NEED_TEAM_TO_UPDATE();
/*//////////////////////////////////////////////////////////////
GAUGE ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when amount is zero
error ZERO_AMOUNT();
/// @notice Thrown when stake notification fails
error CANT_NOTIFY_STAKE();
/// @notice Thrown when reward amount is too high
error REWARD_TOO_HIGH();
/// @notice Thrown when amount exceeds remaining balance
/// @param amount The requested amount
/// @param remaining The remaining balance
error NOT_GREATER_THAN_REMAINING(uint256 amount, uint256 remaining);
/// @notice Thrown when token operation fails
/// @param token The address of the problematic token
error TOKEN_ERROR(address token);
/// @notice Thrown when an address is not an NfpManager
error NOT_NFP_MANAGER(address nfpManager);
/*//////////////////////////////////////////////////////////////
FEE DISTRIBUTOR ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when period is not finalized
/// @param period The unfinalized period
error NOT_FINALIZED(uint256 period);
/// @notice Thrown when the destination of a redirect is not a feeDistributor
/// @param destination Destination of the redirect
error NOT_FEE_DISTRIBUTOR(address destination);
/// @notice Thrown when the destination of a redirect's pool/pair has completely different tokens
error DIFFERENT_DESTINATION_TOKENS();
/*//////////////////////////////////////////////////////////////
PAIR ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when ratio is unstable
error UNSTABLE_RATIO();
/// @notice Thrown when safe transfer fails
error SAFE_TRANSFER_FAILED();
/// @notice Thrown on arithmetic overflow
error OVERFLOW();
/// @notice Thrown when skim operation is disabled
error SKIM_DISABLED();
/// @notice Thrown when insufficient liquidity is minted
error INSUFFICIENT_LIQUIDITY_MINTED();
/// @notice Thrown when insufficient liquidity is burned
error INSUFFICIENT_LIQUIDITY_BURNED();
/// @notice Thrown when output amount is insufficient
error INSUFFICIENT_OUTPUT_AMOUNT();
/// @notice Thrown when input amount is insufficient
error INSUFFICIENT_INPUT_AMOUNT();
/// @notice Generic insufficient liquidity error
error INSUFFICIENT_LIQUIDITY();
/// @notice Invalid transfer error
error INVALID_TRANSFER();
/// @notice K value error in AMM
error K();
/*//////////////////////////////////////////////////////////////
PAIR FACTORY ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when fee is too high
error FEE_TOO_HIGH();
/// @notice Thrown when fee is zero
error ZERO_FEE();
/// @notice Thrown when token assortment is invalid
error INVALID_ASSORTMENT();
/// @notice Thrown when address is zero
error ZERO_ADDRESS();
/// @notice Thrown when pair already exists
error PAIR_EXISTS();
/// @notice Thrown when fee split is invalid
error INVALID_FEE_SPLIT();
/*//////////////////////////////////////////////////////////////
FEE RECIPIENT FACTORY ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when treasury fee is invalid
error INVALID_TREASURY_FEE();
/*//////////////////////////////////////////////////////////////
ROUTER ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when deadline has expired
error EXPIRED();
/// @notice Thrown when tokens are identical
error IDENTICAL();
/// @notice Thrown when amount is insufficient
error INSUFFICIENT_AMOUNT();
/// @notice Thrown when path is invalid
error INVALID_PATH();
/// @notice Thrown when token B amount is insufficient
error INSUFFICIENT_B_AMOUNT();
/// @notice Thrown when token A amount is insufficient
error INSUFFICIENT_A_AMOUNT();
/// @notice Thrown when input amount is excessive
error EXCESSIVE_INPUT_AMOUNT();
/// @notice Thrown when ETH transfer fails
error ETH_TRANSFER_FAILED();
/// @notice Thrown when reserves are invalid
error INVALID_RESERVES();
/*//////////////////////////////////////////////////////////////
MINTER ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when epoch 0 has already started
error STARTED();
/// @notice Thrown when emissions haven't started
error EMISSIONS_NOT_STARTED();
/// @notice Thrown when deviation is too high
error TOO_HIGH();
/// @notice Thrown when no value change detected
error NO_CHANGE();
/// @notice Thrown when updating emissions in same period
error SAME_PERIOD();
/// @notice Thrown when contract setup is invalid
error INVALID_CONTRACT();
/// @notice Thrown when legacy factory doesn't have feeSplitWhenNoGauge on
error FEE_SPLIT_WHEN_NO_GAUGE_IS_OFF();
/*//////////////////////////////////////////////////////////////
ACCESS HUB ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when addresses are identical
error SAME_ADDRESS();
/// @notice Thrown when caller is not timelock
/// @param caller The invalid caller address
error NOT_TIMELOCK(address caller);
/// @notice Thrown when manual execution fails
/// @param reason The failure reason
error MANUAL_EXECUTION_FAILURE(bytes reason);
/// @notice Thrown when kick operation is forbidden
/// @param target The target address
error KICK_FORBIDDEN(address target);
/*//////////////////////////////////////////////////////////////
VOTE MODULE ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when caller is not xShadow
error NOT_XSHADOW();
/// @notice Thrown when cooldown period is still active
error COOLDOWN_ACTIVE();
/// @notice Thrown when caller is not vote module
error NOT_VOTEMODULE();
/// @notice Thrown when caller is unauthorized
error UNAUTHORIZED();
/// @notice Thrown when caller is not access hub
error NOT_ACCESSHUB();
/// @notice Thrown when address is invalid
error INVALID_ADDRESS();
/*//////////////////////////////////////////////////////////////
LAUNCHER PLUGIN ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when caller is not authority
error NOT_AUTHORITY();
/// @notice Thrown when already an authority
error ALREADY_AUTHORITY();
/// @notice Thrown when caller is not operator
error NOT_OPERATOR();
/// @notice Thrown when already an operator
error ALREADY_OPERATOR();
/// @notice Thrown when pool is not enabled
/// @param pool The disabled pool address
error NOT_ENABLED(address pool);
/// @notice Thrown when fee distributor is missing
error NO_FEEDIST();
/// @notice Thrown when already enabled
error ENABLED();
/// @notice Thrown when take value is invalid
error INVALID_TAKE();
/*//////////////////////////////////////////////////////////////
X33 ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when value is zero
error ZERO();
/// @notice Thrown when amount is insufficient
error NOT_ENOUGH();
/// @notice Thrown when value doesn't conform to scale
/// @param value The non-conforming value
error NOT_CONFORMED_TO_SCALE(uint256 value);
/// @notice Thrown when contract is locked
error LOCKED();
/// @notice Thrown when rebase is in progress
error REBASE_IN_PROGRESS();
/// @notice Thrown when aggregator reverts
/// @param reason The revert reason
error AGGREGATOR_REVERTED(bytes reason);
/// @notice Thrown when output amount is too low
/// @param amount The insufficient amount
error AMOUNT_OUT_TOO_LOW(uint256 amount);
/// @notice Thrown when aggregator is not whitelisted
/// @param aggregator The non-whitelisted aggregator address
error AGGREGATOR_NOT_WHITELISTED(address aggregator);
/// @notice Thrown when token is forbidden
/// @param token The forbidden token address
error FORBIDDEN_TOKEN(address token);
/*//////////////////////////////////////////////////////////////
XSHADOW ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when caller is not minter
error NOT_MINTER();
/// @notice Thrown when no vest exists
error NO_VEST();
/// @notice Thrown when already exempt
error ALREADY_EXEMPT();
/// @notice Thrown when not exempt
error NOT_EXEMPT();
/// @notice Thrown when rescue operation is not allowed
error CANT_RESCUE();
/// @notice Thrown when array lengths mismatch
error ARRAY_LENGTHS();
/// @notice Thrown when vesting periods overlap
error VEST_OVERLAP();
/*//////////////////////////////////////////////////////////////
V3 FACTORY ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when tokens are identical
error IDENTICAL_TOKENS();
/// @notice Thrown when fee is too large
error FEE_TOO_LARGE();
/// @notice Address zero error
error ADDRESS_ZERO();
/// @notice Fee zero error
error F0();
/// @notice Thrown when value is out of bounds
/// @param value The out of bounds value
error OOB(uint8 value);
/*//////////////////////////////////////////////////////////////
POOL UPDATER ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when seeding for a pool fails
error TRANSFER_FROM_FOR_SEEDING_FAILED(address token, uint256 amount);
/// @notice Thrown when seeding for a pool fails
error SEEDING_FAILED();
/// @notice Thrown when updatePools is called too early
error TOO_EARLY();
/// @notice Thrown when a callback is called when an update isn't running
error NOT_RUNNING();
/// @notice Thrown when updatePools didn't perform any updates
error NO_UPDATES();
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/extensions/AccessControlEnumerable.sol)
pragma solidity ^0.8.20;
import {IAccessControlEnumerable} from "@openzeppelin/contracts/access/extensions/IAccessControlEnumerable.sol";
import {AccessControlUpgradeable} from "../AccessControlUpgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerable, AccessControlUpgradeable {
using EnumerableSet for EnumerableSet.AddressSet;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControlEnumerable
struct AccessControlEnumerableStorage {
mapping(bytes32 role => EnumerableSet.AddressSet) _roleMembers;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControlEnumerable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlEnumerableStorageLocation = 0xc1f6fe24621ce81ec5827caf0253cadb74709b061630e6b55e82371705932000;
function _getAccessControlEnumerableStorage() private pure returns (AccessControlEnumerableStorage storage $) {
assembly {
$.slot := AccessControlEnumerableStorageLocation
}
}
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual returns (address) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
return $._roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual returns (uint256) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
return $._roleMembers[role].length();
}
/**
* @dev Return all accounts that have `role`
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function getRoleMembers(bytes32 role) public view virtual returns (address[] memory) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
return $._roleMembers[role].values();
}
/**
* @dev Overload {AccessControl-_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
bool granted = super._grantRole(role, account);
if (granted) {
$._roleMembers[role].add(account);
}
return granted;
}
/**
* @dev Overload {AccessControl-_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
bool revoked = super._revokeRole(role, account);
if (revoked) {
$._roleMembers[role].remove(account);
}
return revoked;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface ILauncherPlugin {
/// @dev struct that holds the configurations of each specific pool
struct LauncherConfigs {
uint256 launcherTake;
address takeRecipient;
}
event NewOperator(address indexed _old, address indexed _new);
event NewAuthority(address indexed _newAuthority);
event RemovedAuthority(address indexed _previousAuthority);
event EnabledPool(address indexed pool, string indexed _name);
event DisabledPool(address indexed pool);
event MigratedPool(address indexed oldPool, address indexed newPool);
event Configured(address indexed pool, uint256 take, address indexed recipient);
event Labeled(address indexed authority, string indexed label);
/// @notice address of the accessHub
function accessHub() external view returns (address _accessHub);
/// @notice protocol operator address
function operator() external view returns (address _operator);
/// @notice the denominator constant
function DENOM() external view returns (uint256 _denominator);
/// @notice whether configs are enabled for a pool
/// @param _pool address of the pool
/// @return bool
function launcherPluginEnabled(address _pool) external view returns (bool);
/// @notice maps whether an address is an authority or not
/// @param _who the address to check
/// @return _is true or false
function authorityMap(address _who) external view returns (bool _is);
/// @notice allows migrating the parameters from one pool to the other
/// @param _oldPool the current address of the pair
/// @param _newPool the new pool's address
function migratePool(address _oldPool, address _newPool) external;
/// @notice fetch the launcher configs if any
/// @param _pool address of the pool
/// @return LauncherConfigs the configs
function poolConfigs(address _pool) external view returns (uint256, address);
/// @notice view functionality to see who is an authority
function nameOfAuthority(address) external view returns (string memory);
/// @notice returns the pool address for a feeDist
/// @param _feeDist address of the feeDist
/// @return _pool the pool address from the mapping
function feeDistToPool(address _feeDist) external view returns (address _pool);
/// @notice set launcher configurations for a pool
/// @param _pool address of the pool
/// @param _take the fee that goes to the designated recipient
/// @param _recipient the address that receives the fees
function setConfigs(address _pool, uint256 _take, address _recipient) external;
/// @notice enables the pool for LauncherConfigs
/// @param _pool address of the pool
function enablePool(address _pool) external;
/// @notice disables the pool for LauncherConfigs
/// @dev clears mappings
/// @param _pool address of the pool
function disablePool(address _pool) external;
/// @notice sets a new operator address
/// @param _newOperator new operator address
function setOperator(address _newOperator) external;
/// @notice gives authority to a new contract/address
/// @param _newAuthority the suggested new authority
function grantAuthority(address _newAuthority, string calldata) external;
/// @notice removes authority from a contract/address
/// @param _oldAuthority the to-be-removed authority
function revokeAuthority(address _oldAuthority) external;
/// @notice labels an authority
function label(address, string calldata) external;
/// @notice returns the values for the launcherConfig of the specific feeDist
/// @param _feeDist the address of the feeDist
/// @return _launcherTake fee amount taken
/// @return _recipient address that receives the fees
function values(address _feeDist) external view returns (uint256 _launcherTake, address _recipient);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IVoter} from "./IVoter.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
interface IXShadow is IERC20 {
struct VestPosition {
/// @dev amount of xShadow
uint256 amount;
/// @dev start unix timestamp
uint256 start;
/// @dev start + MAX_VEST (end timestamp)
uint256 maxEnd;
/// @dev vest identifier (starting from 0)
uint256 vestID;
}
event CancelVesting(address indexed user, uint256 indexed vestId, uint256 amount);
event ExitVesting(address indexed user, uint256 indexed vestId, uint256 amount);
event InstantExit(address indexed user, uint256);
event NewSlashingPenalty(uint256 penalty);
event NewVest(address indexed user, uint256 indexed vestId, uint256 indexed amount);
event NewVestingTimes(uint256 min, uint256 max);
event Converted(address indexed user, uint256);
event Exemption(address indexed candidate, bool status, bool success);
event XShadowRedeemed(address indexed user, uint256);
event NewOperator(address indexed o, address indexed n);
event Rebase(address indexed caller, uint256 amount);
event NewRebaseThreshold(uint256 threshold);
/// @notice returns info on a user's vests
function vestInfo(address user, uint256)
external
view
returns (uint256 amount, uint256 start, uint256 maxEnd, uint256 vestID);
/// @notice address of the shadow token
function SHADOW() external view returns (IERC20);
/// @notice address of the voter
function VOTER() external view returns (IVoter);
function MINTER() external view returns (address);
function ACCESS_HUB() external view returns (address);
/// @notice address of the operator
function operator() external view returns (address);
/// @notice address of the VoteModule
function VOTE_MODULE() external view returns (address);
/// @notice max slashing amount
function SLASHING_PENALTY() external view returns (uint256);
/// @notice denominator
function BASIS() external view returns (uint256);
/// @notice the minimum vesting length
function MIN_VEST() external view returns (uint256);
/// @notice the maximum vesting length
function MAX_VEST() external view returns (uint256);
function shadow() external view returns (address);
/// @notice the last period rebases were distributed
function lastDistributedPeriod() external view returns (uint256);
/// @notice amount of pvp rebase penalties accumulated pending to be distributed
function pendingRebase() external view returns (uint256);
/// @notice dust threshold before a rebase can happen
function rebaseThreshold() external view returns (uint256);
/// @notice pauses the contract
function pause() external;
/// @notice unpauses the contract
function unpause() external;
/**
*
*/
// General use functions
/**
*
*/
/// @dev mints xShadows for each shadow.
function convertEmissionsToken(uint256 _amount) external;
/// @notice function called by the minter to send the rebases once a week
function rebase() external;
/**
* @dev exit instantly with a penalty
* @param _amount amount of xShadows to exit
*/
function exit(uint256 _amount) external returns (uint256 _exitedAmount);
/// @dev vesting xShadows --> emissionToken functionality
function createVest(uint256 _amount) external;
/// @dev handles all situations regarding exiting vests
function exitVest(uint256 _vestID) external;
/**
*
*/
// Permissioned functions, timelock/operator gated
/**
*
*/
/// @dev allows the operator to redeem collected xShadows
function operatorRedeem(uint256 _amount) external;
/// @dev allows rescue of any non-stake token
function rescueTrappedTokens(address[] calldata _tokens, uint256[] calldata _amounts) external;
/// @notice migrates the operator to another contract
function migrateOperator(address _operator) external;
/// @notice set exemption status for an address
function setExemption(address[] calldata _exemptee, bool[] calldata _exempt) external;
function setExemptionTo(address[] calldata _exemptee, bool[] calldata _exempt) external;
/// @notice set dust threshold before a rebase can happen
function setRebaseThreshold(uint256 _newThreshold) external;
/**
*
*/
// Getter functions
/**
*
*/
/// @notice returns the amount of SHADOW within the contract
function getBalanceResiding() external view returns (uint256);
/// @notice returns the total number of individual vests the user has
function usersTotalVests(address _who) external view returns (uint256 _numOfVests);
/// @notice whether the address is exempt
/// @param _who who to check
/// @return _exempt whether it's exempt
function isExempt(address _who) external view returns (bool _exempt);
/// @notice returns the vest info for a user
/// @param _who who to check
/// @param _vestID vest ID to check
/// @return VestPosition vest info
function getVestInfo(address _who, uint256 _vestID) external view returns (VestPosition memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IXShadow} from "contracts/interfaces/IXShadow.sol";
interface IX33 is IERC20 {
/// @dev parameters passed to the aggregator swap
struct AggregatorParams {
address aggregator; // address of the whitelisted aggregator
address tokenIn; // token to swap from
uint256 amountIn; // amount of tokenIn to swap
uint256 minAmountOut; // minimum amount of tokenOut to receive
bytes callData; // encoded swap calldata
}
event Entered(address indexed user, uint256 amount, uint256 ratioAtDeposit);
event Exited(address indexed user, uint256 _outAmount, uint256 ratioAtWithdrawal);
event NewOperator(address _oldOperator, address _newOperator);
event Compounded(uint256 oldRatio, uint256 newRatio, uint256 amount);
event SwappedBribe(address indexed operator, address indexed tokenIn, uint256 amountIn, uint256 amountOut);
event Rebased(uint256 oldRatio, uint256 newRatio, uint256 amount);
/// @notice Event emitted when an aggregator's whitelist status changes
event AggregatorWhitelistUpdated(address aggregator, bool status);
event Unlocked(uint256 _ts);
event UpdatedIndex(uint256 _index);
event ClaimedIncentives(address[] feeDistributors, address[][] tokens);
/// @notice submits the optimized votes for the epoch
function submitVotes(address[] calldata _pools, uint256[] calldata _weights) external;
/// @notice swap function using aggregators to process rewards into SHADOW
function swapIncentiveViaAggregator(AggregatorParams calldata _params) external;
/// @notice claims the rebase accrued to x33
function claimRebase() external;
/// @notice compounds any existing SHADOW within the contract
function compound() external;
/// @notice direct claim
function claimIncentives(address[] calldata _feeDistributors, address[][] calldata _tokens) external;
/// @notice rescue stuck tokens
function rescue(address _token, uint256 _amount) external;
/// @notice allows the operator to unlock the contract for the current period
function unlock() external;
/// @notice add or remove an aggregator from the whitelist (timelocked)
/// @param _aggregator address of the aggregator to update
/// @param _status new whitelist status
function whitelistAggregator(address _aggregator, bool _status) external;
/// @notice transfers the operator via accesshub
function transferOperator(address _newOperator) external;
/// @notice simple getPeriod call
function getPeriod() external view returns (uint256 period);
/// @notice if the contract is unlocked for deposits
function isUnlocked() external view returns (bool);
/// @notice determines whether the cooldown is active
function isCooldownActive() external view returns (bool);
/// @notice address of the current operator
function operator() external view returns (address);
/// @notice accessHub address
function accessHub() external view returns (address);
/// @notice returns the ratio of xShadow per X33 token
function ratio() external view returns (uint256 _ratio);
/// @notice the most recent active period the contract has interacted in
function activePeriod() external view returns (uint256);
/// @notice whether the periods are unlocked
function periodUnlockStatus(uint256 _period) external view returns (bool unlocked);
/// @notice the shadow token
function shadow() external view returns (IERC20);
/// @notice the xShadow token
function xShadow() external view returns (IXShadow);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Shadow V3 Factory
/// @notice The Shadow V3 Factory facilitates creation of Shadow V3 pools and control over the protocol fees
interface IShadowV3Factory {
/// @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 fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool
);
/// @notice Emitted when a new tickspacing amount is enabled for pool creation via the factory
/// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param fee The fee, denominated in hundredths of a bip
event TickSpacingEnabled(int24 indexed tickSpacing, uint24 indexed fee);
/// @notice Emitted when the protocol fee is changed
/// @param feeProtocolOld The previous value of the protocol fee
/// @param feeProtocolNew The updated value of the protocol fee
event SetFeeProtocol(uint24 feeProtocolOld, uint24 feeProtocolNew);
/// @notice Emitted when the protocol fee is changed
/// @param pool The pool address
/// @param feeProtocolOld The previous value of the protocol fee
/// @param feeProtocolNew The updated value of the protocol fee
event SetPoolFeeProtocol(address pool, uint24 feeProtocolOld, uint24 feeProtocolNew);
/// @notice Emitted when a pool's fee is changed
/// @param pool The pool address
/// @param newFee The updated value of the protocol fee
event FeeAdjustment(address pool, uint24 newFee);
/// @notice Emitted when the fee collector is changed
/// @param oldFeeCollector The previous implementation
/// @param newFeeCollector The new implementation
event FeeCollectorChanged(address indexed oldFeeCollector, address indexed newFeeCollector);
/// @notice Returns the PoolDeployer address
/// @return The address of the PoolDeployer contract
function shadowV3PoolDeployer() external returns (address);
/// @notice Returns the fee amount for a given tickSpacing, if enabled, or 0 if not enabled
/// @dev A tickSpacing can never be removed, so this value should be hard coded or cached in the calling context
/// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
/// @param tickSpacing The enabled tickSpacing. Returns 0 in case of unenabled tickSpacing
/// @return initialFee The initial fee
function tickSpacingInitialFee(int24 tickSpacing) external view returns (uint24 initialFee);
/// @notice Returns the pool address for a given pair of tokens and a tickSpacing, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param tickSpacing The tickSpacing of the pool
/// @return pool The pool address
function getPool(address tokenA, address tokenB, int24 tickSpacing) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param tickSpacing The desired tickSpacing for the pool
/// @param sqrtPriceX96 initial sqrtPriceX96 of the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
/// @dev The call will revert if the pool already exists, the tickSpacing is invalid, or the token arguments are invalid.
/// @return pool The address of the newly created pool
function createPool(address tokenA, address tokenB, int24 tickSpacing, uint160 sqrtPriceX96)
external
returns (address pool);
/// @notice Enables a tickSpacing with the given initialFee amount
/// @dev unlike UniswapV3, we map via the tickSpacing rather than the fee tier
/// @dev tickSpacings may never be removed once enabled
/// @param tickSpacing The spacing between ticks to be enforced for all pools created
/// @param initialFee The initial fee amount, denominated in hundredths of a bip (i.e. 1e-6)
function enableTickSpacing(int24 tickSpacing, uint24 initialFee) external;
/// @notice Returns the default protocol fee value
/// @return _feeProtocol The default protocol fee percentage
function feeProtocol() external view returns (uint24 _feeProtocol);
/// @notice Returns the protocol fee percentage for a specific pool
/// @dev If the fee is 0 or the pool is uninitialized, returns the Factory's default feeProtocol
/// @param pool The address of the pool
/// @return _feeProtocol The protocol fee percentage for the specified pool
function poolFeeProtocol(address pool) external view returns (uint24 _feeProtocol);
/// @notice Sets the default protocol fee percentage
/// @param _feeProtocol New default protocol fee percentage for token0 and token1
function setFeeProtocol(uint24 _feeProtocol) external;
/// @notice Retrieves the parameters used in constructing a pool
/// @dev Called by the pool constructor to fetch the pool's parameters
/// @return factory The factory address
/// @return token0 The first token of the pool by address sort order
/// @return token1 The second token of the pool by address sort order
/// @return fee The initialized fee tier of the pool, denominated in hundredths of a bip
/// @return tickSpacing The minimum number of ticks between initialized ticks
function parameters()
external
view
returns (address factory, address token0, address token1, uint24 fee, int24 tickSpacing);
/// @notice Updates the fee collector address
/// @param _feeCollector The new fee collector address
function setFeeCollector(address _feeCollector) external;
/// @notice Updates the swap fee for a specific pool
/// @param _pool The address of the pool to modify
/// @param _fee The new fee value, scaled where 1_000_000 = 100%
function setFee(address _pool, uint24 _fee) external;
/// @notice Returns the current fee collector address
/// @dev The fee collector contract determines the distribution of protocol fees
/// @return The address of the fee collector contract
function feeCollector() external view returns (address);
/// @notice Flag for getting a pool to use the default feeProcotol
/// @dev type(uint24).max denotes using default feeProcotol
function DEFAULT_FEE_FLAG() external view returns (uint24);
/// @notice Updates the protocol fee percentage for a specific pool
/// @dev type(uint24).max denotes using default feeProcotol
/// @param pool The address of the pool to modify
/// @param _feeProtocol The new protocol fee percentage to assign
function setPoolFeeProtocol(address pool, uint24 _feeProtocol) external;
/// @notice Enables fee protocol splitting upon gauge creation
/// @param pool The address of the pool to enable fee splitting for
function gaugeFeeSplitEnable(address pool) external;
/// @notice Updates the voter contract address
/// @param _voter The new voter contract address
function setVoter(address _voter) external;
/// @notice Checks if a given address is a V3 pool
/// @param _pool The address to check
/// @return isV3 True if the address is a V3 pool, false otherwise
function isPairV3(address _pool) external view returns (bool isV3);
/// @notice Initializes the factory with a pool deployer
/// @param poolDeployer The address of the pool deployer contract
function initialize(address poolDeployer) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {IShadowV3PoolImmutables} from "./pool/IShadowV3PoolImmutables.sol";
import {IShadowV3PoolState} from "./pool/IShadowV3PoolState.sol";
import {IShadowV3PoolDerivedState} from "./pool/IShadowV3PoolDerivedState.sol";
import {IShadowV3PoolActions} from "./pool/IShadowV3PoolActions.sol";
import {IShadowV3PoolOwnerActions} from "./pool/IShadowV3PoolOwnerActions.sol";
import {IShadowV3PoolErrors} from "./pool/IShadowV3PoolErrors.sol";
import {IShadowV3PoolEvents} from "./pool/IShadowV3PoolEvents.sol";
/// @title The interface for a Shadow V3 Pool
/// @notice A Shadow pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IShadowV3Pool is
IShadowV3PoolImmutables,
IShadowV3PoolState,
IShadowV3PoolDerivedState,
IShadowV3PoolActions,
IShadowV3PoolOwnerActions,
IShadowV3PoolErrors,
IShadowV3PoolEvents
{
/// @notice if a new period, advance on interaction
function _advancePeriod() external;
/// @notice Get the index of the last period in the pool
/// @return The index of the last period
function lastPeriod() external view returns (uint256);
/// @notice allows reading arbitrary storage slots
function readStorage(bytes32[] calldata slots) external view returns (bytes32[] memory returnData);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
interface IGaugeV3 {
/// @notice Emitted when the NFP Manager is changed
/// @param newNfpManager The address of the new NFP Manager
/// @param oldNfpManager The address of the old NFP Manager
event NfpManagerChanged(address indexed newNfpManager, address indexed oldNfpManager);
/// @notice Emitted when a reward notification is made.
/// @param from The address from which the reward is notified.
/// @param reward The address of the reward token.
/// @param amount The amount of rewards notified.
/// @param period The period for which the rewards are notified.
event NotifyReward(address indexed from, address indexed reward, uint256 amount, uint256 period);
/// @notice Emitted when a bribe is made.
/// @param from The address from which the bribe is made.
/// @param reward The address of the reward token.
/// @param amount The amount of tokens bribed.
/// @param period The period for which the bribe is made.
event Bribe(address indexed from, address indexed reward, uint256 amount, uint256 period);
/// @notice Emitted when rewards are claimed.
/// @param period The period for which the rewards are claimed.
/// @param _positionHash The identifier of the NFP for which rewards are claimed.
/// @param receiver The address of the receiver of the claimed rewards.
/// @param reward The address of the reward token.
/// @param amount The amount of rewards claimed.
event ClaimRewards(uint256 period, bytes32 _positionHash, address receiver, address reward, uint256 amount);
/// @notice Emitted when a new reward token was pushed to the rewards array
event RewardAdded(address reward);
/// @notice Emitted when a reward token was removed from the rewards array
event RewardRemoved(address reward);
/// @notice Returns the NFP Manager
function nfpManager() external view returns (address);
/// @notice updates pool data after period flip
function updatePool() external;
/// @notice Syncs NFP Manager from the voter
function syncNfpManager() external;
/// @notice returns an array of all nfpManagers in this gauge
function getNfpManagers() external view returns (address[] memory);
/// @notice returns the pool of this gauge
function pool() external view returns (address);
/// @notice Retrieves the value of the firstPeriod variable.
/// @return The value of the firstPeriod variable.
function firstPeriod() external returns (uint256);
/// @notice Retrieves the total supply of a specific token for a given period.
/// @param period The period for which to retrieve the total supply.
/// @param token The address of the token for which to retrieve the total supply.
/// @return The total supply of the specified token for the given period.
function tokenTotalSupplyByPeriod(uint256 period, address token) external view returns (uint256);
/// @notice Retrieves the getTokenTotalSupplyByPeriod of the current period.
/// @dev included to support voter's left() check during distribute().
/// @param token The address of the token for which to retrieve the remaining amount.
/// @return The amount of tokens left to distribute in this period.
function left(address token) external view returns (uint256);
/// @notice Retrieves the reward rate for a specific reward address.
/// @dev this method returns the base rate without boost
/// @param token The address of the reward for which to retrieve the reward rate.
/// @return The reward rate for the specified reward address.
function rewardRate(address token) external view returns (uint256);
/// @notice Retrieves the claimed amount for a specific period, position hash, and user address.
/// @param period The period for which to retrieve the claimed amount.
/// @param _positionHash The identifier of the NFP for which to retrieve the claimed amount.
/// @param reward The address of the token for the claimed amount.
/// @return The claimed amount for the specified period, token ID, and user address.
function periodClaimedAmount(uint256 period, bytes32 _positionHash, address reward)
external
view
returns (uint256);
/// @notice Retrieves the last claimed period for a specific token, token ID combination.
/// @param token The address of the reward token for which to retrieve the last claimed period.
/// @param _positionHash The identifier of the NFP for which to retrieve the last claimed period.
/// @return The last claimed period for the specified token and token ID.
function lastClaimByToken(address token, bytes32 _positionHash) external view returns (uint256);
/// @notice Checks if a given address is a valid reward.
/// @param reward The address to check.
/// @return A boolean indicating whether the address is a valid reward.
function isGaugeReward(address reward) external view returns (bool);
/// @notice Returns an array of reward token addresses.
/// @return An array of reward token addresses.
function getRewardTokens() external view returns (address[] memory);
/// @notice Returns the hash used to store positions in a mapping
/// @param owner The address of the position owner
/// @param index The index of the position
/// @param tickLower The lower tick boundary of the position
/// @param tickUpper The upper tick boundary of the position
/// @return _hash The hash used to store positions in a mapping
function positionHash(address owner, uint256 index, int24 tickLower, int24 tickUpper)
external
pure
returns (bytes32);
/*
/// @notice Retrieves the liquidity and boosted liquidity for a specific NFP.
/// @param tokenId The identifier of the NFP.
/// @return liquidity The liquidity of the position token.
function positionInfo(
uint256 tokenId
) external view returns (uint128 liquidity);
*/
/// @notice Returns the amount of rewards earned for an NFP.
/// @param token The address of the token for which to retrieve the earned rewards.
/// @param tokenId The identifier of the specific NFP for which to retrieve the earned rewards.
/// @return reward The amount of rewards earned for the specified NFP and tokens.
function earned(address token, uint256 tokenId) external view returns (uint256 reward);
/// @notice Returns the amount of rewards earned during a period for an NFP.
/// @param period The period for which to retrieve the earned rewards.
/// @param token The address of the token for which to retrieve the earned rewards.
/// @param tokenId The identifier of the specific NFP for which to retrieve the earned rewards.
/// @return reward The amount of rewards earned for the specified NFP and tokens.
function periodEarned(uint256 period, address token, uint256 tokenId) external view returns (uint256);
/// @notice Retrieves the earned rewards for a specific period, token, owner, index, tickLower, and tickUpper.
/// @param period The period for which to retrieve the earned rewards.
/// @param token The address of the token for which to retrieve the earned rewards.
/// @param owner The address of the owner for which to retrieve the earned rewards.
/// @param index The index for which to retrieve the earned rewards.
/// @param tickLower The tick lower bound for which to retrieve the earned rewards.
/// @param tickUpper The tick upper bound for which to retrieve the earned rewards.
/// @return The earned rewards for the specified period, token, owner, index, tickLower, and tickUpper.
function periodEarned(uint256 period, address token, address owner, uint256 index, int24 tickLower, int24 tickUpper)
external
view
returns (uint256);
/// @notice Retrieves the earned rewards for a specific period, token, owner, index, tickLower, and tickUpper.
/// @dev used by getReward() and saves gas by saving states
/// @param period The period for which to retrieve the earned rewards.
/// @param token The address of the token for which to retrieve the earned rewards.
/// @param owner The address of the owner for which to retrieve the earned rewards.
/// @param index The index for which to retrieve the earned rewards.
/// @param tickLower The tick lower bound for which to retrieve the earned rewards.
/// @param tickUpper The tick upper bound for which to retrieve the earned rewards.
/// @param caching Whether to cache the results or not.
/// @return The earned rewards for the specified period, token, owner, index, tickLower, and tickUpper.
function cachePeriodEarned(
uint256 period,
address token,
address owner,
uint256 index,
int24 tickLower,
int24 tickUpper,
bool caching
) external returns (uint256);
/// @notice Notifies the contract about the amount of rewards to be distributed for a specific token.
/// @param token The address of the token for which to notify the reward amount.
/// @param amount The amount of rewards to be distributed.
function notifyRewardAmount(address token, uint256 amount) external;
/// @notice Retrieves the reward amount for a specific period, NFP, and token addresses.
/// @param period The period for which to retrieve the reward amount.
/// @param tokens The addresses of the tokens for which to retrieve the reward amount.
/// @param tokenId The identifier of the specific NFP for which to retrieve the reward amount.
/// @param receiver The address of the receiver of the reward amount.
function getPeriodReward(uint256 period, address[] calldata tokens, uint256 tokenId, address receiver) external;
/// @notice Retrieves the reward amount for a specific NFP Manager, period, NFP, and token addresses.
/// @param __nfpManager The NFP Manager.
/// @param period The period for which to retrieve the reward amount.
/// @param tokens The addresses of the tokens for which to retrieve the reward amount.
/// @param tokenId The identifier of the specific NFP for which to retrieve the reward amount.
/// @param receiver The address of the receiver of the reward amount.
function getNfpPeriodReward(
address __nfpManager,
uint256 period,
address[] calldata tokens,
uint256 tokenId,
address receiver
) external;
/// @notice Retrieves the rewards for a specific period, set of tokens, owner, index, tickLower, tickUpper, and receiver.
/// @param period The period for which to retrieve the rewards.
/// @param tokens An array of token addresses for which to retrieve the rewards.
/// @param owner The address of the owner for which to retrieve the rewards.
/// @param index The index for which to retrieve the rewards.
/// @param tickLower The tick lower bound for which to retrieve the rewards.
/// @param tickUpper The tick upper bound for which to retrieve the rewards.
/// @param receiver The address of the receiver of the rewards.
function getPeriodReward(
uint256 period,
address[] calldata tokens,
address owner,
uint256 index,
int24 tickLower,
int24 tickUpper,
address receiver
) external;
/// @notice retrieves rewards based on an NFP id and an array of tokens
function getReward(uint256 tokenId, address[] memory tokens) external;
/// @notice retrieves rewards based on an array of NFP ids and an array of tokens
function getReward(uint256[] calldata tokenIds, address[] memory tokens) external;
/// @notice get reward for an owner of an NFP
function getRewardForOwner(uint256 tokenId, address[] memory tokens) external;
/// @notice get xShadow reward for an owner of an NFP
function getXShadowRewardForOwner(uint256 tokenId) external;
/// @notice Notifies rewards for periods greater than current period
/// @dev does not push fees
/// @dev requires reward token to be whitelisted
function notifyRewardAmountForPeriod(address token, uint256 amount, uint256 period) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {IShadowV3Pool} from "../../core/interfaces/IShadowV3Pool.sol";
interface IFeeCollector {
/// @notice Emitted when the treasury address is changed.
/// @param oldTreasury The previous treasury address.
/// @param newTreasury The new treasury address.
event TreasuryChanged(address oldTreasury, address newTreasury);
/// @notice Emitted when the treasury fees value is changed.
/// @param oldTreasuryFees The previous value of the treasury fees.
/// @param newTreasuryFees The new value of the treasury fees.
event TreasuryFeesChanged(uint256 oldTreasuryFees, uint256 newTreasuryFees);
/// @notice Emitted when protocol fees are collected from a pool and distributed to the fee distributor and treasury.
/// @param pool The address of the pool from which the fees were collected.
/// @param feeDistAmount0 The amount of fee tokens (token 0) distributed to the fee distributor.
/// @param feeDistAmount1 The amount of fee tokens (token 1) distributed to the fee distributor.
/// @param treasuryAmount0 The amount of fee tokens (token 0) allocated to the treasury.
/// @param treasuryAmount1 The amount of fee tokens (token 1) allocated to the treasury.
event FeesCollected(
address pool, uint256 feeDistAmount0, uint256 feeDistAmount1, uint256 treasuryAmount0, uint256 treasuryAmount1
);
/// @notice Returns the treasury address.
function treasury() external returns (address);
/// @notice Returns the treasury fees ratio.
function treasuryFees() external returns (uint256);
/// @notice Sets the treasury address to a new value.
/// @param newTreasury The new address to set as the treasury.
function setTreasury(address newTreasury) external;
/// @notice Sets the value of treasury fees to a new amount.
/// @param _treasuryFees The new amount of treasury fees to be set.
function setTreasuryFees(uint256 _treasuryFees) external;
/// @notice Collects protocol fees from a specified pool and distributes them to the fee distributor and treasury.
/// @param pool The pool from which to collect the protocol fees.
function collectProtocolFees(address pool) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import {IPoolInitializer} from './IPoolInitializer.sol';
import {IPeripheryPayments} from './IPeripheryPayments.sol';
import {IPeripheryImmutableState} from './IPeripheryImmutableState.sol';
import {PoolAddress} from '../libraries/PoolAddress.sol';
import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import {IERC721Metadata} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import {IERC721Enumerable} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
import {IPeripheryErrors} from './IPeripheryErrors.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPeripheryErrors,
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
/// @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 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, uint256 amount0, uint256 amount1);
/// @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 token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return tickSpacing The tickSpacing the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(
uint256 tokenId
)
external
view
returns (
address token0,
address token1,
int24 tickSpacing,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
int24 tickSpacing;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(
MintParams calldata params
) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(
IncreaseLiquidityParams calldata params
) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(
DecreaseLiquidityParams calldata params
) external payable returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
/// @notice Claims gauge rewards from liquidity incentives for a specific tokenId
/// @param tokenId The ID of the token to claim rewards from
/// @param tokens an array of reward tokens to claim
function getReward(uint256 tokenId, address[] calldata tokens) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface IPairFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
event SetFee(uint256 indexed fee);
event SetPairFee(address indexed pair, uint256 indexed fee);
event SetFeeSplit(uint256 indexed _feeSplit);
event SetPairFeeSplit(address indexed pair, uint256 indexed _feeSplit);
event SkimStatus(address indexed _pair, bool indexed _status);
event NewTreasury(address indexed _caller, address indexed _newTreasury);
event FeeSplitWhenNoGauge(address indexed _caller, bool indexed _status);
event SetFeeRecipient(address indexed pair, address indexed feeRecipient);
/// @notice returns the total length of legacy pairs
/// @return _length the length
function allPairsLength() external view returns (uint256 _length);
/// @notice calculates if the address is a legacy pair
/// @param pair the address to check
/// @return _boolean the bool return
function isPair(address pair) external view returns (bool _boolean);
/// @notice calculates the pairCodeHash
/// @return _hash the pair code hash
function pairCodeHash() external view returns (bytes32 _hash);
/// @param tokenA address of tokenA
/// @param tokenB address of tokenB
/// @param stable whether it uses the stable curve
/// @return _pair the address of the pair
function getPair(address tokenA, address tokenB, bool stable) external view returns (address _pair);
/// @notice creates a new legacy pair
/// @param tokenA address of tokenA
/// @param tokenB address of tokenB
/// @param stable whether it uses the stable curve
/// @return pair the address of the created pair
function createPair(address tokenA, address tokenB, bool stable) external returns (address pair);
/// @notice the address of the voter
/// @return _voter the address of the voter
function voter() external view returns (address _voter);
/// @notice returns the address of a pair based on the index
/// @param _index the index to check for a pair
/// @return _pair the address of the pair at the index
function allPairs(uint256 _index) external view returns (address _pair);
/// @notice the swap fee of a pair
/// @param _pair the address of the pair
/// @return _fee the fee
function pairFee(address _pair) external view returns (uint256 _fee);
/// @notice the split of fees
/// @return _split the feeSplit
function feeSplit() external view returns (uint256 _split);
/// @notice sets the swap fee for a pair
/// @param _pair the address of the pair
/// @param _fee the fee for the pair
function setPairFee(address _pair, uint256 _fee) external;
/// @notice set the swap fees of the pair
/// @param _fee the fee, scaled to MAX 500_000 = 50%
function setFee(uint256 _fee) external;
/// @notice the address for the treasury
/// @return _treasury address of the treasury
function treasury() external view returns (address _treasury);
/// @notice sets the pairFees contract
/// @param _pair the address of the pair
/// @param _pairFees the address of the new Pair Fees
function setFeeRecipient(address _pair, address _pairFees) external;
/// @notice sets the feeSplit for a pair
/// @param _pair the address of the pair
/// @param _feeSplit the feeSplit
function setPairFeeSplit(address _pair, uint256 _feeSplit) external;
/// @notice whether there is feeSplit when there's no gauge
/// @return _boolean whether there is a feesplit when no gauge
function feeSplitWhenNoGauge() external view returns (bool _boolean);
/// @notice whether a pair can be skimmed
/// @param _pair the pair address
/// @return _boolean whether skim is enabled
function skimEnabled(address _pair) external view returns (bool _boolean);
/// @notice set whether skim is enabled for a specific pair
function setSkimEnabled(address _pair, bool _status) external;
/// @notice sets a new treasury address
/// @param _treasury the new treasury address
function setTreasury(address _treasury) external;
/// @notice set whether there should be a feesplit without gauges
/// @param status whether enabled or not
function setFeeSplitWhenNoGauge(bool status) external;
/// @notice sets the feesSplit globally
/// @param _feeSplit the fee split
function setFeeSplit(uint256 _feeSplit) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface IFeeRecipientFactory {
/// @notice the pair fees for a specific pair
/// @param pair the pair to check
/// @return feeRecipient the feeRecipient contract address for the pair
function feeRecipientForPair(address pair) external view returns (address feeRecipient);
/// @notice the last feeRecipient address created
/// @return _feeRecipient the address of the last pair fees contract
function lastFeeRecipient() external view returns (address _feeRecipient);
/// @notice create the pair fees for a pair
/// @param pair the address of the pair
/// @return _feeRecipient the address of the newly created feeRecipient
function createFeeRecipient(address pair) external returns (address _feeRecipient);
/// @notice the fee % going to the treasury
/// @return _feeToTreasury the fee %
function feeToTreasury() external view returns (uint256 _feeToTreasury);
/// @notice get the treasury address
/// @return _treasury address of the treasury
function treasury() external view returns (address _treasury);
/// @notice set the fee % to be sent to the treasury
/// @param _feeToTreasury the fee % to be sent to the treasury
function setFeeToTreasury(uint256 _feeToTreasury) external;
/// @notice set a new treasury address
/// @param _treasury the new address
function setTreasury(address _treasury) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
pragma abicoder v2;
interface IVoter {
event GaugeCreated(address indexed gauge, address creator, address feeDistributor, address indexed pool);
event GaugeKilled(address indexed gauge);
event GaugeRevived(address indexed gauge);
event Voted(address indexed owner, uint256 weight, address indexed pool);
event Abstained(address indexed owner, uint256 weight);
event Deposit(address indexed lp, address indexed gauge, address indexed owner, uint256 amount);
event Withdraw(address indexed lp, address indexed gauge, address indexed owner, uint256 amount);
event NotifyReward(address indexed sender, address indexed reward, uint256 amount);
event DistributeReward(address indexed sender, address indexed gauge, uint256 amount);
event EmissionsRatio(address indexed caller, uint256 oldRatio, uint256 newRatio);
event NewGovernor(address indexed sender, address indexed governor);
event Whitelisted(address indexed whitelister, address indexed token);
event WhitelistRevoked(address indexed forbidder, address indexed token, bool status);
event MainTickSpacingChanged(address indexed token0, address indexed token1, int24 indexed newMainTickSpacing);
event Poke(address indexed user);
event EmissionsRedirected(address indexed sourceGauge, address indexed destinationGauge);
struct InitializationParams {
address shadow;
address legacyFactory;
address gauges;
address feeDistributorFactory;
address minter;
address msig;
address xShadow;
address clFactory;
address clGaugeFactory;
address nfpManager;
address feeRecipientFactory;
address voteModule;
address launcherPlugin;
address poolUpdater;
}
function initialize(InitializationParams memory inputs) external;
/// @notice denominator basis
function BASIS() external view returns (uint256);
/// @notice ratio of xShadow emissions globally
function xRatio() external view returns (uint256);
/// @notice xShadow contract address
function xShadow() external view returns (address);
/// @notice legacy factory address (uni-v2/stableswap)
function legacyFactory() external view returns (address);
/// @notice concentrated liquidity factory
function clFactory() external view returns (address);
/// @notice gauge factory for CL
function clGaugeFactory() external view returns (address);
/// @notice pool updater for CL
function poolUpdater() external view returns (address);
/// @notice legacy fee recipient factory
function feeRecipientFactory() external view returns (address);
/// @notice peripheral NFPManager contract
function nfpManager() external view returns (address);
/// @notice returns the address of the current governor
/// @return _governor address of the governor
function governor() external view returns (address _governor);
/// @notice the address of the vote module
/// @return _voteModule the vote module contract address
function voteModule() external view returns (address _voteModule);
/// @notice address of the central access Hub
function accessHub() external view returns (address);
/// @notice the address of the shadow launcher plugin to enable third party launchers
/// @return _launcherPlugin the address of the plugin
function launcherPlugin() external view returns (address _launcherPlugin);
/// @notice distributes emissions from the minter to the voter
/// @param amount the amount of tokens to notify
function notifyRewardAmount(uint256 amount) external;
/// @notice distributes the emissions for a specific gauge
/// @param _gauge the gauge address
function distribute(address _gauge) external;
/// @notice returns the address of the gauge factory
/// @param _gaugeFactory gauge factory address
function gaugeFactory() external view returns (address _gaugeFactory);
/// @notice returns the address of the feeDistributor factory
/// @return _feeDistributorFactory feeDist factory address
function feeDistributorFactory() external view returns (address _feeDistributorFactory);
/// @notice returns the address of the minter contract
/// @return _minter address of the minter
function minter() external view returns (address _minter);
/// @notice check if the gauge is active for governance use
/// @param _gauge address of the gauge
/// @return _trueOrFalse if the gauge is alive
function isAlive(address _gauge) external view returns (bool _trueOrFalse);
/// @notice allows the token to be paired with other whitelisted assets to participate in governance
/// @param _token the address of the token
function whitelist(address _token) external;
/// @notice effectively disqualifies a token from governance
/// @param _token the address of the token
function revokeWhitelist(address _token) external;
/// @notice returns if the address is a gauge
/// @param gauge address of the gauge
/// @return _trueOrFalse boolean if the address is a gauge
function isGauge(address gauge) external view returns (bool _trueOrFalse);
/// @notice disable a gauge from governance
/// @param _gauge address of the gauge
function killGauge(address _gauge) external;
/// @notice re-activate a dead gauge
/// @param _gauge address of the gauge
function reviveGauge(address _gauge) external;
/// @notice re-cast a tokenID's votes
/// @param owner address of the owner
function poke(address owner) external;
/// @notice sets the main destinationGauge of a token pairing
/// @param tokenA address of tokenA
/// @param tokenB address of tokenB
/// @param destinationGauge the main gauge to set to
function redirectEmissions(address tokenA, address tokenB, address destinationGauge) external;
/// @notice returns if the address is a fee distributor
/// @param _feeDistributor address of the feeDist
/// @return _trueOrFalse if the address is a fee distributor
function isFeeDistributor(address _feeDistributor) external view returns (bool _trueOrFalse);
/// @notice returns the address of the emission's token
/// @return _shadow emissions token contract address
function shadow() external view returns (address _shadow);
/// @notice returns the address of the pool's gauge, if any
/// @param _pool pool address
/// @return _gauge gauge address
function gaugeForPool(address _pool) external view returns (address _gauge);
/// @notice returns the address of the pool's feeDistributor, if any
/// @param _gauge address of the gauge
/// @return _feeDistributor address of the pool's feedist
function feeDistributorForGauge(address _gauge) external view returns (address _feeDistributor);
/// @notice returns the gauge address of a CL pool
/// @param tokenA address of token A in the pair
/// @param tokenB address of token B in the pair
/// @param tickSpacing tickspacing of the pool
/// @return gauge address of the gauge
function gaugeForClPool(address tokenA, address tokenB, int24 tickSpacing) external view returns (address gauge);
/// @notice returns the array of all tickspacings for the tokenA/tokenB combination
/// @param tokenA address of token A in the pair
/// @param tokenB address of token B in the pair
/// @return _ts array of all the tickspacings
function tickSpacingsForPair(address tokenA, address tokenB) external view returns (int24[] memory _ts);
/// @notice returns the destination of a gauge redirect
/// @param gauge address of gauge
function gaugeRedirect(address gauge) external view returns (address);
/// @notice returns the block.timestamp divided by 1 week in seconds
/// @return period the period used for gauges
function getPeriod() external view returns (uint256 period);
/// @notice cast a vote to direct emissions to gauges and earn incentives
/// @param owner address of the owner
/// @param _pools the list of pools to vote on
/// @param _weights an arbitrary weight per pool which will be normalized to 100% regardless of numerical inputs
function vote(address owner, address[] calldata _pools, uint256[] calldata _weights) external;
/// @notice reset the vote of an address
/// @param owner address of the owner
function reset(address owner) external;
/// @notice set the governor address
/// @param _governor the new governor address
function setGovernor(address _governor) external;
/// @notice recover stuck emissions
/// @param _gauge the gauge address
/// @param _period the period
function stuckEmissionsRecovery(address _gauge, uint256 _period) external;
/// @notice creates a legacy gauge for the pool
/// @param _pool pool's address
/// @return _gauge address of the new gauge
function createGauge(address _pool) external returns (address _gauge);
/// @notice create a concentrated liquidity gauge
/// @param tokenA the address of tokenA
/// @param tokenB the address of tokenB
/// @param tickSpacing the tickspacing of the pool
/// @return _clGauge address of the new gauge
function createCLGauge(address tokenA, address tokenB, int24 tickSpacing) external returns (address _clGauge);
/// @notice claim concentrated liquidity gauge rewards for specific NFP token ids
/// @param _gauges array of gauges
/// @param _tokens two dimensional array for the tokens to claim
/// @param _nfpTokenIds two dimensional array for the NFPs
function claimClGaugeRewards(
address[] calldata _gauges,
address[][] calldata _tokens,
uint256[][] calldata _nfpTokenIds
) external;
/// @notice claim arbitrary rewards from specific feeDists
/// @param owner address of the owner
/// @param _feeDistributors address of the feeDists
/// @param _tokens two dimensional array for the tokens to claim
function claimIncentives(address owner, address[] calldata _feeDistributors, address[][] calldata _tokens)
external;
/// @notice claim arbitrary rewards from specific feeDists and break up legacy pairs
/// @param owner address of the owner
/// @param _feeDistributors address of the feeDists
/// @param _tokens two dimensional array for the tokens to claim
function claimLegacyIncentives(address owner, address[] calldata _feeDistributors, address[][] calldata _tokens)
external;
/// @notice claim arbitrary rewards from specific gauges
/// @param _gauges address of the gauges
/// @param _tokens two dimensional array for the tokens to claim
function claimRewards(address[] calldata _gauges, address[][] calldata _tokens) external;
/// @notice claim arbitrary rewards from specific legacy gauges, and exit to shadow
/// @param _gauges address of the gauges
/// @param _tokens two dimensional array for the tokens to claim
function claimLegacyRewardsAndExit(address[] calldata _gauges, address[][] calldata _tokens) external;
/// @notice claim arbitrary rewards from specific cl gauges, and exit to shadow
/// @param _gauges address of the gauges
/// @param _tokens two dimensional array for the tokens to claim
/// @param _nfpTokenIds two dimensional array for the nfp to claim
function claimClGaugeRewardsAndExit(
address[] memory _gauges,
address[][] memory _tokens,
uint256[][] memory _nfpTokenIds
) external;
/// @notice distribute emissions to a gauge for a specific period
/// @param _gauge address of the gauge
/// @param _period value of the period
function distributeForPeriod(address _gauge, uint256 _period) external;
/// @notice attempt distribution of emissions to all gauges
function distributeAll() external;
/// @notice distribute emissions to gauges by index
/// @param startIndex start of the loop
/// @param endIndex end of the loop
function batchDistributeByIndex(uint256 startIndex, uint256 endIndex) external;
/// @notice lets governance update lastDistro period for a gauge
/// @dev should only be used if distribute() is running out of gas
/// @dev gaugePeriodDistributed will stop double claiming
/// @param _gauge gauge to update
/// @param _period period to update to
function updateLastDistro(address _gauge, uint256 _period) external;
/// @notice returns the votes cast for a tokenID
/// @param owner address of the owner
/// @return votes an array of votes casted
/// @return weights an array of the weights casted per pool
function getVotes(address owner, uint256 period)
external
view
returns (address[] memory votes, uint256[] memory weights);
/// @notice returns an array of all the pools
/// @return _pools the array of pools
function getAllPools() external view returns (address[] memory _pools);
/// @notice returns the length of pools
function getPoolsLength() external view returns (uint256);
/// @notice returns the pool at index
function getPool(uint256 index) external view returns (address);
/// @notice returns an array of all the gauges
/// @return _gauges the array of gauges
function getAllGauges() external view returns (address[] memory _gauges);
/// @notice returns the length of gauges
function getGaugesLength() external view returns (uint256);
/// @notice returns the gauge at index
function getGauge(uint256 index) external view returns (address);
/// @notice returns an array of all the feeDists
/// @return _feeDistributors the array of feeDists
function getAllFeeDistributors() external view returns (address[] memory _feeDistributors);
/// @notice sets the xShadowRatio default
function setGlobalRatio(uint256 _xRatio) external;
/// @notice whether the token is whitelisted in governance
function isWhitelisted(address _token) external view returns (bool _tf);
/// @notice function for removing malicious or stuffed tokens
function removeFeeDistributorReward(address _feeDist, address _token) external;
/// @notice returns the total votes for a pool in a specific period
/// @param pool the pool address to check
/// @param period the period to check
/// @return votes the total votes for the pool in that period
function poolTotalVotesPerPeriod(address pool, uint256 period) external view returns (uint256 votes);
/// @notice returns the pool address for a given gauge
/// @param gauge address of the gauge
/// @return pool address of the pool
function poolForGauge(address gauge) external view returns (address pool);
/// @notice returns the pool address for a given feeDistributor
/// @param feeDistributor address of the feeDistributor
/// @return pool address of the pool
function poolForFeeDistributor(address feeDistributor) external view returns (address pool);
/// @notice returns the voting power used by a voter for a period
/// @param user address of the user
/// @param period the period to check
function userVotingPowerPerPeriod(address user, uint256 period) external view returns (uint256 votingPower);
/// @notice returns the total votes for a specific period
/// @param period the period to check
/// @return weight the total votes for that period
function totalVotesPerPeriod(uint256 period) external view returns (uint256 weight);
/// @notice returns the total rewards allocated for a specific period
/// @param period the period to check
/// @return amount the total rewards for that period
function totalRewardPerPeriod(uint256 period) external view returns (uint256 amount);
/// @notice returns the last distribution period for a gauge
/// @param _gauge address of the gauge
/// @return period the last period distributions occurred
function lastDistro(address _gauge) external view returns (uint256 period);
/// @notice returns if the gauge is a Cl gauge
/// @param gauge the gauge to check
function isClGauge(address gauge) external view returns (bool);
/// @notice returns if the gauge is a legacy gauge
/// @param gauge the gauge to check
function isLegacyGauge(address gauge) external view returns (bool);
/// @notice sets a new NFP manager
function setNfpManager(address _nfpManager) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface IMinter {
event SetVeDist(address _value);
event SetVoter(address _value);
event Mint(address indexed sender, uint256 weekly);
event RebaseUnsuccessful(uint256 _current, uint256 _currentPeriod);
event EmissionsMultiplierUpdated(uint256 _emissionsMultiplier);
/// @notice decay or inflation scaled to 1_000_000 = 100%
/// @return _multiplier the emissions multiplier
function emissionsMultiplier() external view returns (uint256 _multiplier);
/// @notice unix timestamp of current epoch's start
/// @return _activePeriod the active period
function activePeriod() external view returns (uint256 _activePeriod);
/// @notice update the epoch (period) -- callable once a week at >= Thursday 0 UTC
/// @return period the new period
function updatePeriod() external returns (uint256 period);
/// @notice start emissions for epoch 0
function startEmissions() external;
/// @notice updates the decay or inflation scaled to 1_000_000 = 100%
/// @param _emissionsMultiplier multiplier for emissions each week
function updateEmissionsMultiplier(uint256 _emissionsMultiplier) external;
/// @notice calculates the emissions to be sent to the voter
/// @return _weeklyEmissions the amount of emissions for the week
function calculateWeeklyEmissions() external view returns (uint256 _weeklyEmissions);
/// @notice kicks off the initial minting and variable declarations
function kickoff(
address _shadow,
address _voter,
uint256 _initialWeeklyEmissions,
uint256 _initialMultiplier,
address _xShadow
) external;
/// @notice returns (block.timestamp / 1 week) for gauge use
/// @return period period number
function getPeriod() external view returns (uint256 period);
/// @notice returns the numerical value of the current epoch
/// @return _epoch epoch number
function getEpoch() external view returns (uint256 _epoch);
/// @notice emissions value
function weeklyEmissions() external view returns (uint256);
/// @notice unix timestamp of the first period
function firstPeriod() external view returns (uint256);
/// @notice the last period the emissions multiplier was updated
function lastMultiplierUpdate() external view returns (uint256);
/// @notice current operator
function operator() external view returns (address);
/// @notice the access control center
function accessHub() external view returns (address);
/// @notice xShadow contract address
function xShadow() external view returns (address);
/// @notice central voter contract
function voter() external view returns (address);
/// @notice the IERC20 version of shadow
function shadow() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {IMinter} from "./IMinter.sol";
interface IMarbleMinter is IMinter {
/// @notice migrate gauges for Marble Zone Migration
function migration(address[] calldata gauges) external;
/// @notice sets up fee redirection for new legacy gauges
function postCreateLegacyGaugeHook(address pool) external;
/// @notice redirects legacy pair fees to new feeRecipients
function redirectFees(uint256 start, uint256 batchSize) external;
/// @notice allows governance to rescue tokens (pair fees without gauges)
function rescueTokens(address token, uint256 amount) external;
/// @notice allows governance to change Access Hub
function setAccessHub(address _accessHub) external;
/// @notice allows governance to change Operator
function setOperator(address _operator) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface IVoteModule {
/**
* Events
*/
event Deposit(address indexed from, uint256 amount);
event Withdraw(address indexed from, uint256 amount);
event NotifyReward(address indexed from, uint256 amount);
event ClaimRewards(address indexed from, uint256 amount);
event ExemptedFromCooldown(address indexed candidate, bool status);
event NewDuration(uint256 oldDuration, uint256 newDuration);
event NewCooldown(uint256 oldCooldown, uint256 newCooldown);
event Delegate(address indexed delegator, address indexed delegatee, bool indexed isAdded);
event SetAdmin(address indexed owner, address indexed operator, bool indexed isAdded);
/**
* Functions
*/
function delegates(address) external view returns (address);
/// @notice mapping for admins for a specific address
/// @param owner the owner to check against
/// @return operator the address that is designated as an admin/operator
function admins(address owner) external view returns (address operator);
function accessHub() external view returns (address);
/// @notice reward supply for a period
function rewardSupply(uint256 period) external view returns (uint256);
/// @notice user claimed reward amount for a period
/// @dev same mapping order as FeeDistributor so the name is a bit odd
function userClaimed(uint256 period, address owner) external view returns (uint256);
/// @notice last claimed period for a user
function userLastClaimPeriod(address owner) external view returns (uint256);
/// @notice returns the current period
function getPeriod() external view returns (uint256);
/// @notice returns the amount of unclaimed rebase earned by the user
function earned(address account) external view returns (uint256 _reward);
/// @notice returns the amount of unclaimed rebase earned by the user for a period
function periodEarned(uint256 period, address user) external view returns (uint256 amount);
/// @notice the time which users can deposit and withdraw
function unlockTime() external view returns (uint256 _timestamp);
/// @notice claims pending rebase rewards
function getReward() external;
/// @notice claims pending rebase rewards for a period
function getPeriodReward(uint256 period) external;
/// @notice allows users to set their own last claimed period in case they haven't claimed in a while
/// @param period the new period to start loops from
function setUserLastClaimPeriod(uint256 period) external;
/// @notice deposits all xShadow in the caller's wallet
function depositAll() external;
/// @notice deposit a specified amount of xShadow
function deposit(uint256 amount) external;
/// @notice withdraw all xShadow
function withdrawAll() external;
/// @notice withdraw a specified amount of xShadow
function withdraw(uint256 amount) external;
/// @notice check for admin perms
/// @param operator the address to check
/// @param owner the owner to check against for permissions
function isAdminFor(address operator, address owner) external view returns (bool approved);
/// @notice check for delegations
/// @param delegate the address to check
/// @param owner the owner to check against for permissions
function isDelegateFor(address delegate, address owner) external view returns (bool approved);
/// @notice used by the xShadow contract to notify pending rebases
/// @param amount the amount of Shadow to be notified from exit penalties
function notifyRewardAmount(uint256 amount) external;
/// @notice the address of the xShadow token (staking/voting token)
/// @return _xShadow the address
function xShadow() external view returns (address _xShadow);
/// @notice address of the voter contract
/// @return _voter the voter contract address
function voter() external view returns (address _voter);
/// @notice returns the total voting power (equal to total supply in the VoteModule)
/// @return _totalSupply the total voting power
function totalSupply() external view returns (uint256 _totalSupply);
/// @notice voting power
/// @param user the address to check
/// @return amount the staked balance
function balanceOf(address user) external view returns (uint256 amount);
/// @notice delegate voting perms to another address
/// @param delegatee who you delegate to
/// @dev set address(0) to revoke
function delegate(address delegatee) external;
/// @notice give admin permissions to a another address
/// @param operator the address to give administrative perms to
/// @dev set address(0) to revoke
function setAdmin(address operator) external;
function cooldownExempt(address) external view returns (bool);
function setCooldownExemption(address, bool) external;
/// @notice lock period after rebase starts accruing
function cooldown() external returns (uint256);
function setNewCooldown(uint256) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import {IVoter} from "../interfaces/IVoter.sol";
import {IVoteModule} from "../interfaces/IVoteModule.sol";
interface IFeeDistributor {
event Deposit(address owner, uint256 amount);
event Withdraw(address owner, uint256 amount);
event NotifyReward(address indexed from, address indexed reward, uint256 amount, uint256 period);
event VotesIncentivized(address indexed from, address indexed reward, uint256 amount, uint256 period);
event ClaimRewards(uint256 period, address owner, address receiver, address reward, uint256 amount);
event RewardsRedirected(address indexed destination, address indexed _reward, uint256 _amount);
event RewardsRemoved(address _reward);
/// @notice the address of the voter contract
function voter() external view returns (IVoter);
/// @notice the address of the voting module
function voteModule() external view returns (IVoteModule);
/// @notice the address of the feeRecipient contract
function feeRecipient() external view returns (address);
/// @notice the first period (epoch) that this contract was deployed
function firstPeriod() external view returns (uint256);
/// @notice balance of the voting power for a user
/// @param owner the owner
/// @return amount the amount of voting share
function balanceOf(address owner) external view returns (uint256 amount);
/// @notice total cumulative amount of voting power per epoch
/// @param period the period to check
/// @return weight the amount of total voting power
function votes(uint256 period) external view returns (uint256 weight);
/// @notice "internal" function gated to voter to add votes
/// @dev internal notation inherited from original solidly, kept for continuity
function _deposit(uint256 amount, address owner) external;
/// @notice "internal" function gated to voter to remove votes
/// @dev internal notation inherited from original solidly, kept for continuity
function _withdraw(uint256 amount, address owner) external;
/// @notice function to claim rewards on behalf of another
/// @param owner owner's address
/// @param tokens an array of the tokens
function getRewardForOwner(address owner, address[] memory tokens) external;
/// @notice function to claim rewards on behalf of another
/// @param owner owner's address
/// @param tokens an array of the tokens
/// @param destination destination of the rewards
function getRewardForOwnerTo(address owner, address[] memory tokens, address destination) external;
/// @notice function for sending fees directly to be claimable (in system where fees are distro'd through the week)
/// @dev for lumpsum - this would operate similarly to incentivize
/// @param token the address of the token to send for notifying
/// @param amount the amount of token to send
function notifyRewardAmount(address token, uint256 amount) external;
/// @notice gives an array of reward tokens for the feedist
/// @return _rewards array of rewards
function getRewardTokens() external view returns (address[] memory _rewards);
/// @notice shows the earned incentives in the feedist
/// @param token the token address to check
/// @param owner owner's address
/// @return reward the amount earned/claimable
function earned(address token, address owner) external view returns (uint256 reward);
/// @notice function to submit incentives to voters for the upcoming flip
/// @param token the address of the token to send for incentivization
/// @param amount the amount of token to send
function incentivize(address token, uint256 amount) external;
/// @notice get the rewards for a specific period
/// @param owner owner's address
function getPeriodReward(uint256 period, address owner, address token) external;
/// @notice get the fees and incentives
function getReward(address owner, address[] memory tokens) external;
/// @notice remove a reward from the set
function removeReward(address _token) external;
/// @notice claws back rewards
function clawbackRewards(address token, address destination) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/extensions/IAccessControlEnumerable.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "../IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC-165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IShadowV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IShadowV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @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 Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IShadowV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// @return observationIndex The index of the last oracle observation that was written,
/// @return observationCardinality The current maximum number of observations stored in the pool,
/// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// @return feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint24 feeProtocol,
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 feeGrowthGlobal0X128() 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 feeGrowthGlobal1X128() external view returns (uint256);
/// @notice Get the accumulated fee growth for the first token in the pool before protocol fees
/// @dev This value can overflow the uint256
function grossFeeGrowthGlobal0X128() external view returns (uint256);
/// @notice Get the accumulated fee growth for the second token in the pool before protocol fees
/// @dev This value can overflow the uint256
function grossFeeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
/// @return The liquidity at the current price of the pool
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper
/// @return liquidityNet how much liquidity changes when the pool price crosses the tick,
/// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// @return secondsOutside the seconds spent on the other side of the tick from the current tick,
/// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// 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 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return liquidity The amount of liquidity in the position,
/// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(
bytes32 key
)
external
view
returns (
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// @return initialized whether the observation has been initialized and the values are safe to use
function observations(
uint256 index
)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
/// @notice get the period seconds in range of a specific position
/// @param period the period number
/// @param owner owner address
/// @param index position index
/// @param tickLower lower bound of range
/// @param tickUpper upper bound of range
/// @return periodSecondsInsideX96 seconds the position was not in range for the period
function positionPeriodSecondsInRange(
uint256 period,
address owner,
uint256 index,
int24 tickLower,
int24 tickUpper
) external view returns (uint256 periodSecondsInsideX96);
}
// 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.
interface IShadowV3PoolDerivedState {
/// @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 secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(
uint32[] calldata secondsAgos
) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @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 tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(
int24 tickLower,
int24 tickUpper
) external view returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IShadowV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param index The index for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The 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
function mint(
address recipient,
uint256 index,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @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 index The index of the position to be collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper 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,
uint256 index,
int24 tickLower,
int24 tickUpper,
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 index The index for which the liquidity will be burned
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper 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(
uint256 index,
int24 tickLower,
int24 tickUpper,
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 IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne 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 sqrtPriceLimitX96 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
/// @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 zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
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 IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata 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;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// 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
interface IShadowV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
function setFeeProtocol() external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
function setFee(uint24 _fee) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Errors emitted by a pool
/// @notice Contains all custom errors that can be emitted by the pool
interface IShadowV3PoolErrors {
/*//////////////////////////////////////////////////////////////
POOL ERRORS
//////////////////////////////////////////////////////////////*/
/// @notice Thrown when the pool is locked during a swap or mint/burn operation
error LOK(); // Locked
/// @notice Thrown when tick lower is greater than upper in position management
error TLU(); // Tick Lower > Upper
/// @notice Thrown when tick lower is less than minimum allowed
error TLM(); // Tick Lower < Min
/// @notice Thrown when tick upper is greater than maximum allowed
error TUM(); // Tick Upper > Max
/// @notice Thrown when the pool is already initialized
error AI(); // Already Initialized
/// @notice Thrown when the first margin value is zero
error M0(); // Mint token 0 error
/// @notice Thrown when the second margin value is zero
error M1(); // Mint token1 error
/// @notice Thrown when amount specified is invalid
error AS(); // Amount Specified Invalid
/// @notice Thrown when input amount is insufficient
error IIA(); // Insufficient Input Amount
/// @notice Thrown when pool lacks sufficient liquidity for operation
error L(); // Insufficient Liquidity
/// @notice Thrown when the first fee value is zero
error F0(); // Fee0 issue or Fee = 0
/// @notice Thrown when the second fee value is zero
error F1(); // Fee1 issue
/// @notice Thrown when square price limit is invalid
error SPL(); // Square Price Limit Invalid
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IShadowV3PoolEvents {
/// @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 sqrtPriceX96 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 sqrtPriceX96, 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 tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount 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 tickLower,
int24 indexed tickUpper,
uint128 amount,
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 tickLower The lower tick of the position
/// @param tickUpper 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 tickLower,
int24 indexed tickUpper,
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 tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount 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 tickLower,
int24 indexed tickUpper,
uint128 amount,
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 sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
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 by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// 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.
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 tickSpacing The tickSpacing of the v3 pool for the specified token pair
/// @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,
int24 tickSpacing,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @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.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 deployer
function deployer() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the deployer, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0x892f127ed4b26ca352056c8fb54585a3268f76f97fdd84d5836ef4bda8d8c685;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
int24 tickSpacing;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param tickSpacing The tickSpacing of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(address tokenA, address tokenB, int24 tickSpacing) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, tickSpacing: tickSpacing});
}
/// @notice Deterministically computes the pool address given the deployer and PoolKey
/// @param deployer The Uniswap V3 deployer contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address deployer, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1, "!TokenOrder");
pool = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
deployer,
keccak256(abi.encode(key.token0, key.token1, key.tickSpacing)),
POOL_INIT_CODE_HASH
)
)
)
)
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../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: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Errors emitted by the NonFungiblePositionManager
/// @notice Contains all events emitted by the NfpManager
interface IPeripheryErrors {
error InvalidTokenId(uint256 tokenId);
error CheckSlippage();
error NotCleared();
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* 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[ERC 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);
}