Warning! Contract bytecode has been changed and doesn't match the verified one. Therefore, interaction with this smart contract may be risky.
This contract has been partially verified via Sourcify.
View contract in Sourcify repository
- Contract name:
- Minter
- Optimization enabled
- true
- Compiler version
- v0.8.28+commit.7893614a
- Optimization runs
- 1000
- EVM Version
- paris
- Verified at
- 2026-06-06T09:17:55.471252Z
contracts/Minter.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.28;
import {UUPSUpgradeable} from '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import {Ownable2StepUpgradeable} from '@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol';
import {ReentrancyGuardUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {PeriodLibrary} from './libraries/PeriodLibrary.sol';
import {IMinter} from './interfaces/IMinter.sol';
import {IMintable} from './interfaces/IMintable.sol';
import {IVoter} from './interfaces/IVoter.sol';
import {IVotingEscrow} from './interfaces/IVotingEscrow.sol';
import {ISWITCH} from './interfaces/ISWITCH.sol';
contract Minter is IMinter, UUPSUpgradeable, Ownable2StepUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20 for IMintable;
uint256 public constant DURATION = PeriodLibrary.DURATION;
uint256 internal constant PRECISION = 10_000;
uint256 public constant MAX_TREASURY_RATE = 1000; // 10%
uint256 internal constant YEAR = 365 days;
IMintable public token;
IVoter public voter;
IVotingEscrow public veNFT;
address public treasury;
// Fixed-schedule emission state
uint256 public emissionStart; // timestamp
uint256 public emissionEnd; // timestamp
uint256 public lastUpdate; // timestamp
uint256 public baseRatePerSecond; // initial tokens per second before halvings
uint256 public totalBudget; // total emissions over schedule (includes treasury share)
uint256 public emitted; // cumulative emitted (treasury + voter)
uint256 public treasuryRate; // in PRECISION (1e4)
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(address __voter, address _veNFT, address _treasury, uint256 _totalBudget) external initializer {
__UUPSUpgradeable_init();
__Ownable2Step_init();
__Ownable_init(msg.sender);
__ReentrancyGuard_init();
treasuryRate = MAX_TREASURY_RATE; // 10%
if (__voter == address(0) || _veNFT == address(0) || _treasury == address(0)) revert ZeroAddress();
treasury = _treasury;
veNFT = IVotingEscrow(_veNFT);
token = IMintable(veNFT.token());
voter = IVoter(__voter);
_validateBudgetAgainstCap(_totalBudget);
totalBudget = _totalBudget;
// disable until start()
emissionStart = 0;
emissionEnd = 0;
lastUpdate = 0;
}
/* public functions */
function updatePeriod() external override nonReentrant returns (bool) {
if (emissionStart == 0) return false;
uint256 tNow = block.timestamp;
uint256 tEnd = emissionEnd;
uint256 tEffective = tNow < tEnd ? tNow : tEnd;
if (tEffective <= lastUpdate) return false;
uint256 budget = _emittableBetween(lastUpdate, tEffective);
if (tEffective == tEnd && emitted + budget < totalBudget) {
budget = totalBudget - emitted;
} else if (emitted + budget > totalBudget) {
budget = totalBudget - emitted;
}
if (budget == 0) {
lastUpdate = tEffective;
return false;
}
uint256 toTreasury = (budget * treasuryRate) / PRECISION;
uint256 toVoter = budget - toTreasury;
// Mint shortfall only
uint256 bal = token.balanceOf(address(this));
uint256 need = budget;
if (bal < need) {
token.mint(address(this), need - bal);
}
if (toTreasury > 0) token.safeTransfer(treasury, toTreasury);
if (toVoter > 0) {
token.forceApprove(address(voter), toVoter);
voter.notifyRewardAmount(toVoter);
token.forceApprove(address(voter), 0);
}
emitted += budget;
lastUpdate = tEffective;
emit Mint(msg.sender, toVoter, toTreasury, emitted);
return true;
}
function _emittableBetween(uint256 from, uint256 to) internal view returns (uint256 sum) {
if (to <= from) return 0;
uint256 start0 = emissionStart;
uint256 end0 = start0 + YEAR;
uint256 start1 = end0;
uint256 end1 = start1 + YEAR;
uint256 start2 = end1;
uint256 end2 = emissionEnd;
uint256 base = baseRatePerSecond;
if (to > start0 && from < end0) {
uint256 a0 = from > start0 ? from : start0;
uint256 b0 = to < end0 ? to : end0;
if (b0 > a0) sum += (b0 - a0) * base;
}
if (to > start1 && from < end1) {
uint256 a1 = from > start1 ? from : start1;
uint256 b1 = to < end1 ? to : end1;
if (b1 > a1) sum += ((b1 - a1) * base) / 2;
}
if (to > start2 && from < end2) {
uint256 a2 = from > start2 ? from : start2;
uint256 b2 = to < end2 ? to : end2;
if (b2 > a2) sum += ((b2 - a2) * base) / 4;
}
}
/// @notice Remaining tokens to emit
function getRemainingBudget() external view override returns (uint256) {
return totalBudget - emitted;
}
/// @notice Emission schedule summary and current phase index
function getEmissionSchedule() external view override returns (uint256 startTimestamp, uint256 endTimestamp, uint256 rate, uint256 currentPhase) {
startTimestamp = emissionStart;
endTimestamp = emissionEnd;
rate = baseRatePerSecond;
if (startTimestamp == 0) {
currentPhase = 0;
} else if (block.timestamp < startTimestamp + YEAR) {
currentPhase = 0;
} else if (block.timestamp < startTimestamp + 2 * YEAR) {
currentPhase = 1;
} else {
currentPhase = 2;
}
}
/// @notice Details of the current phase
function getEmissionPhaseInfo() external view override returns (uint256 phase, uint256 phaseStart, uint256 phaseEnd, uint256 phaseRate) {
uint256 _start = emissionStart;
if (_start == 0) {
return (0, 0, 0, 0);
}
if (block.timestamp < _start + YEAR) {
phase = 0;
phaseStart = _start;
phaseEnd = _start + YEAR;
phaseRate = baseRatePerSecond;
} else if (block.timestamp < _start + 2 * YEAR) {
phase = 1;
phaseStart = _start + YEAR;
phaseEnd = _start + 2 * YEAR;
phaseRate = baseRatePerSecond / 2;
} else {
phase = 2;
phaseStart = _start + 2 * YEAR;
phaseEnd = emissionEnd;
phaseRate = baseRatePerSecond / 4;
}
}
/* view functions */
function getCurrentPeriod() public view override returns (uint256) {
return block.timestamp / DURATION;
}
/* authorized functions */
function start() external override {
if (msg.sender != address(voter)) revert NotVoter();
if (emissionStart == 0) {
emissionStart = block.timestamp;
emissionEnd = emissionStart + 2 * YEAR + (YEAR / 2); // 2.5 years
lastUpdate = emissionStart;
baseRatePerSecond = (totalBudget * 8) / (13 * YEAR);
}
}
function setTreasury(address _treasury) external onlyOwner {
if (_treasury == address(0)) revert ZeroAddress();
treasury = _treasury;
}
function setTreasuryRate(uint256 _treasuryRate) external onlyOwner {
if (_treasuryRate > MAX_TREASURY_RATE) revert TreasuryRateTooHigh();
treasuryRate = _treasuryRate;
}
function _validateBudgetAgainstCap(uint256 _totalBudget) internal view {
if (_totalBudget == 0) return;
try ISWITCH(address(token)).cap() returns (uint256 cap_) {
if (cap_ == 0) return;
uint256 supply = token.totalSupply();
if (cap_ < supply) revert BudgetExceedsCap();
uint256 remaining = cap_ - supply;
if (_totalBudget > remaining) revert BudgetExceedsCap();
} catch {}
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
// --- Storage gap ---
uint256[50] private __gap;
}
/Voter.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {UUPSUpgradeable} from '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import {Ownable2StepUpgradeable} from '@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol';
import {AccessControlUpgradeable} from '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {ReentrancyGuardUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol';
import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import {VotingRewardFactory} from './reward/VotingRewardFactory.sol';
import {PeriodLibrary} from './libraries/PeriodLibrary.sol';
import {V4GaugeFactory} from './gauge/V4GaugeFactory.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IV4Pool} from '@switchx/v4-core/contracts/interfaces/IV4Pool.sol';
import {IV4CommunityVault} from '@switchx/v4-core/contracts/interfaces/vault/IV4CommunityVault.sol';
import {IV4VaultFactory} from '@switchx/v4-core/contracts/interfaces/vault/IV4VaultFactory.sol';
import {IV4Gauge} from './interfaces/IV4Gauge.sol';
import {IMinter} from './interfaces/IMinter.sol';
import {IVoter} from './interfaces/IVoter.sol';
import {IVotingEscrow} from './interfaces/IVotingEscrow.sol';
import {IVotingReward} from './interfaces/IVotingReward.sol';
import {IProtocolFeeManager} from './interfaces/IProtocolFeeManager.sol';
interface IV4VaultFactoryWithFactory {
function factory() external view returns (address);
}
contract Voter is IVoter, UUPSUpgradeable, Ownable2StepUpgradeable, AccessControlUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/* constants */
uint256 public constant DURATION = PeriodLibrary.DURATION;
uint256 public constant MAX_VOTE_POOLS = 32;
bytes32 public constant AUTHORIZED_ROLE = keccak256('AUTHORIZED_ROLE');
/* contracts */
IERC20 public token;
IVotingEscrow public veNFT;
IMinter public minter;
VotingRewardFactory public votingRewardFactory;
V4GaugeFactory public v4GaugeFactory;
IV4VaultFactory public v4VaultFactory;
/* gauge */
EnumerableSet.AddressSet internal poolList;
EnumerableSet.AddressSet internal gaugeList;
mapping(address _pool => Gauge) internal gauge;
mapping(address _gauge => address) public gaugeToPool;
/* voting: period => voting data */
uint256 public epoch0Period; // the period for epoch 0
mapping(uint256 _period => Period) public period;
EnumerableSet.AddressSet internal whitelistedTokenList;
/* fee configuration */
/// @notice Default community fee percentage enforced on pools (in thousandths, i.e. 1e-3, so 1000 = 100%)
uint16 public defaultCommunityFee;
/// @notice Default receiver for v4 fee share applied when Voter configures a pool vault
address public defaultV4FeeReceiver;
/// @notice Default v4 fee share applied when Voter configures a pool vault
uint16 public defaultV4Fee;
IProtocolFeeManager public protocolFeeManager;
/// @notice Allows current-period V4 fee forwarding even when SWITCH emissions are zero.
mapping(address _pool => bool) public v4FeeDistributionEnabled;
/// @notice Tracks V4 fee forwarding separately from emission forwarding.
mapping(uint256 _period => mapping(address _gauge => bool)) public v4FeesDistributed;
/* modifiers */
modifier onlyOwnerOrAuthorized() {
if (msg.sender != owner() && !hasRole(AUTHORIZED_ROLE, msg.sender)) revert Unauthorized();
_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(address _veNFT, address _initialOwner) public initializer {
__UUPSUpgradeable_init();
__Ownable2Step_init();
__Ownable_init(_initialOwner);
__AccessControl_init();
__ReentrancyGuard_init();
veNFT = IVotingEscrow(_veNFT);
token = IERC20(veNFT.token());
_grantRole(DEFAULT_ADMIN_ROLE, _initialOwner);
// Default to 75% of swap fees going to community vault
defaultCommunityFee = 750;
}
/* public functions */
/// @notice Deposit votes into the next period for a list of gauges
/// @dev Supports recasting: if the tokenId has already voted, previous votes are atomically reset before applying new ones
function vote(uint256 _tokenId, address[] memory _poolList, uint256[] memory weightList) external nonReentrant {
uint256 nextPeriod = getCurrentPeriod() + 1;
uint256 poolCount = _poolList.length;
if (veNFT.isApprovedOrOwner(msg.sender, _tokenId) == false) revert NotApprovedOrOwner();
if (poolCount != weightList.length || poolCount == 0 || poolCount > MAX_VOTE_POOLS) revert InvalidParameters();
_validatePoolList(_poolList);
// Atomically reset any previous votes before applying new ones
_resetVotes(nextPeriod, _tokenId);
period[nextPeriod].voted[_tokenId] = true;
_vote(nextPeriod, _tokenId, _poolList, weightList);
}
/// @notice Recast the same pool votes with current veNFT voting power
/// @dev Useful when veNFT balance has changed (decay, additional lock, merge)
function poke(uint256 _tokenId) external nonReentrant {
uint256 nextPeriod = getCurrentPeriod() + 1;
if (veNFT.isApprovedOrOwner(msg.sender, _tokenId) == false) revert NotApprovedOrOwner();
if (!_checkPeriodVoted(nextPeriod, _tokenId)) revert NotVotedInPeriod();
// Snapshot current pool votes and weights before resetting
address[] memory previousPools = period[nextPeriod].tokenIdVotedList[_tokenId].values();
uint256 poolCount = previousPools.length;
uint256[] memory previousWeights = new uint256[](poolCount);
for (uint256 i; i < poolCount; ++i) {
previousWeights[i] = period[nextPeriod].tokenIdVotes[gauge[previousPools[i]].gauge][_tokenId];
}
_resetVotes(nextPeriod, _tokenId);
_vote(nextPeriod, _tokenId, previousPools, previousWeights);
}
/// @notice Reset all votes for the next period, allowing the veNFT to be transferred
function reset(uint256 _tokenId) external nonReentrant {
uint256 nextPeriod = getCurrentPeriod() + 1;
if (veNFT.isApprovedOrOwner(msg.sender, _tokenId) == false) revert NotApprovedOrOwner();
if (!_checkPeriodVoted(nextPeriod, _tokenId)) revert NotVotedInPeriod();
_resetVotes(nextPeriod, _tokenId);
period[nextPeriod].voted[_tokenId] = false;
emit VotesReset(_tokenId, nextPeriod);
}
/// @notice Deposit token emissions
/// @dev Minter deposits accrue to current period with carry-forward of prior unclaimed.
/// Third parties can deposit incentives for the next period only.
function notifyRewardAmount(uint256 _amount) public {
uint256 currentPeriod = getCurrentPeriod();
token.safeTransferFrom(msg.sender, address(this), _amount);
if (msg.sender == address(minter)) {
// Defensive guard for epoch 0
if (currentPeriod > 0) {
uint256 unclaimedEmissions = period[currentPeriod - 1].totalEmissions - period[currentPeriod - 1].totalClaimedEmissions;
if (unclaimedEmissions > 0) {
period[currentPeriod].totalEmissions += unclaimedEmissions;
period[currentPeriod - 1].totalClaimedEmissions += unclaimedEmissions;
}
}
period[currentPeriod].totalEmissions += _amount;
} else {
// Third-party incentives are scheduled for the next period
period[currentPeriod + 1].totalEmissions += _amount;
}
}
/// @notice Collect fees and distribute token emissions for current period
function distributeAll() public {
minter.updatePeriod();
uint256 currentPeriod = getCurrentPeriod();
address[] memory _gaugeList = gaugeList.values();
uint256 gaugeCount = _gaugeList.length;
for (uint256 i; i < gaugeCount; ++i) {
_distribute(currentPeriod, _gaugeList[i]);
}
}
/// @notice Distribute for a defined range
function distributeRange(uint256 _start, uint256 _amount) public {
minter.updatePeriod();
uint256 currentPeriod = getCurrentPeriod();
address[] memory _gaugeList = gaugeList.values();
uint256 range = _start + _amount;
for (uint256 i = _start; i < range; ++i) {
_distribute(currentPeriod, _gaugeList[i]);
}
}
/// @notice Distribute for a gauge
function distribute(address _gauge) public {
minter.updatePeriod();
_distribute(getCurrentPeriod(), _gauge);
}
function claimVotingRewardBatch(address[] memory _votingRewardList, uint256 _tokenId) external {
if (veNFT.isApprovedOrOwner(msg.sender, _tokenId) == false) revert NotApprovedOrOwner();
uint256 votingRewardCount = _votingRewardList.length;
for (uint256 i; i < votingRewardCount; ++i) IVotingReward(_votingRewardList[i]).getRewardForOwner(_tokenId);
}
/* view functions */
function checkPeriodVoted(uint256 _period, uint256 _tokenId) public view returns (bool) {
return _checkPeriodVoted(_period, _tokenId);
}
function isWhitelisted(address _token) public view returns (bool) {
return whitelistedTokenList.contains(_token);
}
function isGauge(address _gauge) public view returns (bool) {
return gaugeList.contains(_gauge);
}
function isAlive(address _gauge) public view returns (bool) {
return gauge[gaugeToPool[_gauge]].isAlive;
}
function getCurrentPeriod() public view virtual returns (uint256) {
return PeriodLibrary.getPeriod(block.timestamp);
}
function getGauge(address _pool) external view returns (Gauge memory) {
return gauge[_pool];
}
function getPoolList() external view returns (address[] memory) {
return poolList.values();
}
function getGaugeList() external view returns (address[] memory) {
return gaugeList.values();
}
/// @notice Get all the data for a period
function getPeriodData(
uint256 _period
)
external
view
returns (
uint256 _globalTotalVotes,
address[] memory _gaugeList,
uint256[] memory _gaugeTotalVotesList,
uint256 _totalEmissions,
Emissions[] memory _gaugeEmissionsList,
uint256 _totalClaimedEmissions
)
{
Period storage ps = period[_period];
_globalTotalVotes = ps.globalTotalVotes;
_totalEmissions = ps.totalEmissions;
_totalClaimedEmissions = ps.totalClaimedEmissions;
_gaugeList = gaugeList.values();
_gaugeTotalVotesList = new uint256[](_gaugeList.length);
_gaugeEmissionsList = new Emissions[](_gaugeList.length);
uint256 gaugeCount = _gaugeList.length;
for (uint256 i; i < gaugeCount; ++i) {
_gaugeTotalVotesList[i] = ps.gaugeTotalVotes[_gaugeList[i]];
_gaugeEmissionsList[i] = ps.gaugeEmissions[_gaugeList[i]];
}
}
function getTokenIdVotes(
uint256 _period,
uint256 _tokenId
) external view returns (address[] memory _tokenIdVotedList, uint256[] memory _tokenIdVotes) {
Period storage ps = period[_period];
_tokenIdVotedList = ps.tokenIdVotedList[_tokenId].values();
_tokenIdVotes = new uint256[](_tokenIdVotedList.length);
uint256 tokenIdVotedListCount = _tokenIdVotedList.length;
for (uint256 i; i < tokenIdVotedListCount; ++i) {
_tokenIdVotes[i] = ps.tokenIdVotes[gauge[_tokenIdVotedList[i]].gauge][_tokenId];
}
}
/* access control functions */
/// @dev Can be modified to support other gauge types
function createGauge() external {}
/// @notice Create a gauge for V4Pool
function createV4Gauge(address _poolAddress) external onlyOwnerOrAuthorized returns (address _gauge, address _votingReward) {
return _createGauge(_poolAddress, true);
}
function killGauge(address _gauge) external onlyOwnerOrAuthorized {
if (gaugeToPool[_gauge] == address(0)) revert GaugeDoesNotExist();
gauge[gaugeToPool[_gauge]].isAlive = false;
if (gauge[gaugeToPool[_gauge]].isV4) {
IV4Gauge(_gauge).killGauge();
}
emit GaugeKilled(_gauge);
}
function reviveGauge(address _gauge) external onlyOwnerOrAuthorized {
if (gaugeToPool[_gauge] == address(0)) revert GaugeDoesNotExist();
gauge[gaugeToPool[_gauge]].isAlive = true;
emit GaugeRevived(_gauge);
}
function setMinter(address _minter) external onlyOwnerOrAuthorized {
minter = IMinter(_minter);
}
/// @notice Whitelist token for gauge creation and incentives
function setTokenStatus(address _token, bool _status) external onlyOwnerOrAuthorized {
_status ? whitelistedTokenList.add(_token) : whitelistedTokenList.remove(_token);
emit TokenStatus(_token, _status);
}
function setVotingRewardFactory(address _votingRewardFactory) external onlyOwnerOrAuthorized {
votingRewardFactory = VotingRewardFactory(_votingRewardFactory);
}
function setV4GaugeFactory(address _v4GaugeFactory) external onlyOwnerOrAuthorized {
v4GaugeFactory = V4GaugeFactory(_v4GaugeFactory);
}
function setV4VaultFactory(address _v4VaultFactory) external onlyOwnerOrAuthorized {
v4VaultFactory = IV4VaultFactory(_v4VaultFactory);
}
/// @notice Set the minimum community fee percentage for new gauges
/// @param _communityFee The community fee floor in thousandths (1000 = 100%, 777 = 77.7%)
function setDefaultCommunityFee(uint16 _communityFee) external onlyOwnerOrAuthorized {
if (_communityFee > 1_000) revert InvalidParameters();
defaultCommunityFee = _communityFee;
emit DefaultCommunityFeeChanged(_communityFee);
}
/// @notice Set default v4 vault fee config applied when Voter configures a pool vault
/// @param _receiver Receiver for v4 fee share (must be non-zero when _v4Fee > 0)
/// @param _v4Fee v4 fee share in thousandths (1000 = 100%)
function setDefaultV4VaultFeeConfig(address _receiver, uint16 _v4Fee) external onlyOwnerOrAuthorized {
if (_v4Fee > 1_000) revert InvalidParameters();
if (_v4Fee != 0 && _receiver == address(0)) revert InvalidParameters();
defaultV4FeeReceiver = _receiver;
defaultV4Fee = _v4Fee;
emit DefaultV4VaultFeeConfigChanged(_receiver, _v4Fee);
}
/// @notice Updates v4 fee receiver and v4 fee for an existing gauge vault
/// @dev Requires Voter to be current v4FeeManager of the vault
function setGaugeVaultV4FeeConfig(address _pool, address _receiver, uint16 _v4Fee) external onlyOwnerOrAuthorized {
Gauge storage gs = gauge[_pool];
if (gs.gauge == address(0)) revert GaugeDoesNotExist();
IV4CommunityVault vault = IV4CommunityVault(gs.vault);
_applyV4VaultFeeConfig(vault, _receiver, _v4Fee);
emit GaugeVaultV4FeeConfigChanged(_pool, _receiver, _v4Fee);
}
/// @notice Initiates transfer of gauge vault v4 fee manager role
/// @dev New manager must call acceptV4FeeManagerRole() on the vault to finalize
function transferGaugeVaultV4FeeManager(address _pool, address _newV4FeeManager) external onlyOwnerOrAuthorized {
if (_newV4FeeManager == address(0)) revert InvalidParameters();
Gauge storage gs = gauge[_pool];
if (gs.gauge == address(0)) revert GaugeDoesNotExist();
IV4CommunityVault(gs.vault).transferV4FeeManagerRole(_newV4FeeManager);
emit GaugeVaultV4FeeManagerTransferStarted(_pool, _newV4FeeManager);
}
/// @notice Enables or disables zero-emission V4 fee forwarding for an onboarded V4 pool.
/// @dev Positive-emission distributions can still release fees even when this flag is false.
function setV4FeeDistributionStatus(address _pool, bool _enabled) external onlyOwnerOrAuthorized {
Gauge storage gs = gauge[_pool];
if (gs.gauge == address(0)) revert GaugeDoesNotExist();
if (!gs.isV4) revert InvalidParameters();
v4FeeDistributionEnabled[_pool] = _enabled;
emit V4FeeDistributionStatus(_pool, _enabled);
}
function setProtocolFeeManager(address _protocolFeeManager) external onlyOwnerOrAuthorized {
protocolFeeManager = IProtocolFeeManager(_protocolFeeManager);
emit ProtocolFeeManagerUpdated(_protocolFeeManager);
}
/// @notice Start ve33 voting and epoch 0
function start() external onlyOwnerOrAuthorized {
epoch0Period = getCurrentPeriod();
minter.start();
}
/* internal functions */
function _checkPeriodVoted(uint256 _period, uint256 _tokenId) internal view returns (bool) {
return period[_period].voted[_tokenId];
}
/// @notice Remove all existing votes for a tokenId in a given period
function _resetVotes(uint256 _period, uint256 _tokenId) internal {
address[] memory previousPools = period[_period].tokenIdVotedList[_tokenId].values();
uint256 poolCount = previousPools.length;
for (uint256 i; i < poolCount; ++i) {
_removeVoteForGauge(_period, _tokenId, previousPools[i]);
}
}
function _validatePoolList(address[] memory _poolList) internal pure {
uint256 poolCount = _poolList.length;
for (uint256 i; i < poolCount; ++i) {
for (uint256 j = i + 1; j < poolCount; ++j) {
if (_poolList[i] == _poolList[j]) revert InvalidParameters();
}
}
}
function _vote(uint256 _period, uint256 _tokenId, address[] memory _poolList, uint256[] memory _weightList) internal {
uint256 votingPower = veNFT.balanceOfNFT(_tokenId);
uint256 totalWeight;
uint256 weightCount = _weightList.length;
for (uint256 i; i < weightCount; ++i) totalWeight += _weightList[i];
if (totalWeight == 0) revert ZeroVotes();
uint256 poolCount = _poolList.length;
for (uint256 i; i < poolCount; ++i) {
_removeVoteForGauge(_period, _tokenId, _poolList[i]);
_voteForGauge(_period, _tokenId, _poolList[i], (votingPower * _weightList[i]) / totalWeight);
}
emit Voted(_tokenId, votingPower, _period);
}
/// @notice Deposit votes for a gauge
/// @dev Does not need to check for double voting to same pool as _removeVoteForGauge is called before _voteForGauge - the side effect will be losing total votingPower if they try to vote twice or more on the same pool
function _voteForGauge(uint256 _period, uint256 _tokenId, address _pool, uint256 _votes) internal {
IVoter.Period storage ps = period[_period];
IVoter.Gauge storage gs = gauge[_pool];
address _gauge = gs.gauge;
// checks
if (_gauge == address(0)) revert GaugeDoesNotExist();
if (gs.isAlive == false) revert GaugeDead();
if (_votes == 0) revert ZeroVotes();
// internal voting for gauge
ps.globalTotalVotes += _votes;
ps.gaugeTotalVotes[_gauge] += _votes;
ps.tokenIdVotes[_gauge][_tokenId] += _votes;
ps.tokenIdVotedList[_tokenId].add(_pool);
// deposit weights into rewards contract
IVotingReward(gs.votingReward)._deposit(_votes, _tokenId);
// rebaseReward._deposit(_votes, _tokenId);
}
/// @notice Remove votes for a gauge in period
function _removeVoteForGauge(uint256 _period, uint256 _tokenId, address _pool) internal {
IVoter.Period storage ps = period[_period];
IVoter.Gauge storage gs = gauge[_pool];
address _gauge = gs.gauge;
uint256 previousVotes = ps.tokenIdVotes[_gauge][_tokenId];
ps.globalTotalVotes -= previousVotes;
ps.gaugeTotalVotes[_gauge] -= previousVotes;
ps.tokenIdVotes[_gauge][_tokenId] = 0;
ps.tokenIdVotedList[_tokenId].remove(_pool);
IVotingReward(gs.votingReward)._withdraw(previousVotes, _tokenId);
// rebaseReward._withdraw(previousVotes, _tokenId);
}
/// @dev Can be modified to support other gauge types
function _createGauge(address _poolAddress, bool _isV4) internal returns (address _gauge, address _votingReward) {
Gauge storage gs = gauge[_poolAddress];
if (gs.gauge != address(0)) revert GaugeAlreadyExist();
IV4Pool v4Pool = IV4Pool(_poolAddress);
// check if tokens are whitelisted
address _token0 = v4Pool.token0();
address _token1 = v4Pool.token1();
address coreFactory = IV4VaultFactoryWithFactory(address(v4VaultFactory)).factory();
if (v4Pool.factory() != coreFactory) revert InvalidParameters();
if (!whitelistedTokenList.contains(_token0) || !whitelistedTokenList.contains(_token1)) revert TokenNotWhitelisted();
// create VotingReward
gs.votingReward = votingRewardFactory.createVotingReward();
IVotingReward(gs.votingReward).grantNotifyRole(address(this));
gs.isV4 = _isV4;
gs.isAlive = true;
// try to get existing vault
address vault = v4VaultFactory.getVaultForPool(_poolAddress);
if (vault == address(0)) {
// create new V4CommunityVault for gauge and set to pool
vault = v4VaultFactory.createVaultForPool(_poolAddress, msg.sender, address(0), _token0, _token1);
v4Pool.setCommunityVault(vault);
}
gs.vault = vault;
IV4CommunityVault newVault = IV4CommunityVault(vault);
// Configure community receiver and optional v4 fee split for ve routing.
(, , , , uint16 _communityFee, ) = v4Pool.globalState();
if (_communityFee != defaultCommunityFee) v4Pool.setCommunityFee(defaultCommunityFee);
if (newVault.communityFeeReceiver() != address(this)) {
newVault.changeCommunityFeeReceiver(address(this));
}
_applyV4VaultFeeConfig(newVault, defaultV4FeeReceiver, defaultV4Fee);
uint256 seedAmount = 1; // dust for creating farm
token.safeTransferFrom(msg.sender, address(this), seedAmount);
token.approve(address(v4GaugeFactory), seedAmount);
gs.gauge = v4GaugeFactory.createGauge(_poolAddress, seedAmount);
poolList.add(_poolAddress);
gaugeList.add(gs.gauge);
gaugeToPool[gs.gauge] = _poolAddress;
emit GaugeCreated(gs.gauge, gs.votingReward, _poolAddress);
return (gs.gauge, gs.votingReward);
}
/// @notice Collect fees and distribute token emissions to the gauge for current period
function _distribute(uint256 _period, address _gauge) internal {
// check to see if trying to distribute for future period
uint256 currentPeriod = getCurrentPeriod();
if (_period > currentPeriod) revert InvalidPeriod();
IVoter.Period storage ps = period[_period];
IVoter.Emissions storage es = ps.gaugeEmissions[_gauge];
if (ps.gaugeTotalVotes[_gauge] == 0 || ps.globalTotalVotes == 0) return;
uint256 emissions = (ps.totalEmissions * ps.gaugeTotalVotes[_gauge]) / ps.globalTotalVotes;
address _pool = gaugeToPool[_gauge];
IVoter.Gauge storage gs = gauge[_pool];
bool gaugeAlive = gs.isAlive;
bool willDistributePositiveEmissions = !es.distributed && emissions > 0 && gaugeAlive;
bool shouldDistributeV4Fees = gaugeAlive &&
gs.isV4 &&
currentPeriod == _period &&
!v4FeesDistributed[_period][_gauge] &&
(willDistributePositiveEmissions || v4FeeDistributionEnabled[_pool]);
if (es.distributed) {
emissions = 0;
} else if (emissions > 0) {
ps.totalClaimedEmissions += emissions;
// transfer emissions to minter if gauge is killed
if (!gaugeAlive) {
token.transfer(address(minter), emissions);
emissions = 0;
} else {
es.amount = emissions;
}
es.distributed = true;
} else {
// Preserve the emission-distribution completion marker for zero-emission periods.
// Fee forwarding is tracked separately by v4FeesDistributed.
es.distributed = true;
emissions = 0;
}
// voting rewards can only be distributed for the current period.
// all rewards not distributed from previous periods will be carried forward to current period.
if (shouldDistributeV4Fees) {
v4FeesDistributed[_period][_gauge] = true;
_claimAndDistributeV4PoolFees(_pool);
}
if (emissions > 0) {
// notified amounts to gauge will be added on top of existing emissions
token.approve(_gauge, emissions);
IV4Gauge(_gauge).notifyRewardAmount(emissions);
emit DistributeEmissions(_gauge, emissions, _period);
}
}
/// @notice Claim and distribute fees from V4CommunityVault to VotingReward
function _claimAndDistributeV4PoolFees(address _pool) internal {
IV4Pool v4Pool = IV4Pool(_pool);
IVotingReward votingReward = IVotingReward(gauge[_pool].votingReward);
IERC20 token0 = IERC20(v4Pool.token0());
IERC20 token1 = IERC20(v4Pool.token1());
IV4CommunityVault vault = IV4CommunityVault(v4Pool.communityVault());
uint256 token0BalVault = token0.balanceOf(address(vault));
uint256 token0BalBefore = token0.balanceOf(address(this));
vault.withdraw(address(token0), token0BalVault);
uint256 token0Claimed = token0.balanceOf(address(this)) - token0BalBefore;
_forwardFeesToVotingReward(votingReward, token0, token0Claimed);
uint256 token1BalVault = token1.balanceOf(address(vault));
uint256 token1BalBefore = token1.balanceOf(address(this));
vault.withdraw(address(token1), token1BalVault);
uint256 token1Claimed = token1.balanceOf(address(this)) - token1BalBefore;
_forwardFeesToVotingReward(votingReward, token1, token1Claimed);
emit DistributeV4Fees(_pool, token0Claimed, token1Claimed);
}
function _forwardFeesToVotingReward(IVotingReward votingReward, IERC20 feeToken, uint256 amount) internal {
if (amount == 0) return;
address votingRewardAddress = address(votingReward);
IProtocolFeeManager manager = protocolFeeManager;
if (address(manager) != address(0)) {
feeToken.safeTransfer(address(manager), amount);
(address buybackToken, uint256 buybackAmount, uint256 passthroughAmount) = manager.handleFee(address(feeToken), amount);
if (buybackAmount > 0) {
IERC20(buybackToken).forceApprove(votingRewardAddress, buybackAmount);
votingReward.notifyRewardAmount(buybackToken, buybackAmount);
IERC20(buybackToken).forceApprove(votingRewardAddress, 0);
}
if (passthroughAmount > 0) {
feeToken.forceApprove(votingRewardAddress, passthroughAmount);
votingReward.notifyRewardAmount(address(feeToken), passthroughAmount);
feeToken.forceApprove(votingRewardAddress, 0);
}
} else {
feeToken.forceApprove(votingRewardAddress, amount);
votingReward.notifyRewardAmount(address(feeToken), amount);
feeToken.forceApprove(votingRewardAddress, 0);
}
}
function _applyV4VaultFeeConfig(IV4CommunityVault vault, address receiver, uint16 fee) internal {
if (fee > 1_000) revert InvalidParameters();
if (fee != 0) {
if (receiver == address(0)) revert InvalidParameters();
if (vault.v4FeeReceiver() != receiver) {
vault.changeV4FeeReceiver(receiver);
}
}
if (vault.v4Fee() != fee) {
if (vault.hasNewV4FeeProposal()) {
vault.cancelV4FeeChangeProposal();
}
vault.proposeV4FeeChange(fee);
vault.acceptV4FeeChangeProposal(fee);
}
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
// --- Storage gap for future upgrades ---
uint256[50] private __gap;
}
/IPeripheryImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface IPeripheryImmutableState {
/// @return Returns the address of the V4 factory
function factory() external view returns (address);
/// @return Returns the address of the pool Deployer
function poolDeployer() external view returns (address);
/// @return Returns the address of WNativeToken
function WNativeToken() external view returns (address);
}
/INonfungiblePositionManager.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
/// @title Non-fungible token for positions
/// @notice Wraps V4 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidityDesired The amount by which liquidity for the NFT position was increased
/// @param actualLiquidity the actual liquidity that was added into a pool. Could differ from
/// _liquidity_ when using FeeOnTransfer tokens
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(
uint256 indexed tokenId,
uint128 liquidityDesired,
uint128 actualLiquidity,
uint256 amount0,
uint256 amount1,
address pool
);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Emitted if farming failed in call from NonfungiblePositionManager.
/// @dev Should never be emitted
/// @param tokenId The ID of corresponding token
event FarmingFailed(uint256 indexed tokenId);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return deployer The address of the custom pool deployer
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(
uint256 tokenId
)
external
view
returns (
uint88 nonce,
address operator,
address token0,
address token1,
address deployer,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
address deployer;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @dev If native token is used as input, this function should be accompanied by a `refundNativeToken` in multicall to avoid potential loss of native tokens
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The liquidity delta amount as a result of the increase
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(
MintParams calldata params
) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @dev If native token is used as input, this function should be accompanied by a `refundNativeToken` in multicall to avoid potential loss of native tokens
/// @return liquidity The liquidity delta amount as a result of the increase
/// @return amount0 The amount of token0 to achieve resulting liquidity
/// @return amount1 The amount of token1 to achieve resulting liquidity
function increaseLiquidity(
IncreaseLiquidityParams calldata params
) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(
DecreaseLiquidityParams calldata params
) external payable returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @dev If `recipient` is zero, the manager contract is used. Always pair that usage with a
/// sweep/unwrap in the same transaction to avoid leaving funds temporarily custodied and
/// exposed to MEV/front-running.
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens (zero defaults to the manager),
/// 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);
struct CollectAndSweepParams {
uint256 tokenId;
uint128 amount0Max;
uint128 amount1Max;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
}
/// @notice Collects fees to the manager and immediately sweeps both tokens to a recipient.
/// @dev Use when collecting to the manager (`recipient=address(0)`) to avoid leaving funds
/// in custody across transactions. Reverts if either collected amount is below the
/// provided minimums.
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect,
/// amount0Min The minimum amount of token0 that must be swept,
/// amount1Min The minimum amount of token1 that must be swept,
/// recipient The account that should receive swept tokens (zero defaults to msg.sender)
/// @return amount0 The amount of token0 swept to the recipient
/// @return amount1 The amount of token1 swept to the recipient
function collectAndSweep(
CollectAndSweepParams calldata params
) external payable returns (uint256 amount0, uint256 amount1);
struct CollectAndUnwrapWNativeParams {
uint256 tokenId;
uint128 amount0Max;
uint128 amount1Max;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
}
/// @notice Collects position proceeds while unwrapping WNative and avoiding an extra hop for the paired ERC20.
/// @dev Use for WNative/token positions, especially when the paired ERC20 may charge transfer fees.
/// The non-WNative token is collected directly to the recipient; WNative is collected to this contract,
/// unwrapped, and sent as native token. Reverts if neither pool token is WNative.
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect,
/// amount0Min The minimum final token0 amount that must reach the recipient,
/// amount1Min The minimum final token1 amount that must reach the recipient,
/// recipient The account that should receive collected assets (zero defaults to msg.sender)
/// @return amount0 The final amount of token0 delivered to the recipient, after transfer tax if any
/// @return amount1 The final amount of token1 delivered to the recipient, after transfer tax if any
function collectAndUnwrapWNativeToken(
CollectAndUnwrapWNativeParams calldata params
) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
/// @notice Changes approval of token ID for farming.
/// @param tokenId The ID of the token that is being approved / unapproved
/// @param approve New status of approval
/// @param farmingAddress The address of farming: used to prevent tx frontrun
function approveForFarming(uint256 tokenId, bool approve, address farmingAddress) external payable;
/// @notice Changes farming status of token to 'farmed' or 'not farmed'
/// @dev can be called only by farmingCenter
/// @param tokenId The ID of the token
/// @param toActive The new status
function switchFarmingStatus(uint256 tokenId, bool toActive) external;
/// @notice Changes address of farmingCenter
/// @dev can be called only by factory owner or NONFUNGIBLE_POSITION_MANAGER_ADMINISTRATOR_ROLE
/// @param newFarmingCenter The new address of farmingCenter
function setFarmingCenter(address newFarmingCenter) external;
/// @notice Returns whether `spender` is allowed to manage `tokenId`
/// @dev Requirement: `tokenId` must exist
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
/// @notice Returns the address of currently connected farming, if any
/// @return The address of the farming center contract, which handles farmings logic
function farmingCenter() external view returns (address);
/// @notice Returns the address of farming that is approved for this token, if any
function farmingApprovals(uint256 tokenId) external view returns (address);
/// @notice Returns the address of farming in which this token is farmed, if any
function tokenFarmedIn(uint256 tokenId) external view returns (address);
}
/PeriodLibrary.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.7.6;
// used to sync contracts to use the same period durations
library PeriodLibrary {
uint256 internal constant DURATION = 7 * 86400;
function periodStart(uint256 timestamp) internal pure returns (uint256) {
return (timestamp / DURATION) * DURATION;
}
function periodNext(uint256 timestamp) internal pure returns (uint256) {
return (timestamp / DURATION) * DURATION + DURATION;
}
function getPeriod(uint256 timestamp) internal pure returns (uint256) {
return timestamp / DURATION;
}
}
/Math.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
library Math {
function max(uint a, uint b) internal pure returns (uint) {
return a >= b ? a : b;
}
function min(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function cbrt(uint256 n) internal pure returns (uint256) {
unchecked {
uint256 x = 0;
for (uint256 y = 1 << 255; y > 0; y >>= 3) {
x <<= 1;
uint256 z = 3 * x * (x + 1) + 1;
if (n / y >= z) {
n -= y * z;
x += 1;
}
}
return x;
}
}
}
/LibRebaseRewardStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
library LibRebaseRewardStorage {
struct Layout {
IERC20 token;
}
bytes32 internal constant STORAGE_SLOT = keccak256('tokenswap.contracts.storage.RebaseReward');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
/IMintable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IMintable is IERC20 {
error NotMinter();
function mint(address, uint) external;
function minter() external view returns (address);
}
/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
interface IERC20 {
function totalSupply() external view returns (uint256);
function transfer(address recipient, uint amount) external returns (bool);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function balanceOf(address) external view returns (uint);
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/VeArtProxy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Base64} from './libraries/Base64.sol';
import {IVeArtProxy} from './interfaces/IVeArtProxy.sol';
contract VeArtProxy is IVeArtProxy {
function toString(uint value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return '0';
}
uint temp = value;
uint digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint(value % 10)));
value /= 10;
}
return string(buffer);
}
function _tokenURI(uint _tokenId, uint _balanceOf, uint _locked_end, uint _value) external pure returns (string memory output) {
output = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">';
output = string(abi.encodePacked(output, 'token ', toString(_tokenId), '</text><text x="10" y="40" class="base">'));
output = string(abi.encodePacked(output, 'balanceOf ', toString(_balanceOf), '</text><text x="10" y="60" class="base">'));
output = string(abi.encodePacked(output, 'locked_end ', toString(_locked_end), '</text><text x="10" y="80" class="base">'));
output = string(abi.encodePacked(output, 'value ', toString(_value), '</text></svg>'));
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "lock #',
toString(_tokenId),
'", "description": "Token locks, can be used to boost gauge yields, vote on token emission, and receive bribes", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(output)),
'"}'
)
)
)
);
output = string(abi.encodePacked('data:application/json;base64,', json));
}
}
/MockV4VaultFactory.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
contract MockV4CommunityVault {
address public administrator;
address public v4FeeManager;
address public pendingV4FeeManager;
address public communityFeeReceiver;
address public v4FeeReceiver;
uint16 public v4Fee;
bool public hasNewV4FeeProposal;
uint16 public proposedNewV4Fee;
modifier onlyAdministrator() {
require(msg.sender == administrator, 'only administrator');
_;
}
modifier onlyV4FeeManager() {
require(msg.sender == v4FeeManager, 'only switchx fee manager');
_;
}
constructor(address _administrator, address _v4FeeManager) {
require(_administrator != address(0), 'invalid administrator');
require(_v4FeeManager != address(0), 'invalid fee manager');
administrator = _administrator;
v4FeeManager = _v4FeeManager;
}
function changeCommunityFeeReceiver(address _receiver) external onlyAdministrator {
communityFeeReceiver = _receiver;
}
function changeV4FeeReceiver(address _receiver) external onlyV4FeeManager {
require(_receiver != address(0), 'invalid switchx fee receiver');
v4FeeReceiver = _receiver;
}
function proposeV4FeeChange(uint16 _newV4Fee) external onlyV4FeeManager {
require(_newV4Fee <= 1_000, 'invalid new fee');
proposedNewV4Fee = _newV4Fee;
hasNewV4FeeProposal = true;
}
function cancelV4FeeChangeProposal() external onlyV4FeeManager {
proposedNewV4Fee = 0;
hasNewV4FeeProposal = false;
}
function acceptV4FeeChangeProposal(uint16 _newV4Fee) external onlyAdministrator {
require(hasNewV4FeeProposal && proposedNewV4Fee == _newV4Fee, 'invalid proposal');
v4Fee = _newV4Fee;
proposedNewV4Fee = 0;
hasNewV4FeeProposal = false;
}
function transferV4FeeManagerRole(address _newV4FeeManager) external onlyV4FeeManager {
pendingV4FeeManager = _newV4FeeManager;
}
function acceptV4FeeManagerRole() external {
require(msg.sender == pendingV4FeeManager, 'only pending fee manager');
v4FeeManager = msg.sender;
pendingV4FeeManager = address(0);
}
function withdraw(address token, uint256 amount) external {
IERC20(token).transfer(msg.sender, amount);
}
}
contract MockV4VaultFactory {
address public factory;
mapping(address => address) public getVaultForPool;
constructor(address _factory) {
factory = _factory;
}
function createVaultForPool(address pool, address, address, address, address) external returns (address) {
address vault = address(new MockV4CommunityVault(msg.sender, msg.sender));
getVaultForPool[pool] = vault;
return vault;
}
}
/MockV4Pool.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
contract MockV4Pool {
address public token0;
address public token1;
address public factory;
address public communityVault;
uint16 public communityFee;
address public plugin;
uint8 public pluginConfig;
constructor(address _token0, address _token1) {
token0 = _token0;
token1 = _token1;
factory = msg.sender;
}
function setCommunityVault(address _vault) external {
communityVault = _vault;
}
function setCommunityFee(uint16 _fee) external {
communityFee = _fee;
}
function globalState() external view returns (uint160 price, int24 tick, uint16 lastFee, uint8 currentPluginConfig, uint16 _communityFee, bool unlocked) {
return (0, 0, 0, this.pluginConfig(), communityFee, true);
}
function setPlugin(address _plugin) external {
plugin = _plugin;
pluginConfig = 0;
}
function setPluginConfig(uint8 _pluginConfig) external {
pluginConfig = _pluginConfig;
}
function setFactory(address _factory) external {
factory = _factory;
}
}
/MockRewardVoter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IReward} from '../interfaces/IReward.sol';
contract MockRewardVoter {
mapping(address token => bool status) public whitelisted;
function setWhitelisted(address token, bool status) external {
whitelisted[token] = status;
}
function isWhitelisted(address token) external view returns (bool) {
return whitelisted[token];
}
function deposit(IReward reward, uint256 amount, uint256 tokenId) external {
reward._deposit(amount, tokenId);
}
}
/MockNonStandardERC20.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import '@switchx/v4-core/contracts/interfaces/IERC20Minimal.sol';
error ApprovalResetRequired();
error InsufficientBalance();
error InsufficientAllowance();
contract MockNonStandardERC20 is IERC20Minimal {
string public name;
string public symbol;
uint8 public constant decimals = 18;
bool public immutable failTransferFrom;
bool public immutable requireZeroReset;
mapping(address => uint256) public override balanceOf;
mapping(address => mapping(address => uint256)) public override allowance;
constructor(string memory _name, string memory _symbol, bool _failTransferFrom, bool _requireZeroReset) {
name = _name;
symbol = _symbol;
failTransferFrom = _failTransferFrom;
requireZeroReset = _requireZeroReset;
}
function mint(address to, uint256 amount) external {
balanceOf[to] += amount;
emit Transfer(address(0), to, amount);
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function approve(address spender, uint256 amount) external override returns (bool) {
if (requireZeroReset && amount != 0 && allowance[msg.sender][spender] != 0) revert ApprovalResetRequired();
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if (failTransferFrom) {
return false;
}
uint256 allowed = allowance[sender][msg.sender];
if (allowed < amount) revert InsufficientAllowance();
allowance[sender][msg.sender] = allowed - amount;
emit Approval(sender, msg.sender, allowance[sender][msg.sender]);
_transfer(sender, recipient, amount);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
if (balanceOf[sender] < amount) revert InsufficientBalance();
balanceOf[sender] -= amount;
balanceOf[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
}
/MockGaugeFactory.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {IncentiveKey} from '@switchx/v4-farming/contracts/base/IncentiveKey.sol';
contract MockGaugeFactory {
function setRates(IncentiveKey memory, uint128, uint128) external {}
}
/MockFarming.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import '../interfaces/IV4Gauge.sol';
import {IncentiveKey} from '@switchx/v4-farming/contracts/base/IncentiveKey.sol';
import {IV4EternalFarming} from '@switchx/v4-farming/contracts/interfaces/IV4EternalFarming.sol';
import {IERC20Minimal} from '@switchx/v4-core/contracts/interfaces/IERC20Minimal.sol';
contract MockVirtualPool {
uint128 public rate0;
uint128 public rate1;
function setRates(uint128 _r0, uint128 _r1) external {
rate0 = _r0;
rate1 = _r1;
}
function rewardRates() external view returns (uint128, uint128) {
return (rate0, rate1);
}
}
contract MockFarming {
struct Incentive {
uint128 totalReward;
uint128 bonusReward;
address virtualPoolAddress;
uint24 minimalPositionWidth;
bool deactivated;
address pluginAddress;
}
mapping(bytes32 => Incentive) public incentives;
address public mockVirtualPool;
uint256 public numOfIncentives;
constructor() {
mockVirtualPool = address(new MockVirtualPool());
}
function addRewards(IncentiveKey memory, uint128, uint128) external {}
function createEternalFarming(IncentiveKey memory key, IV4EternalFarming.IncentiveParams memory params, address plugin) external returns (address) {
bytes32 id = keccak256(abi.encode(key));
incentives[id] = Incentive(params.reward, params.bonusReward, mockVirtualPool, params.minimalPositionWidth, false, plugin);
numOfIncentives++;
return mockVirtualPool;
}
function setRates(IncentiveKey memory, uint128 r0, uint128 r1) external {
MockVirtualPool(mockVirtualPool).setRates(r0, r1);
}
function setIncentive(bytes32 id, uint128 r, uint128 br, address vp) external {
incentives[id] = Incentive(r, br, vp, 0, false, address(0));
}
}
/MockERC20.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
contract MockERC20 is ERC20 {
constructor(string memory name, string memory symbol) ERC20(name, symbol) {}
function mint(address to, uint256 amount) external {
_mint(to, amount);
}
}
/SWITCH.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.28;
import {Ownable2Step, Ownable} from '@openzeppelin/contracts/access/Ownable2Step.sol';
import {ERC20Burnable, ERC20} from '@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol';
import {ERC20Permit} from '@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol';
import {ISWITCH} from './interfaces/ISWITCH.sol';
/// @title SWITCH Token
/// @notice Immutable ERC20 governance token with minter role, hard cap, and EIP-2612 permit
contract SWITCH is ISWITCH, Ownable2Step, ERC20Burnable, ERC20Permit {
address public override minter;
uint256 public immutable override cap;
uint256 public immutable override emissionBudget;
uint256 public override emittedSupply;
/// @param initialMint amount to mint to `initialRecipient` during deployment
/// @param initialRecipient address that receives the `initialMint`
/// @param _cap maximum total supply (hard cap)
/// @param _isTest whether the token is a test token
constructor(
uint256 initialMint,
address initialRecipient,
uint256 _cap,
bool _isTest
) Ownable(msg.sender) ERC20(_isTest ? 'TEST-TOKEN' : 'SWITCH', _isTest ? 'TEST-TOKEN' : 'SWITCH') ERC20Permit(_isTest ? 'TEST-TOKEN' : 'SWITCH') {
require(_cap > 0, 'CapZero');
cap = _cap;
if (initialMint > cap) revert CapExceeded();
uint256 initialSupply = 0;
if (initialRecipient != address(0) && initialMint > 0) {
_mint(initialRecipient, initialMint);
initialSupply = initialMint;
}
emissionBudget = cap - initialSupply;
}
/// @notice Set the minter contract address
/// @param _minter new minter address
function setMinter(address _minter) external override onlyOwner {
address prev = minter;
minter = _minter;
emit MinterSet(prev, _minter);
}
/// @notice Mint tokens
/// @dev Only the minter can mint tokens
/// @param _account address to mint tokens to
/// @param _amount amount of tokens to mint
function mint(address _account, uint256 _amount) external override {
if (msg.sender != minter) revert NotMinter();
if (emittedSupply + _amount > emissionBudget) revert EmissionBudgetExceeded();
if (totalSupply() + _amount > cap) revert CapExceeded();
emittedSupply += _amount;
_mint(_account, _amount);
}
// Explicit overrides to satisfy interface + base class resolution
function burn(uint256 value) public override(ISWITCH, ERC20Burnable) {
super.burn(value);
}
function burnFrom(address account, uint256 value) public override(ISWITCH, ERC20Burnable) {
super.burnFrom(account, value);
}
}
/VotingRewardFactory.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
import {UUPSUpgradeable} from '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import {Ownable2StepUpgradeable} from '@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol';
import {ERC1967Proxy} from '@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol';
import {VotingReward} from './VotingReward.sol';
contract VotingRewardFactory is UUPSUpgradeable, Ownable2StepUpgradeable {
/* errors */
error NotVoter();
address public implementation;
address public veNFT;
address public voter;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(address _veNFT, address _voter, address _initialOwner) public initializer {
__UUPSUpgradeable_init();
__Ownable2Step_init();
__Ownable_init(_initialOwner);
implementation = address(new VotingReward());
veNFT = _veNFT;
voter = _voter;
}
function createVotingReward() external returns (address) {
if (msg.sender != voter) revert NotVoter();
VotingReward newVotingReward = VotingReward(
address(new ERC1967Proxy(implementation, abi.encodeCall(VotingReward.initialize, (voter, veNFT, owner()))))
);
return address(newVotingReward);
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
}
/VotingReward.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {Reward} from './Reward.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IReward} from '../interfaces/IReward.sol';
import {IVotingReward} from '../interfaces/IVotingReward.sol';
contract VotingReward is IVotingReward, Reward {
using SafeERC20 for IERC20;
constructor() {
_disableInitializers();
}
function initialize(address _voter, address _veNFT, address _initialOwner) public initializer {
__Reward_init(_voter, _veNFT, _initialOwner);
}
function grantNotifyRole(address _account) external override(Reward, IVotingReward) onlyVoter {
_grantRole(NOTIFY_ROLE, _account);
}
function _getReward(uint256 _period, uint256 _tokenId, address _token, address _owner) internal override {
if (totalVotesInPeriod[_period] > 0) {
uint256 reward = _earned(_period, _tokenId, _token);
tokenIdRewardClaimedInPeriod[_period][_tokenId][_token] += reward;
if (reward > 0) {
IERC20(_token).safeTransfer(_owner, reward);
emit ClaimReward(_period, _tokenId, _token, _owner);
}
}
}
}
/Reward.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {UUPSUpgradeable} from '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import {Ownable2StepUpgradeable} from '@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol';
import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import {AccessControlUpgradeable} from '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {ReentrancyGuardUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol';
import {PeriodLibrary} from '../libraries/PeriodLibrary.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IVoter} from '../interfaces/IVoter.sol';
import {IVotingEscrow} from '../interfaces/IVotingEscrow.sol';
import {IReward} from '../interfaces/IReward.sol';
abstract contract Reward is IReward, UUPSUpgradeable, Ownable2StepUpgradeable, ReentrancyGuardUpgradeable, AccessControlUpgradeable {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/* constants */
uint256 public constant DURATION = PeriodLibrary.DURATION;
uint256 public constant PRECISION = 1 ether;
bytes32 public constant NOTIFY_ROLE = keccak256('NOTIFY_ROLE');
IVoter public voter;
IVotingEscrow public veNFT;
uint256 public periodInit; // first period on initialize
mapping(uint256 _period => mapping(uint256 _tokenId => uint256)) public tokenIdVotesInPeriod;
mapping(uint256 _period => uint256) public totalVotesInPeriod;
mapping(uint256 _period => mapping(address _reward => uint256)) public rewardForPeriod;
mapping(uint256 _period => mapping(uint256 _tokenId => mapping(address _reward => uint256))) public tokenIdRewardClaimedInPeriod;
mapping(uint256 _tokenId => uint256) fullClaimedPeriod;
EnumerableSet.AddressSet internal rewardTokenList;
modifier onlyVoter() {
if (msg.sender != address(voter)) revert NotVoter();
_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function __Reward_init(address _voter, address _veNFT, address _initialOwner) internal onlyInitializing {
__UUPSUpgradeable_init();
__Ownable2Step_init();
__Ownable_init(_initialOwner);
__ReentrancyGuard_init();
__AccessControl_init();
_grantRole(DEFAULT_ADMIN_ROLE, _initialOwner);
voter = IVoter(_voter);
veNFT = IVotingEscrow(_veNFT);
periodInit = getCurrentPeriod();
}
/* public functions */
function getRewardForPeriod(uint256 _period, uint256 _tokenId, address _token) external virtual nonReentrant {
if (!veNFT.isApprovedOrOwner(msg.sender, _tokenId)) revert NotApprovedOrOwner();
if (_period > getCurrentPeriod()) revert FuturePeriodNotClaimable();
_getReward(_period, _tokenId, _token, msg.sender);
}
function getRewardForTokenId(uint256 _tokenId) external virtual nonReentrant {
if (!veNFT.isApprovedOrOwner(msg.sender, _tokenId)) revert NotApprovedOrOwner();
_getRewardForTokenId(_tokenId, msg.sender);
}
function getRewardForOwner(uint256 _tokenId) external virtual nonReentrant {
if (msg.sender != address(voter)) revert NotVoter();
_getRewardForTokenId(_tokenId, veNFT.ownerOf(_tokenId));
}
/* view functions */
function earnedForTokenId(uint256 _tokenId) public view virtual returns (uint256[] memory rewardList, address[] memory tokenList) {
tokenList = rewardTokenList.values();
uint256 len = rewardTokenList.length();
rewardList = new uint256[](len);
for (uint256 i; i < len; ) {
rewardList[i] = earnedForToken(_tokenId, rewardTokenList.at(i));
unchecked {
++i;
}
}
}
function earnedForToken(uint256 _tokenId, address _token) public view virtual returns (uint256 reward) {
uint256 period = fullClaimedPeriod[_tokenId] > periodInit ? fullClaimedPeriod[_tokenId] : periodInit;
uint256 currentPeriod = getCurrentPeriod();
for (; period <= currentPeriod; ) {
reward += _earned(period, _tokenId, _token);
unchecked {
++period;
}
}
}
function earnedForPeriod(uint256 _period, uint256 _tokenId, address _token) public view virtual returns (uint256) {
return _earned(_period, _tokenId, _token);
}
function getCurrentPeriod() public view virtual returns (uint256) {
return block.timestamp / DURATION;
}
function getRewardList() external view virtual returns (address[] memory) {
return rewardTokenList.values();
}
/* only voter functions */
function _deposit(uint256 _amount, uint256 _tokenId) external virtual onlyVoter {
uint256 nextPeriod = getCurrentPeriod() + 1;
tokenIdVotesInPeriod[nextPeriod][_tokenId] += _amount;
totalVotesInPeriod[nextPeriod] += _amount;
emit Deposit(nextPeriod, _amount, _tokenId);
}
function _withdraw(uint256 _amount, uint256 _tokenId) external virtual onlyVoter {
uint256 nextPeriod = getCurrentPeriod() + 1;
if (tokenIdVotesInPeriod[nextPeriod][_tokenId] > 0) {
tokenIdVotesInPeriod[nextPeriod][_tokenId] -= _amount;
totalVotesInPeriod[nextPeriod] -= _amount;
emit Withdraw(nextPeriod, _amount, _tokenId);
}
}
function grantNotifyRole(address _account) external virtual;
function rolloverZeroVoteIncentives(uint256 _period, address[] calldata _tokens) external virtual nonReentrant {
uint256 currentPeriod = getCurrentPeriod();
if (_period > currentPeriod) revert FuturePeriodNotRecoverable();
if (totalVotesInPeriod[_period] > 0) revert PeriodHasVotes();
uint256 nextPeriod = currentPeriod + 1;
uint256 len = _tokens.length;
for (uint256 i; i < len; ) {
address tokenAddress = _tokens[i];
uint256 amount = rewardForPeriod[_period][tokenAddress];
if (amount > 0) {
rewardForPeriod[_period][tokenAddress] = 0;
rewardForPeriod[nextPeriod][tokenAddress] += amount;
emit ZeroVoteIncentivesRolledOver(_period, nextPeriod, tokenAddress, amount);
}
unchecked {
++i;
}
}
}
/* only notify role functions */
function notifyRewardAmount(address _token, uint256 _amount) public virtual nonReentrant onlyRole(NOTIFY_ROLE) {
uint256 currentPeriod = getCurrentPeriod();
_addReward(currentPeriod, _token, _amount);
emit NotifyReward(currentPeriod, msg.sender, _token, _amount);
}
function incentivize(address _token, uint256 _amount) public virtual nonReentrant {
if (voter.isWhitelisted(_token) == false) revert NotWhitelistedRewardToken();
uint256 currentPeriod = getCurrentPeriod() + 1;
uint256 amount = _addReward(currentPeriod, _token, _amount);
emit IncentivizedReward(currentPeriod, msg.sender, _token, amount);
}
/* internal functions */
function _addReward(uint256 _period, address _token, uint256 _amount) internal virtual returns (uint256 amount) {
_trackRewardToken(_token);
IERC20 token = IERC20(_token);
uint256 tokenBalBefore = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 tokenBalAfter = token.balanceOf(address(this));
amount = tokenBalAfter - tokenBalBefore;
rewardForPeriod[_period][_token] += amount;
}
function _trackRewardToken(address _token) internal {
if (rewardTokenList.contains(_token)) return;
rewardTokenList.add(_token);
}
function _getReward(uint256 _period, uint256 _tokenId, address _token, address _owner) internal virtual;
function _getRewardForTokenId(uint256 _tokenId, address _to) internal virtual {
uint256 len = rewardTokenList.length();
address[] memory tokenList = rewardTokenList.values();
uint256 currentPeriod = getCurrentPeriod();
for (uint256 i; i < len; ) {
uint256 period = fullClaimedPeriod[_tokenId] > periodInit ? fullClaimedPeriod[_tokenId] : periodInit;
for (; period <= currentPeriod; ) {
_getReward(period, _tokenId, tokenList[i], _to);
unchecked {
++period;
}
}
unchecked {
++i;
}
}
fullClaimedPeriod[_tokenId] = currentPeriod - 1;
}
function _earned(uint256 _period, uint256 _tokenId, address _token) internal view virtual returns (uint256 reward) {
if (totalVotesInPeriod[_period] > 0) {
reward = (rewardForPeriod[_period][_token] * tokenIdVotesInPeriod[_period][_tokenId] * PRECISION) / totalVotesInPeriod[_period] / PRECISION;
reward -= tokenIdRewardClaimedInPeriod[_period][_tokenId][_token];
}
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
// --- Storage gap for future upgrades ---
uint256[50] private __gap;
}
/RebaseReward.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IRebaseReward} from '../interfaces/IRebaseReward.sol';
import {IReward} from '../interfaces/IReward.sol';
import {IVotingEscrow} from '../interfaces/IVotingEscrow.sol';
import {Reward} from './Reward.sol';
import {LibRebaseRewardStorage} from '../libraries/LibRebaseRewardStorage.sol';
contract RebaseReward is IRebaseReward, Reward {
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(address _voter, address _veNFT, address _initialOwner) public initializer {
LibRebaseRewardStorage.Layout storage s = LibRebaseRewardStorage.layout();
__Reward_init(_voter, _veNFT, _initialOwner);
// Get address from VotingEscrow
address tokenAddress = IVotingEscrow(_veNFT).token();
s.token = IERC20(tokenAddress);
// Approve VotingEscrow to spend tokens for auto-relock functionality
IERC20(tokenAddress).approve(_veNFT, type(uint256).max);
}
function grantNotifyRole(address _account) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_grantRole(NOTIFY_ROLE, _account);
}
function notifyRewardAmount(uint256 _amount) external {
notifyRewardAmount(address(token()), _amount);
}
function notifyRewardAmount(address _token, uint256 _amount) public override(Reward, IReward) {
if (_token != address(token())) revert NotToken();
Reward.notifyRewardAmount(_token, _amount);
}
function incentivize(address _token, uint256 _amount) public override {
if (_token != address(token())) revert NotToken();
Reward.incentivize(_token, _amount);
}
function _getReward(uint256 _period, uint256 _tokenId, address _token, address _owner) internal override {
if (totalVotesInPeriod[_period] > 0) {
uint256 reward = _earned(_period, _tokenId, _token);
tokenIdRewardClaimedInPeriod[_period][_tokenId][_token] += reward;
if (reward > 0) {
(int128 amount, uint256 end) = veNFT.locked(_tokenId);
if (_tokenId <= veNFT.tokenId() && amount > 0 && end > block.timestamp) {
veNFT.deposit_for(_tokenId, reward);
} else {
veNFT.create_lock_for(reward, veNFT.MAXTIME(), _owner);
}
emit ClaimReward(_period, _tokenId, _token, _owner);
}
}
}
function _getRewardForTokenId(uint256 _tokenId, address _to) internal override {
address rewardToken = address(token());
uint256 currentPeriod = getCurrentPeriod();
uint256 period = fullClaimedPeriod[_tokenId] > periodInit ? fullClaimedPeriod[_tokenId] : periodInit;
uint256 totalReward;
for (; period <= currentPeriod; ) {
uint256 reward = _earned(period, _tokenId, rewardToken);
tokenIdRewardClaimedInPeriod[period][_tokenId][rewardToken] += reward;
if (reward > 0) {
totalReward += reward;
emit ClaimReward(period, _tokenId, rewardToken, _to);
}
unchecked {
++period;
}
}
fullClaimedPeriod[_tokenId] = currentPeriod - 1;
if (totalReward == 0) return;
(int128 amount, uint256 end) = veNFT.locked(_tokenId);
if (_tokenId <= veNFT.tokenId() && amount > 0 && end > block.timestamp) {
veNFT.deposit_for(_tokenId, totalReward);
} else {
veNFT.create_lock_for(totalReward, veNFT.MAXTIME(), _to);
}
}
function token() public view returns (IERC20 _token) {
_token = LibRebaseRewardStorage.layout().token;
}
}
/DripVotingRewardFactory.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {UUPSUpgradeable} from '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import {Ownable2StepUpgradeable} from '@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol';
import {ERC1967Proxy} from '@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol';
import {DripVotingReward} from './DripVotingReward.sol';
/// @title DripVotingRewardFactory
/// @notice Factory contract for deploying DripVotingReward instances
/// @dev Creates proxied DripVotingReward contracts with configurable default drip rate
contract DripVotingRewardFactory is UUPSUpgradeable, Ownable2StepUpgradeable {
/* errors */
error NotVoter();
error InvalidDripRate();
error ZeroAddress();
/* events */
event DefaultDripRateUpdated(uint16 oldRate, uint16 newRate);
event ImplementationUpdated(address oldImplementation, address newImplementation);
/* state variables */
address public implementation;
address public veNFT;
address public voter;
uint16 public defaultDripRate;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @notice Initialize the factory
/// @param _veNFT The VotingEscrow contract address
/// @param _voter The Voter contract address
/// @param _initialOwner The initial owner address
/// @param _defaultDripRate The default drip rate for new instances (basis points, e.g., 2000 = 20%)
function initialize(address _veNFT, address _voter, address _initialOwner, uint16 _defaultDripRate) public initializer {
__UUPSUpgradeable_init();
__Ownable2Step_init();
__Ownable_init(_initialOwner);
if (_veNFT == address(0) || _voter == address(0) || _initialOwner == address(0)) revert ZeroAddress();
if (_defaultDripRate > 10000) revert InvalidDripRate();
implementation = address(new DripVotingReward());
veNFT = _veNFT;
voter = _voter;
defaultDripRate = _defaultDripRate;
}
/// @notice Create a new DripVotingReward instance
/// @dev Can only be called by the Voter contract
/// @return The address of the newly created DripVotingReward proxy
function createVotingReward() external returns (address) {
if (msg.sender != voter) revert NotVoter();
DripVotingReward newDripVotingReward = DripVotingReward(
address(new ERC1967Proxy(implementation, abi.encodeCall(DripVotingReward.initialize, (voter, veNFT, owner(), defaultDripRate))))
);
return address(newDripVotingReward);
}
/// @notice Update the default drip rate for new instances
/// @param _rate New default drip rate in basis points (max 10000)
function setDefaultDripRate(uint16 _rate) external onlyOwner {
if (_rate > 10000) revert InvalidDripRate();
uint16 oldRate = defaultDripRate;
defaultDripRate = _rate;
emit DefaultDripRateUpdated(oldRate, _rate);
}
/// @notice Update the implementation contract for new instances
/// @param _newImplementation The new implementation contract address
function setImplementation(address _newImplementation) external onlyOwner {
if (_newImplementation == address(0)) revert ZeroAddress();
address oldImplementation = implementation;
implementation = _newImplementation;
emit ImplementationUpdated(oldImplementation, _newImplementation);
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
}
/DripVotingReward.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import {Reward} from './Reward.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IReward} from '../interfaces/IReward.sol';
import {IVotingReward} from '../interfaces/IVotingReward.sol';
import {IDripVotingReward} from '../interfaces/IDripVotingReward.sol';
/// @title DripVotingReward
/// @notice A voting reward contract that pools fees and releases a configurable percentage each period
/// @dev Extends Reward.sol and overrides key functions to implement drip-based distribution
contract DripVotingReward is IDripVotingReward, Reward {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/* state variables */
/// @notice Accounts allowed to top up pooled rewards directly
bytes32 public constant TOP_UP_ROLE = keccak256('TOP_UP_ROLE');
/// @notice The percentage of pool to release each period (basis points, 10000 = 100%)
uint16 public dripRate;
/// @notice Total accumulated pool balance per token (not yet released)
mapping(address _token => uint256) public poolBalance;
/// @notice Amount released (made claimable) per period per token
mapping(uint256 _period => mapping(address _token => uint256)) public releasedForPeriod;
/// @notice Last period when drip was executed for each token
mapping(address _token => uint256) public lastDripPeriod;
/// @notice Maximum number of periods to catch up in a single call (DoS protection)
uint256 public constant MAX_CATCHUP_PERIODS = 52; // ~1 year of weekly periods
/* constructor */
constructor() {
_disableInitializers();
}
/* initializer */
/// @notice Initialize the DripVotingReward contract
/// @param _voter The Voter contract address
/// @param _veNFT The VotingEscrow contract address
/// @param _initialOwner The initial owner address
/// @param _initialDripRate The initial drip rate in basis points (e.g., 1000 = 10%)
function initialize(address _voter, address _veNFT, address _initialOwner, uint16 _initialDripRate) public initializer {
__Reward_init(_voter, _veNFT, _initialOwner);
if (_initialDripRate > 10000) revert InvalidDripRate();
dripRate = _initialDripRate;
_grantRole(TOP_UP_ROLE, _initialOwner);
}
/* admin functions */
/// @inheritdoc IDripVotingReward
/// @dev Reverts with `PendingCatchupSettlement` if any pooled reward token still has pending catch-up periods.
function setDripRate(uint16 _newRate) external onlyOwner {
if (_newRate > 10000) revert InvalidDripRate();
_revertIfPendingCatchupExists();
uint16 oldRate = dripRate;
dripRate = _newRate;
emit DripRateUpdated(oldRate, _newRate);
}
/// @inheritdoc IDripVotingReward
function grantTopUpRole(address _account) external onlyOwner {
_grantRole(TOP_UP_ROLE, _account);
}
/// @inheritdoc IDripVotingReward
function revokeTopUpRole(address _account) external onlyOwner {
_revokeRole(TOP_UP_ROLE, _account);
}
/* public functions */
/// @inheritdoc IDripVotingReward
function triggerDrip(address _token) external nonReentrant {
// Safety: do not allow anyone to "burn" pooled rewards into a period with no votes for this gauge.
// If there are no votes in the current period, any released amount would be unclaimable.
if (totalVotesInPeriod[getCurrentPeriod()] == 0) return;
_checkpoint(_token);
}
/// @inheritdoc IDripVotingReward
function topUpPoolBalance(address _token, uint256 _amount) external nonReentrant onlyRole(TOP_UP_ROLE) {
if (voter.isWhitelisted(_token) == false) revert NotWhitelistedRewardToken();
uint256 currentPeriod = getCurrentPeriod();
// Settle pending drips at the pre-top-up balance so the incoming funds
// are not retroactively included in catch-up drip calculations.
if (totalVotesInPeriod[currentPeriod] > 0) {
_checkpoint(_token);
} else if (lastDripPeriod[_token] != 0 && lastDripPeriod[_token] < currentPeriod && poolBalance[_token] > 0) {
// No votes in current period — can't release drips (they'd be stranded).
// Advance watermark to prevent retroactive drip on the incoming top-up.
// Trade-off: the pre-existing pool skips its compound decay step for the
// no-vote period(s). Tokens remain in poolBalance and drip in future periods,
// but the intermediate compound reduction is permanently skipped. This is
// preferable to stranding funds in a voteless period or allowing retroactive
// drip inflation on the new top-up.
lastDripPeriod[_token] = currentPeriod;
}
rewardTokenList.add(_token);
IERC20 token = IERC20(_token);
uint256 tokenBalBefore = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 tokenBalAfter = token.balanceOf(address(this));
uint256 received = tokenBalAfter - tokenBalBefore;
poolBalance[_token] += received;
if (lastDripPeriod[_token] == 0) {
lastDripPeriod[_token] = currentPeriod;
}
emit PoolBalanceToppedUp(currentPeriod, msg.sender, _token, received);
}
/// @notice Grant NOTIFY_ROLE to an account (only callable by voter)
function grantNotifyRole(address _account) external override(Reward, IVotingReward) onlyVoter {
_grantRole(NOTIFY_ROLE, _account);
}
/// @inheritdoc Reward
/// @dev Fee-forwarding path used by Voter during `distribute()`. Deterministic:
/// - Simulates missed-period drips on the existing pool (credited to current period).
/// - Splits the new inflow: `dripRate%` becomes immediately claimable for current period; remainder stays in pool.
function notifyRewardAmount(address _token, uint256 _amount) public override(Reward, IReward) nonReentrant onlyRole(NOTIFY_ROLE) {
uint256 currentPeriod = getCurrentPeriod();
// Defense-in-depth: never credit `releasedForPeriod[currentPeriod]` when there are no votes for this gauge
// in the current period, because those rewards would be unclaimable (stranded) under `_earned()`.
// In the normal path, Voter only calls `notifyRewardAmount()` when distributing for a voted period,
// so this primarily protects against accidental/misconfigured NOTIFY_ROLE grants.
if (totalVotesInPeriod[currentPeriod] == 0) {
rewardTokenList.add(_token);
IERC20 t = IERC20(_token);
uint256 balBefore = t.balanceOf(address(this));
t.safeTransferFrom(msg.sender, address(this), _amount);
uint256 balAfter = t.balanceOf(address(this));
uint256 receivedNoVote = balAfter - balBefore;
poolBalance[_token] += receivedNoVote;
if (lastDripPeriod[_token] == 0) {
lastDripPeriod[_token] = currentPeriod;
}
emit NotifyReward(currentPeriod, msg.sender, _token, receivedNoVote);
return;
}
// Important: checkpoint before taking the new inflow, so missed-period drip math
// cannot retroactively include new amounts.
_checkpoint(_token);
rewardTokenList.add(_token);
IERC20 token = IERC20(_token);
uint256 tokenBalBefore = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 tokenBalAfter = token.balanceOf(address(this));
uint256 received = tokenBalAfter - tokenBalBefore;
uint256 releaseNow = (received * dripRate) / 10000;
if (releaseNow > 0) {
releasedForPeriod[currentPeriod][_token] += releaseNow;
}
poolBalance[_token] += (received - releaseNow);
// Anchor the pool start for this token to avoid "retroactive" catch-up when the first pool deposit happens
// long after the gauge/reward contract was created.
if (lastDripPeriod[_token] == 0) {
lastDripPeriod[_token] = currentPeriod;
}
emit NotifyReward(currentPeriod, msg.sender, _token, received);
}
/// @inheritdoc Reward
/// @dev Bribe path: preserve classic ve(3,3) semantics (targets next period, not dripped).
function incentivize(address _token, uint256 _amount) public override nonReentrant {
if (voter.isWhitelisted(_token) == false) revert NotWhitelistedRewardToken();
uint256 nextPeriod = getCurrentPeriod() + 1;
rewardTokenList.add(_token);
IERC20 token = IERC20(_token);
uint256 tokenBalBefore = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 tokenBalAfter = token.balanceOf(address(this));
uint256 received = tokenBalAfter - tokenBalBefore;
rewardForPeriod[nextPeriod][_token] += received;
emit IncentivizedReward(nextPeriod, msg.sender, _token, received);
}
/* view functions */
/// @notice Calculate earned rewards for a token ID across all periods
/// @dev Deterministic: counts only released drip + period-specific rewards.
function earnedForToken(uint256 _tokenId, address _token) public view override returns (uint256 reward) {
uint256 period = fullClaimedPeriod[_tokenId] > periodInit ? fullClaimedPeriod[_tokenId] : periodInit;
uint256 currentPeriod = getCurrentPeriod();
for (; period <= currentPeriod; ) {
reward += _earned(period, _tokenId, _token);
unchecked {
++period;
}
}
}
/// @notice Calculate earned rewards for a specific period
function earnedForPeriod(uint256 _period, uint256 _tokenId, address _token) public view override returns (uint256) {
return _earned(_period, _tokenId, _token);
}
/// @notice Get the number of periods pending catch-up for a token
/// @param _token The token address
/// @return pending Number of periods pending
/// @return requiresMultipleCalls Whether multiple triggerDrip calls are needed
function pendingCatchupPeriods(address _token) external view returns (uint256 pending, bool requiresMultipleCalls) {
uint256 currentPeriod = getCurrentPeriod();
if (poolBalance[_token] == 0) return (0, false);
uint256 lastDrip = lastDripPeriod[_token];
if (lastDrip == 0) {
// A token with pooled balance but no watermark should be treated as "started" this period.
lastDrip = currentPeriod;
}
if (currentPeriod > lastDrip) {
pending = currentPeriod - lastDrip;
requiresMultipleCalls = pending > MAX_CATCHUP_PERIODS;
}
}
/* internal functions */
function _revertIfPendingCatchupExists() internal view {
uint256 currentPeriod = getCurrentPeriod();
address[] memory tokenList = rewardTokenList.values();
uint256 len = tokenList.length;
for (uint256 i; i < len; ) {
address tokenAddress = tokenList[i];
uint256 currentPool = poolBalance[tokenAddress];
uint256 last = lastDripPeriod[tokenAddress];
if (currentPool > 0 && last != 0 && currentPeriod > last) {
revert PendingCatchupSettlement(tokenAddress);
}
unchecked {
++i;
}
}
}
/// @notice Apply missed-period drips on the pool and credit the released amount to the current period.
/// @dev This avoids retroactive attribution to old periods (and thus avoids late-claim affecting old votes),
/// while ensuring the pool decays as-if a drip happened each period.
/// @dev If more than MAX_CATCHUP_PERIODS have elapsed, call multiple times to fully catch up.
function _checkpoint(address _token) internal {
uint256 currentPeriod = getCurrentPeriod();
uint256 currentPool = poolBalance[_token];
uint256 last = lastDripPeriod[_token];
// If this token has never had pooled rewards and currently has none, do nothing.
// This prevents state bloat from arbitrary callers passing random token addresses to `triggerDrip`.
if (last == 0 && currentPool == 0) return;
// If there's no pool to drip, just advance the watermark so that a future first deposit
// cannot cause "catch-up" drips for periods where the pool was empty.
if (currentPool == 0) {
lastDripPeriod[_token] = currentPeriod;
return;
}
// If the pool exists but watermark is missing, anchor it to the current period.
if (last == 0) {
lastDripPeriod[_token] = currentPeriod;
return;
}
if (currentPeriod <= last) return;
uint256 pending = currentPeriod - last;
uint256 toProcess = pending;
if (toProcess > MAX_CATCHUP_PERIODS) toProcess = MAX_CATCHUP_PERIODS;
uint256 releasedAggregate;
for (uint256 i; i < toProcess; ) {
uint256 r = (poolBalance[_token] * dripRate) / 10000;
if (r > 0) {
poolBalance[_token] -= r;
releasedAggregate += r;
}
unchecked {
++i;
}
}
lastDripPeriod[_token] = last + toProcess;
if (releasedAggregate > 0) {
releasedForPeriod[currentPeriod][_token] += releasedAggregate;
emit DripReleased(currentPeriod, _token, releasedAggregate, poolBalance[_token]);
}
}
/// @notice Override _earned to use releasedForPeriod instead of rewardForPeriod
/// @dev Returns sum of released drip + period-specific rewards (e.g., bribes).
function _earned(uint256 _period, uint256 _tokenId, address _token) internal view override returns (uint256 reward) {
if (totalVotesInPeriod[_period] > 0) {
uint256 totalReward = releasedForPeriod[_period][_token] + rewardForPeriod[_period][_token];
reward = (totalReward * tokenIdVotesInPeriod[_period][_tokenId] * PRECISION) / totalVotesInPeriod[_period] / PRECISION;
reward -= tokenIdRewardClaimedInPeriod[_period][_tokenId][_token];
}
}
/// @notice Override _getReward to pay only already-accounted rewards
/// @dev Does not trigger drip release; drip release is performed by `notifyRewardAmount()` (fees) and `triggerDrip()`.
function _getReward(uint256 _period, uint256 _tokenId, address _token, address _owner) internal override {
if (totalVotesInPeriod[_period] > 0) {
uint256 reward = _earned(_period, _tokenId, _token);
tokenIdRewardClaimedInPeriod[_period][_tokenId][_token] += reward;
if (reward > 0) {
IERC20(_token).safeTransfer(_owner, reward);
emit ClaimReward(_period, _tokenId, _token, _owner);
}
}
}
}
/AlternateDripVotingReward.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
// import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
// import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
// import {Reward} from './Reward.sol';
// import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
// import {IReward} from '../interfaces/IReward.sol';
// import {IVotingReward} from '../interfaces/IVotingReward.sol';
// import {IDripVotingReward} from '../interfaces/IDripVotingReward.sol';
// /// @title AlternateDripVotingReward
// /// @notice A voting reward contract that pools fees and releases a configurable percentage each period
// /// @dev Extends Reward.sol and overrides key functions to implement drip-based distribution
// contract AlternateDripVotingReward is IDripVotingReward, Reward {
// using SafeERC20 for IERC20;
// using EnumerableSet for EnumerableSet.AddressSet;
// /* state variables */
// /// @notice Accounts allowed to top up pooled rewards directly
// bytes32 public constant TOP_UP_ROLE = keccak256('TOP_UP_ROLE');
// /// @notice The percentage of pool to release each period (basis points, 10000 = 100%)
// uint16 public dripRate;
// /// @notice Total accumulated pool balance per token (not yet released)
// mapping(address _token => uint256) public poolBalance;
// /// @notice Amount released (made claimable) per period per token
// mapping(uint256 _period => mapping(address _token => uint256)) public releasedForPeriod;
// /// @notice Amount already released from the pool but waiting for the next voted period to become claimable
// mapping(address _token => uint256) public pendingReleased;
// /// @notice Last period when drip was executed for each token
// mapping(address _token => uint256) public lastDripPeriod;
// /// @notice Maximum number of periods to catch up in a single call (DoS protection)
// uint256 public constant MAX_CATCHUP_PERIODS = 52; // ~1 year of weekly periods
// /* constructor */
// constructor() {
// _disableInitializers();
// }
// /* initializer */
// /// @notice Initialize the DripVotingReward contract
// /// @param _voter The Voter contract address
// /// @param _veNFT The VotingEscrow contract address
// /// @param _initialOwner The initial owner address
// /// @param _initialDripRate The initial drip rate in basis points (e.g., 1000 = 10%)
// function initialize(address _voter, address _veNFT, address _initialOwner, uint16 _initialDripRate) public initializer {
// __Reward_init(_voter, _veNFT, _initialOwner);
// if (_initialDripRate > 10000) revert InvalidDripRate();
// dripRate = _initialDripRate;
// _grantRole(TOP_UP_ROLE, _initialOwner);
// }
// /* admin functions */
// /// @inheritdoc IDripVotingReward
// function setDripRate(uint16 _newRate) external onlyOwner {
// if (_newRate > 10000) revert InvalidDripRate();
// _settlePendingDripsBeforeRateChange();
// uint16 oldRate = dripRate;
// dripRate = _newRate;
// emit DripRateUpdated(oldRate, _newRate);
// }
// /// @inheritdoc IDripVotingReward
// function grantTopUpRole(address _account) external onlyOwner {
// _grantRole(TOP_UP_ROLE, _account);
// }
// /// @inheritdoc IDripVotingReward
// function revokeTopUpRole(address _account) external onlyOwner {
// _revokeRole(TOP_UP_ROLE, _account);
// }
// /* public functions */
// /// @inheritdoc IDripVotingReward
// function triggerDrip(address _token) external nonReentrant {
// _checkpoint(_token);
// }
// /// @inheritdoc IDripVotingReward
// function topUpPoolBalance(address _token, uint256 _amount) external nonReentrant onlyRole(TOP_UP_ROLE) {
// if (voter.isWhitelisted(_token) == false) revert NotWhitelistedRewardToken();
// // Settle pending drips at the pre-top-up balance so the incoming funds
// // are not retroactively included in catch-up drip calculations.
// _checkpointBeforePoolMutation(_token);
// uint256 currentPeriod = getCurrentPeriod();
// _trackRewardToken(_token);
// IERC20 token = IERC20(_token);
// uint256 tokenBalBefore = token.balanceOf(address(this));
// token.safeTransferFrom(msg.sender, address(this), _amount);
// uint256 tokenBalAfter = token.balanceOf(address(this));
// uint256 received = tokenBalAfter - tokenBalBefore;
// poolBalance[_token] += received;
// if (lastDripPeriod[_token] == 0) {
// lastDripPeriod[_token] = currentPeriod;
// }
// emit PoolBalanceToppedUp(currentPeriod, msg.sender, _token, received);
// }
// /// @notice Grant NOTIFY_ROLE to an account (only callable by voter)
// function grantNotifyRole(address _account) external override(Reward, IVotingReward) onlyVoter {
// _grantRole(NOTIFY_ROLE, _account);
// }
// /// @inheritdoc Reward
// /// @dev Fee-forwarding path used by Voter during `distribute()`. Deterministic:
// /// - Simulates missed-period drips on the existing pool (credited or carried from the current period).
// /// - Splits the new inflow: `dripRate%` becomes immediately claimable for current period; remainder stays in pool.
// function notifyRewardAmount(address _token, uint256 _amount) public override(Reward, IReward) nonReentrant onlyRole(NOTIFY_ROLE) {
// uint256 currentPeriod = getCurrentPeriod();
// bool currentPeriodHasVotes = totalVotesInPeriod[currentPeriod] > 0;
// // Settle pending drips on the existing pool before taking the new inflow so the fresh
// // amount is never retroactively included in catch-up math.
// _checkpointBeforePoolMutation(_token);
// // Defense-in-depth: if there are no votes in the current period, keep fresh inflow in the pool.
// // Any older pending release was already carried into `pendingReleased` by the checkpoint above.
// if (!currentPeriodHasVotes) {
// _trackRewardToken(_token);
// IERC20 t = IERC20(_token);
// uint256 balBefore = t.balanceOf(address(this));
// t.safeTransferFrom(msg.sender, address(this), _amount);
// uint256 balAfter = t.balanceOf(address(this));
// uint256 receivedNoVote = balAfter - balBefore;
// poolBalance[_token] += receivedNoVote;
// if (lastDripPeriod[_token] == 0) {
// lastDripPeriod[_token] = currentPeriod;
// }
// emit NotifyReward(currentPeriod, msg.sender, _token, receivedNoVote);
// return;
// }
// _trackRewardToken(_token);
// IERC20 token = IERC20(_token);
// uint256 tokenBalBefore = token.balanceOf(address(this));
// token.safeTransferFrom(msg.sender, address(this), _amount);
// uint256 tokenBalAfter = token.balanceOf(address(this));
// uint256 received = tokenBalAfter - tokenBalBefore;
// uint256 releaseNow = (received * dripRate) / 10000;
// if (releaseNow > 0) {
// releasedForPeriod[currentPeriod][_token] += releaseNow;
// }
// poolBalance[_token] += (received - releaseNow);
// // Anchor the pool start for this token to avoid "retroactive" catch-up when the first pool deposit happens
// // long after the gauge/reward contract was created.
// if (lastDripPeriod[_token] == 0) {
// lastDripPeriod[_token] = currentPeriod;
// }
// emit NotifyReward(currentPeriod, msg.sender, _token, received);
// }
// /// @inheritdoc Reward
// /// @dev Bribe path: preserve classic ve(3,3) semantics (targets next period, not dripped).
// function incentivize(address _token, uint256 _amount) public override nonReentrant {
// if (voter.isWhitelisted(_token) == false) revert NotWhitelistedRewardToken();
// uint256 nextPeriod = getCurrentPeriod() + 1;
// _trackRewardToken(_token);
// IERC20 token = IERC20(_token);
// uint256 tokenBalBefore = token.balanceOf(address(this));
// token.safeTransferFrom(msg.sender, address(this), _amount);
// uint256 tokenBalAfter = token.balanceOf(address(this));
// uint256 received = tokenBalAfter - tokenBalBefore;
// rewardForPeriod[nextPeriod][_token] += received;
// emit IncentivizedReward(nextPeriod, msg.sender, _token, received);
// }
// /* view functions */
// /// @notice Calculate earned rewards for a token ID across all periods
// /// @dev Deterministic: counts only released drip + period-specific rewards.
// function earnedForToken(uint256 _tokenId, address _token) public view override returns (uint256 reward) {
// uint256 period = fullClaimedPeriod[_tokenId] > periodInit ? fullClaimedPeriod[_tokenId] : periodInit;
// uint256 currentPeriod = getCurrentPeriod();
// for (; period <= currentPeriod; ) {
// reward += _earned(period, _tokenId, _token);
// unchecked {
// ++period;
// }
// }
// }
// /// @notice Calculate earned rewards for a specific period
// function earnedForPeriod(uint256 _period, uint256 _tokenId, address _token) public view override returns (uint256) {
// return _earned(_period, _tokenId, _token);
// }
// /// @notice Get the number of periods pending catch-up for a token
// /// @param _token The token address
// /// @return pending Number of periods pending
// /// @return requiresMultipleCalls Whether multiple triggerDrip calls are needed
// function pendingCatchupPeriods(address _token) external view returns (uint256 pending, bool requiresMultipleCalls) {
// uint256 currentPeriod = getCurrentPeriod();
// if (poolBalance[_token] == 0) return (0, false);
// uint256 lastDrip = lastDripPeriod[_token];
// if (lastDrip == 0) {
// // A token with pooled balance but no watermark should be treated as "started" this period.
// lastDrip = currentPeriod;
// }
// if (currentPeriod > lastDrip) {
// pending = currentPeriod - lastDrip;
// requiresMultipleCalls = pending > MAX_CATCHUP_PERIODS;
// }
// }
// /* internal functions */
// /// @notice Apply missed-period drips on the pool and credit or carry the released amount for the current period.
// /// @dev This avoids retroactive attribution to old periods (and thus avoids late-claim affecting old votes),
// /// while ensuring the pool decays as-if a drip happened each period. If the current period has no votes,
// /// the released amount is accumulated in `pendingReleased` and flushed into the next voted period.
// /// @dev If more than MAX_CATCHUP_PERIODS have elapsed, call multiple times to fully catch up.
// function _checkpoint(address _token) internal {
// uint256 currentPeriod = getCurrentPeriod();
// bool currentPeriodHasVotes = totalVotesInPeriod[currentPeriod] > 0;
// uint256 currentPool = poolBalance[_token];
// uint256 last = lastDripPeriod[_token];
// // If this token has never had pooled rewards and currently has none, do nothing.
// // This prevents state bloat from arbitrary callers passing random token addresses to `triggerDrip`.
// if (last == 0 && currentPool == 0) {
// _flushPendingReleasedIfVoted(_token, currentPeriod, currentPeriodHasVotes);
// return;
// }
// // If there's no pool to drip, just advance the watermark so that a future first deposit
// // cannot cause "catch-up" drips for periods where the pool was empty.
// if (currentPool == 0) {
// lastDripPeriod[_token] = currentPeriod;
// _flushPendingReleasedIfVoted(_token, currentPeriod, currentPeriodHasVotes);
// return;
// }
// // If the pool exists but watermark is missing, anchor it to the current period.
// if (last == 0) {
// lastDripPeriod[_token] = currentPeriod;
// _flushPendingReleasedIfVoted(_token, currentPeriod, currentPeriodHasVotes);
// return;
// }
// if (currentPeriod <= last) {
// _flushPendingReleasedIfVoted(_token, currentPeriod, currentPeriodHasVotes);
// return;
// }
// uint256 pending = currentPeriod - last;
// uint256 toProcess = pending;
// if (toProcess > MAX_CATCHUP_PERIODS) toProcess = MAX_CATCHUP_PERIODS;
// uint256 releasedAggregate;
// for (uint256 i; i < toProcess; ) {
// uint256 r = (poolBalance[_token] * dripRate) / 10000;
// if (r > 0) {
// poolBalance[_token] -= r;
// releasedAggregate += r;
// }
// unchecked {
// ++i;
// }
// }
// lastDripPeriod[_token] = last + toProcess;
// if (releasedAggregate > 0) {
// if (currentPeriodHasVotes) {
// releasedForPeriod[currentPeriod][_token] += releasedAggregate;
// emit DripReleased(currentPeriod, _token, releasedAggregate, poolBalance[_token]);
// } else {
// pendingReleased[_token] += releasedAggregate;
// }
// }
// _flushPendingReleasedIfVoted(_token, currentPeriod, currentPeriodHasVotes);
// }
// function _settlePendingDripsBeforeRateChange() internal {
// uint256 currentPeriod = getCurrentPeriod();
// bool currentPeriodHasVotes = totalVotesInPeriod[currentPeriod] > 0;
// uint256 len = rewardTokenList.length();
// for (uint256 i; i < len; ) {
// address tokenAddress = rewardTokenList.at(i);
// uint256 last = lastDripPeriod[tokenAddress];
// if (last != 0 && last < currentPeriod) {
// uint256 currentPool = poolBalance[tokenAddress];
// if (currentPool == 0) {
// lastDripPeriod[tokenAddress] = currentPeriod;
// _flushPendingReleasedIfVoted(tokenAddress, currentPeriod, currentPeriodHasVotes);
// } else {
// uint256 pending = currentPeriod - last;
// if (pending > MAX_CATCHUP_PERIODS) revert PendingCatchupSettlement(tokenAddress, pending);
// _checkpoint(tokenAddress);
// }
// } else {
// _flushPendingReleasedIfVoted(tokenAddress, currentPeriod, currentPeriodHasVotes);
// }
// unchecked {
// ++i;
// }
// }
// }
// function _checkpointBeforePoolMutation(address _token) internal {
// uint256 currentPeriod = getCurrentPeriod();
// uint256 last = lastDripPeriod[_token];
// if (last != 0 && last < currentPeriod && poolBalance[_token] > 0) {
// uint256 pending = currentPeriod - last;
// if (pending > MAX_CATCHUP_PERIODS) revert PendingCatchupSettlement(_token, pending);
// }
// _checkpoint(_token);
// }
// function _flushPendingReleasedIfVoted(address _token, uint256 _currentPeriod, bool _currentPeriodHasVotes) internal {
// if (!_currentPeriodHasVotes) return;
// uint256 carried = pendingReleased[_token];
// if (carried == 0) return;
// pendingReleased[_token] = 0;
// releasedForPeriod[_currentPeriod][_token] += carried;
// }
// /// @notice Override _earned to use releasedForPeriod instead of rewardForPeriod
// /// @dev Returns sum of released drip + period-specific rewards (e.g., bribes).
// function _earned(uint256 _period, uint256 _tokenId, address _token) internal view override returns (uint256 reward) {
// if (totalVotesInPeriod[_period] > 0) {
// uint256 totalReward = releasedForPeriod[_period][_token] + rewardForPeriod[_period][_token];
// reward = (totalReward * tokenIdVotesInPeriod[_period][_tokenId] * PRECISION) / totalVotesInPeriod[_period] / PRECISION;
// reward -= tokenIdRewardClaimedInPeriod[_period][_tokenId][_token];
// }
// }
// /// @notice Override _getReward to pay only already-accounted rewards
// /// @dev Does not trigger drip release; drip release is performed by `notifyRewardAmount()` (fees) and `triggerDrip()`.
// function _getReward(uint256 _period, uint256 _tokenId, address _token, address _owner) internal override {
// if (totalVotesInPeriod[_period] > 0) {
// uint256 reward = _earned(_period, _tokenId, _token);
// tokenIdRewardClaimedInPeriod[_period][_tokenId][_token] += reward;
// if (reward > 0) {
// IERC20(_token).safeTransfer(_owner, reward);
// emit ClaimReward(_period, _tokenId, _token, _owner);
// }
// }
// }
// }
/ProtocolFeeManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Ownable2StepUpgradeable} from '@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol';
import {ReentrancyGuardUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol';
import {UUPSUpgradeable} from '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {ISwapRouter} from '@switchx/v4-periphery/contracts/interfaces/ISwapRouter.sol';
import {Path} from '@switchx/v4-periphery/contracts/libraries/Path.sol';
import {IOracleSlippage} from './interfaces/external/IOracleSlippage.sol';
import {IProtocolFeeManager} from './interfaces/IProtocolFeeManager.sol';
/// @title Protocol Fee Manager
/// @notice Converts raw swap fees into the asset distributed to ve voters (pass-through or buybacks)
contract ProtocolFeeManager is IProtocolFeeManager, Ownable2StepUpgradeable, ReentrancyGuardUpgradeable, UUPSUpgradeable {
using SafeERC20 for IERC20;
using Path for bytes;
address public router;
address public targetToken; // Token purchased during buybacks (e.g. SWITCH)
bool public buybackEnabled;
uint16 public buybackBps; // out of 10_000
// Token -> path to targetToken (encoded for Algebra/Uniswap v3 style routers)
mapping(address => bytes) public tokenToPath;
address public voter; // Authorized caller
IProtocolFeeManager.SlippageConfig public slippageConfig;
uint256[50] private __gap;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(address _router, address _targetToken, address _voter) external initializer {
__Ownable2Step_init();
__Ownable_init(msg.sender);
__ReentrancyGuard_init();
__UUPSUpgradeable_init();
if (_router == address(0) || _targetToken == address(0)) revert ZeroAddress();
router = _router;
targetToken = _targetToken;
if (_voter != address(0)) {
voter = _voter;
emit VoterUpdated(_voter);
}
buybackEnabled = false;
buybackBps = 5_000; // default to 50% buyback, 50% passthrough in native pool tokens
}
/// @inheritdoc IProtocolFeeManager
function handleFee(
address token,
uint256 amount
) external override nonReentrant returns (address buybackToken, uint256 buybackAmount, uint256 passthroughAmount) {
if (msg.sender != voter) revert UnauthorizedCaller();
if (amount == 0) return (token, 0, 0);
bytes memory path = tokenToPath[token];
uint256 toSwap = buybackEnabled && targetToken != address(0) && path.length > 0 ? (amount * buybackBps) / 10_000 : 0;
passthroughAmount = amount - toSwap;
if (toSwap == 0) {
IERC20(token).safeTransfer(msg.sender, amount);
emit FeeProcessed(token, amount, token, amount);
return (token, 0, amount);
}
// Check oracle slippage before swap (if enabled)
// If slippage check fails, fall back to passthrough to avoid swapping during manipulation
if (!_checkOracleSlippageSafe(path)) {
emit SwapFailed(token, toSwap, 'slippage');
IERC20(token).safeTransfer(msg.sender, amount);
emit FeeProcessed(token, amount, token, amount);
return (token, 0, amount);
}
// Attempt swap with graceful fallback
// This ensures rewards always flow to voters even if buyback pool has insufficient liquidity
// Note: amountOutMinimum is 0 because:
// 1. Oracle TWAP slippage check above rejects swaps during price manipulation (fail-closed)
// 2. Failed swaps fall back to passthrough (tokens never lost)
// 3. These are protocol fees, not user funds requiring strict protection
IERC20(token).forceApprove(router, toSwap);
bytes[] memory pluginData = new bytes[](path.numPools());
try
ISwapRouter(router).exactInput(
ISwapRouter.ExactInputParams({
pluginData: pluginData,
path: path,
recipient: msg.sender,
deadline: block.timestamp,
amountIn: toSwap,
amountOutMinimum: 0
})
)
returns (uint256 amountOut) {
IERC20(token).forceApprove(router, 0);
if (passthroughAmount > 0) {
IERC20(token).safeTransfer(msg.sender, passthroughAmount);
}
emit FeeProcessed(token, toSwap, targetToken, amountOut);
return (targetToken, amountOut, passthroughAmount);
} catch (bytes memory reason) {
// Swap failed - clear approval and fall back to passthrough mode
IERC20(token).forceApprove(router, 0);
emit SwapFailed(token, toSwap, reason);
IERC20(token).safeTransfer(msg.sender, amount);
emit FeeProcessed(token, amount, token, amount);
return (token, 0, amount);
}
}
function setBuybackBps(uint16 _buybackBps) external onlyOwner {
if (_buybackBps > 10_000) revert InvalidPercentage();
buybackBps = _buybackBps;
emit BuybackBpsUpdated(_buybackBps);
}
/// @notice Set the buyback configuration (router/target token may be updated as part of the call)
function setBuybackConfig(bool _enabled, address _router, address _targetToken) external onlyOwner {
if (_router != address(0)) {
router = _router;
}
if (_targetToken != address(0)) {
targetToken = _targetToken;
}
buybackEnabled = _enabled;
emit BuybackConfigUpdated(_enabled, targetToken, router);
}
/// @notice Configure swap path for a token (empty path disables buybacks for that token)
function setTokenPath(address token, bytes calldata path) external onlyOwner {
if (token == address(0)) revert ZeroAddress();
tokenToPath[token] = path;
emit TokenPathUpdated(token, path);
}
function setSlippageConfig(uint24 shortTermMaxTick, uint24 longTermMaxTick, uint32 longTermSecondsAgo, bool enabled) external onlyOwner {
if (enabled && shortTermMaxTick == 0 && (longTermMaxTick == 0 || longTermSecondsAgo == 0)) {
revert InvalidSlippageConfig();
}
slippageConfig = IProtocolFeeManager.SlippageConfig({
shortTermMaxTick: shortTermMaxTick,
longTermMaxTick: longTermMaxTick,
longTermSecondsAgo: longTermSecondsAgo,
enabled: enabled
});
emit SlippageConfigUpdated(shortTermMaxTick, longTermMaxTick, longTermSecondsAgo, enabled);
}
function setVoter(address _voter) external onlyOwner {
if (_voter == address(0)) revert ZeroAddress();
voter = _voter;
emit VoterUpdated(_voter);
}
/// @notice Recover tokens that become stranded inside the manager
function rescueTokens(address token, uint256 amount, address to) external onlyOwner {
if (to == address(0)) revert ZeroAddress();
IERC20(token).safeTransfer(to, amount);
}
/// @dev Check oracle slippage safely - returns false if check fails or is not configured (fail-closed)
function _checkOracleSlippageSafe(bytes memory path) internal view returns (bool) {
IProtocolFeeManager.SlippageConfig memory cfg = slippageConfig;
if (!cfg.enabled) return false; // Fail-closed: skip buyback swap when slippage protection is not configured
IOracleSlippage oracle = IOracleSlippage(router);
// Check short-term slippage
if (cfg.shortTermMaxTick > 0) {
try oracle.checkOracleSlippage(path, cfg.shortTermMaxTick, 0) {
// passed
} catch {
return false;
}
}
// Check long-term slippage
if (cfg.longTermMaxTick > 0 && cfg.longTermSecondsAgo > 0) {
try oracle.checkOracleSlippage(path, cfg.longTermMaxTick, cfg.longTermSecondsAgo) {
// passed
} catch {
return false;
}
}
return true;
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
}
/EarlyExitLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Math} from '@openzeppelin/contracts/utils/math/Math.sol';
import {IVotingEscrow} from '../interfaces/IVotingEscrow.sol';
/// @title Early Exit Fee Calculation Library
/// @notice Extracted from VotingEscrow to reduce main contract bytecode below the Spurious Dragon limit.
library EarlyExitLib {
uint256 internal constant MAX_BPS = 10_000;
/// @notice Calculate early exit penalty based on time-decay curve
/// @param start Lock start timestamp
/// @param end Lock end timestamp
/// @param value Locked token amount
/// @param maxFeeBps Maximum fee in basis points
/// @param minFeeBps Minimum (floor) fee in basis points
/// @param decayType Fee decay curve type (Linear, Inverse Quadratic, Inverse Cubic)
/// @param feeSplitBps Portion of penalty directed to voter rewards (rest burned)
function calculatePenalty(
uint256 start,
uint256 end,
uint256 value,
uint256 maxFeeBps,
uint256 minFeeBps,
IVotingEscrow.FeeDecayType decayType,
uint256 feeSplitBps
)
public
view
returns (uint256 amountToReceive, uint256 penaltyAmount, uint256 rewardShare, uint256 burnShare, uint256 feeBps)
{
if (start == 0 || end <= start) revert IVotingEscrow.InvalidLockStartTime();
if (end <= block.timestamp) revert IVotingEscrow.LockExpired();
uint256 totalDuration = end - start;
if (totalDuration == 0) revert IVotingEscrow.InvalidLockDuration();
uint256 timeRemaining = end - block.timestamp;
if (timeRemaining > totalDuration) {
timeRemaining = totalDuration;
}
if (maxFeeBps == 0) {
return (value, 0, 0, 0, 0);
}
// Calculate fee based on decay type
if (decayType == IVotingEscrow.FeeDecayType.LINEAR) {
uint256 variableFee = maxFeeBps - minFeeBps;
feeBps = minFeeBps + Math.mulDiv(variableFee, timeRemaining, totalDuration);
} else if (decayType == IVotingEscrow.FeeDecayType.INVERSE_QUADRATIC) {
uint256 elapsed = totalDuration - timeRemaining;
uint256 progressBps = Math.mulDiv(elapsed, MAX_BPS, totalDuration);
uint256 feeRawBps = MAX_BPS - Math.mulDiv(progressBps, progressBps, MAX_BPS);
feeBps = Math.mulDiv(maxFeeBps, feeRawBps, MAX_BPS);
} else if (decayType == IVotingEscrow.FeeDecayType.INVERSE_CUBIC) {
uint256 elapsed = totalDuration - timeRemaining;
uint256 progressBps = Math.mulDiv(elapsed, MAX_BPS, totalDuration);
uint256 squaredProgressBps = Math.mulDiv(progressBps, progressBps, MAX_BPS);
uint256 cubedProgressBps = Math.mulDiv(squaredProgressBps, progressBps, MAX_BPS);
uint256 feeRawBps = MAX_BPS - cubedProgressBps;
feeBps = Math.mulDiv(maxFeeBps, feeRawBps, MAX_BPS);
} else {
revert IVotingEscrow.InvalidEarlyExitFee();
}
// Clamp to [minFee, maxFee]
if (feeBps < minFeeBps) feeBps = minFeeBps;
if (feeBps > maxFeeBps) feeBps = maxFeeBps;
// Calculate penalty and split
penaltyAmount = Math.mulDiv(value, feeBps, MAX_BPS);
if (penaltyAmount > value) penaltyAmount = value;
rewardShare = Math.mulDiv(penaltyAmount, feeSplitBps, MAX_BPS);
burnShare = penaltyAmount - rewardShare;
amountToReceive = value - penaltyAmount;
}
}
/Base64.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <brecht@loopring.org>
library Base64 {
bytes internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint len = data.length;
if (len == 0) return '';
// multiply by 4/3 rounded up
uint encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
/IYieldStrategy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @title IYieldStrategy
/// @notice Interface for yield strategies that can be used by DripVotingReward to generate yield on pooled rewards
/// @dev This interface is designed for future extensibility. Implementations can wrap protocols like Aave, Compound, etc.
interface IYieldStrategy {
/// @notice Deposit tokens into the yield strategy
/// @param _token The token address to deposit
/// @param _amount The amount to deposit
/// @return sharesOrReceipt Implementation-specific receipt (shares, NFT id, etc.)
function deposit(address _token, uint256 _amount) external returns (uint256 sharesOrReceipt);
/// @notice Withdraw tokens from the yield strategy
/// @param _token The token address to withdraw
/// @param _amount The amount to withdraw (in underlying, not shares)
/// @return actualAmount The actual amount withdrawn (may differ due to slippage/fees)
function withdraw(address _token, uint256 _amount) external returns (uint256 actualAmount);
/// @notice Get the current balance of deposited tokens (including yield)
/// @param _token The token address
/// @return balance The current balance including any accrued yield
function balanceOf(address _token) external view returns (uint256 balance);
/// @notice Check if a token is supported by this strategy
/// @param _token The token address to check
/// @return supported Whether the token is supported
function supportsToken(address _token) external view returns (bool supported);
}
/IVotingReward.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IReward} from './IReward.sol';
interface IVotingReward is IReward {
function grantNotifyRole(address _account) external;
}
/IVotingEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
interface IVotingEscrow is IERC721 {
enum DepositType {
DEPOSIT_FOR_TYPE,
CREATE_LOCK_TYPE,
INCREASE_LOCK_AMOUNT,
INCREASE_UNLOCK_TIME,
MERGE_TYPE // used for splitting as well
}
enum FeeDecayType {
LINEAR,
INVERSE_QUADRATIC,
INVERSE_CUBIC
}
struct EarlyExitConfigParams {
bool enabled;
uint16 maxFeeBps;
uint16 minFeeBps;
FeeDecayType decayType;
uint16 feeSplitBps; // portion of penalty sent to voters (rest burned)
}
struct LockedBalance {
int128 amount;
uint256 end;
}
struct Point {
int128 bias;
int128 slope; // # -dweight / dt
uint256 ts;
uint256 blk; // block
}
event Deposit(address indexed provider, uint256 tokenId, uint256 value, uint256 indexed locktime, DepositType deposit_type, uint256 ts);
event Withdraw(address indexed provider, uint256 tokenId, uint256 value, uint256 ts);
event Supply(uint256 prevSupply, uint256 supply);
event Split(uint256 indexed _from, address _sender, uint256 _count);
event Merge(uint256 indexed from, uint256 indexed to, address indexed sender, uint256 amountFrom, uint256 ts);
event TokensBurned(address indexed owner, uint256 indexed tokenId, uint256 amountBurned, uint256 burnPowerAdded);
event BurnParamsUpdated(uint256 burnMultiplierBps);
event BurnPowerTransferred(uint256 indexed from, uint256 indexed to, uint256 burnPower);
event BurnLockCreated(address indexed owner, uint256 indexed tokenId, uint256 amountBurned, uint256 burnPowerAdded);
event EarlyExitConfigUpdated(bool enabled, uint256 maxFeeBps, uint256 minFeeBps, uint8 decayType, uint256 feeSplitBps);
event VoterUpdated(address indexed oldVoter, address indexed newVoter);
event EarlyExit(
address indexed provider,
uint256 indexed tokenId,
uint256 amountReceived,
uint256 penaltyAmount,
uint256 rewardShare,
uint256 burnShare,
uint256 feeBps,
uint256 timestamp
);
error Voted();
error Invalid();
error ZeroSplit();
error NotVoter();
error LockNotExist();
error LockExpired();
error OverMaxLockTime();
error NotExpired();
error InvalidParameters();
error InvalidAddress();
error InsufficientBalance();
error InvalidBurnParams();
error CannotWithdrawBurnLock();
error CannotSplitBurnLock();
error IncompatibleLockTypes();
error EarlyExitDisabled();
error CannotEarlyExitBurnLock();
error InvalidEarlyExitFee();
error NoRewards();
error TransferFailed();
error InvalidLockStartTime();
error InvalidLockDuration();
function MAXTIME() external view returns (uint256);
function token() external view returns (address);
function epoch() external view returns (uint256);
function point_history(uint256 loc) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk);
function tokenId() external view returns (uint256);
function user_point_history(uint256 tokenId, uint256 loc) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk);
function user_point_epoch(uint256 tokenId) external view returns (uint256);
function locked(uint256 tokenId) external view returns (int128 amount, uint256 end);
function isApprovedOrOwner(address, uint256) external view returns (bool);
function checkpoint() external;
function deposit_for(uint256 tokenId, uint256 value) external;
function create_lock_for(uint256, uint256, address) external returns (uint256);
function increase_unlock_time(uint256 tokenId, uint256 lockDuration) external;
function balanceOfNFT(uint256) external view returns (uint256);
function totalVotingPower() external view returns (uint256);
// --- Burn Lock extensions ---
function burnPowerOf(uint256 tokenId) external view returns (uint256);
function totalBurnPower() external view returns (uint256);
function burn_lock(uint256 tokenId) external;
function create_burn(uint256 value) external returns (uint256);
function create_burn_for(uint256 value, address to) external returns (uint256);
function increase_burn(uint256 tokenId, uint256 value) external;
// --- Early exit functions ---
function canEarlyExit(uint256 _tokenId) external view returns (bool);
function previewEarlyExitPenalty(
uint256 _tokenId
) external view returns (uint256 amountToReceive, uint256 penaltyAmount, uint256 rewardShare, uint256 burnShare, uint256 feeBps);
function earlyExit(uint256 _tokenId) external;
}
/IPeripheryPayments.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of NativeToken
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface IPeripheryPayments {
/// @notice Unwraps the contract's WNativeToken balance and sends it to recipient as NativeToken.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WNativeToken from users.
/// When collecting with `recipient=address(this)` in other contracts, always unwrap/sweep in the
/// same transaction to avoid leaving funds briefly custodied and exposed to MEV.
/// @param amountMinimum The minimum amount of WNativeToken to unwrap
/// @param recipient The address receiving NativeToken
function unwrapWNativeToken(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any NativeToken balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundNativeToken() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users.
/// If tokens were just collected to this contract (e.g., via `recipient=address(this)`), this
/// should be invoked in the same transaction/multicall to mitigate frontrun risk.
/// @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;
}
/IVoter.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
interface IVoter {
struct Emissions {
uint256 amount;
bool distributed;
bool killedDistributed;
}
struct Period {
uint256 globalTotalVotes;
mapping(address _gauge => uint256) gaugeTotalVotes;
mapping(address _gauge => mapping(uint256 _tokenId => uint256)) tokenIdVotes;
mapping(uint256 _tokenId => EnumerableSet.AddressSet) tokenIdVotedList;
mapping(uint256 _tokenId => bool) voted;
uint256 totalEmissions;
uint256 totalClaimedEmissions;
mapping(address _gauge => Emissions) gaugeEmissions;
}
struct Gauge {
address gauge;
bool isV4; // true for V4 pool
address votingReward;
bool isAlive;
address vault;
}
event GaugeCreated(address _gauge, address _votingReward, address _pool);
event GaugeKilled(address _gauge);
event GaugeRevived(address _gauge);
event Voted(uint256 _tokenId, uint256 _votingPower, uint256 _period);
event VotesReset(uint256 _tokenId, uint256 _period);
event DistributeEmissions(address _gauge, uint256 _amount, uint256 _period);
event TokenStatus(address _token, bool _status);
event DistributeV4Fees(address _pool, uint256 _amount0, uint256 _amount1);
event DefaultCommunityFeeChanged(uint16 _communityFee);
event DefaultV4VaultFeeConfigChanged(address _receiver, uint16 _v4Fee);
event GaugeVaultV4FeeConfigChanged(address _pool, address _receiver, uint16 _v4Fee);
event GaugeVaultV4FeeManagerTransferStarted(address _pool, address _newV4FeeManager);
event V4FeeDistributionStatus(address _pool, bool _enabled);
event ProtocolFeeManagerUpdated(address protocolFeeManager);
error GaugeDoesNotExist();
error GaugeAlreadyExist();
error GaugeDead();
error NotApprovedOrOwner();
error NotVotedInPeriod();
error InvalidParameters();
error Unauthorized();
error TokenNotWhitelisted();
error ZeroVotes();
error InvalidPeriod();
function isWhitelisted(address token) external view returns (bool);
function notifyRewardAmount(uint amount) external;
function distribute(address _gauge) external;
function isGauge(address _gauge) external view returns (bool);
function isAlive(address _gauge) external view returns (bool);
function vote(uint256 _tokenId, address[] memory _poolList, uint256[] memory _weightList) external;
function poke(uint256 _tokenId) external;
function reset(uint256 _tokenId) external;
function setDefaultV4VaultFeeConfig(address _receiver, uint16 _v4Fee) external;
function setGaugeVaultV4FeeConfig(address _pool, address _receiver, uint16 _v4Fee) external;
function transferGaugeVaultV4FeeManager(address _pool, address _newV4FeeManager) external;
function setV4FeeDistributionStatus(address _pool, bool _enabled) external;
function getGauge(address _pool) external view returns (Gauge memory);
function getPoolList() external view returns (address[] memory);
function getGaugeList() external view returns (address[] memory);
function checkPeriodVoted(uint256 _period, uint256 _tokenId) external view returns (bool);
function getTokenIdVotes(
uint256 _period,
uint256 _tokenId
) external view returns (address[] memory _tokenIdVotedList, uint256[] memory _tokenIdVotes);
}
/IVeArtProxy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IVeArtProxy {
function _tokenURI(uint _tokenId, uint _balanceOf, uint _locked_end, uint _value) external pure returns (string memory output);
}
/IV4GaugeFactory.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {IncentiveKey} from '@switchx/v4-farming/contracts/base/IncentiveKey.sol';
interface IV4GaugeFactory {
error NotVoter();
error NotGauge();
error ZeroAddress();
error InvalidImplementation(address implementation);
event ImplementationUpdated(address oldImplementation, address newImplementation);
function createGauge(address _poolAddress, uint256 _seedAmount) external returns (address);
function setImplementation(address _newImplementation) external;
function setRates(IncentiveKey memory _key, uint128 _rewardRate, uint128 _bonusRewardRate) external;
}
/IV4Gauge.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {IncentiveKey} from '@switchx/v4-farming/contracts/base/IncentiveKey.sol';
import {IERC20Minimal} from '@switchx/v4-core/contracts/interfaces/IERC20Minimal.sol';
import {IV4Pool} from '@switchx/v4-core/contracts/interfaces/IV4Pool.sol';
interface IV4Gauge {
error NotVoterOrOwner();
function notifyRewardAmount(uint256 _emissionsAmount) external;
function killGauge() external;
function periodEnd() external view returns (uint256);
function key() external view returns (IERC20Minimal rewardToken, IERC20Minimal bonusRewardToken, IV4Pool pool, uint256 nonce);
}
/ISWITCH.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface ISWITCH is IERC20 {
error NotMinter();
error CapExceeded();
error EmissionBudgetExceeded();
event MinterSet(address indexed previousMinter, address indexed newMinter);
function cap() external view returns (uint256);
function emissionBudget() external view returns (uint256);
function emittedSupply() external view returns (uint256);
function minter() external view returns (address);
function mint(address, uint) external;
function burn(uint256 value) external;
function burnFrom(address account, uint256 value) external;
function setMinter(address minter) external;
}
/IReward.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IReward {
event Deposit(uint256 _period, uint256 _amount, uint256 _tokenId);
event Withdraw(uint256 _period, uint256 _amount, uint256 _tokenId);
event NotifyReward(uint256 _period, address _from, address _token, uint256 amount);
event IncentivizedReward(uint256 _period, address _from, address _token, uint256 amount);
event ZeroVoteIncentivesRolledOver(uint256 _fromPeriod, uint256 _toPeriod, address _token, uint256 amount);
event ClaimReward(uint256 _period, uint256 _tokenId, address _token, address _to);
error NotVoter();
error NotWhitelistedRewardToken();
error NotApprovedOrOwner();
error FuturePeriodNotClaimable();
error FuturePeriodNotRecoverable();
error PeriodHasVotes();
/* only voter functions */
function _deposit(uint256 _amount, uint256 _tokenId) external;
function _withdraw(uint256 _amount, uint256 _tokenId) external;
function getRewardForOwner(uint256 _tokenId) external;
function rolloverZeroVoteIncentives(uint256 _period, address[] calldata _tokens) external;
/* only authorized notifier functions*/
function notifyRewardAmount(address _token, uint _amount) external;
/* others */
// function left(address token) external view returns (uint);
}
/IRebaseReward.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IReward} from './IReward.sol';
interface IRebaseReward is IReward {
error NotToken();
}
/IProtocolFeeManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IProtocolFeeManager {
error ZeroAddress();
error UnauthorizedCaller();
error InvalidSlippageConfig();
error InvalidPercentage();
event BuybackConfigUpdated(bool enabled, address targetToken, address router);
event TokenPathUpdated(address indexed token, bytes path);
event FeeProcessed(address indexed tokenIn, uint256 amountIn, address indexed tokenOut, uint256 amountOut);
event SlippageConfigUpdated(uint24 shortTermMaxTick, uint24 longTermMaxTick, uint32 longTermSecondsAgo, bool enabled);
event VoterUpdated(address indexed newVoter);
event BuybackBpsUpdated(uint16 buybackBps);
event SwapFailed(address indexed token, uint256 amount, bytes reason);
struct SlippageConfig {
uint24 shortTermMaxTick;
uint24 longTermMaxTick;
uint32 longTermSecondsAgo;
bool enabled;
}
/// @notice Process the fee token (e.g., swap to reward token) and return the resulting token and amount
/// @param token The input token address
/// @param amount The input token amount transferred to the manager before the call
/// @return buybackToken The address of the swapped token returned to the caller
/// @return buybackAmount The amount of `buybackToken` returned
/// @return passthroughAmount The amount of remaining original token returned (if any)
function handleFee(address token, uint256 amount) external returns (address buybackToken, uint256 buybackAmount, uint256 passthroughAmount);
}
/IMinter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IMinter {
error NotVoter();
error TreasuryRateTooHigh();
error ZeroAddress();
error BudgetExceedsCap();
event Mint(address indexed sender, uint256 toVoter, uint256 toTreasury, uint256 emittedTotal);
function start() external;
function updatePeriod() external returns (bool);
function getCurrentPeriod() external view returns (uint256);
function getEmissionSchedule() external view returns (uint256 startTimestamp, uint256 endTimestamp, uint256 rate, uint256 currentPhase);
function getEmissionPhaseInfo() external view returns (uint256 phase, uint256 phaseStart, uint256 phaseEnd, uint256 phaseRate);
function getRemainingBudget() external view returns (uint256);
}
/IDripVotingReward.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IVotingReward} from './IVotingReward.sol';
/// @title IDripVotingReward
/// @notice Interface for DripVotingReward - a voting reward contract that pools fees and drips a percentage each period
interface IDripVotingReward is IVotingReward {
/* events */
event DripReleased(uint256 indexed period, address indexed token, uint256 releasedAmount, uint256 remainingPool);
event DripRateUpdated(uint16 oldRate, uint16 newRate);
event PoolBalanceToppedUp(uint256 indexed period, address indexed from, address indexed token, uint256 amount);
/* errors */
error InvalidDripRate();
error PendingCatchupSettlement(address token);
/* view functions */
/// @notice Get the total accumulated pool balance for a token (not yet released)
/// @param _token The token address
/// @return The pool balance
function poolBalance(address _token) external view returns (uint256);
/// @notice Get the amount released for a specific period and token
/// @param _period The period number
/// @param _token The token address
/// @return The released amount
function releasedForPeriod(uint256 _period, address _token) external view returns (uint256);
/// @notice Get the current drip rate in basis points (10000 = 100%)
/// @return The drip rate
function dripRate() external view returns (uint16);
/// @notice Get the last period when drip was executed for a token
/// @param _token The token address
/// @return The last drip period
function lastDripPeriod(address _token) external view returns (uint256);
/* admin functions */
/// @notice Set the drip rate (only owner)
/// @dev Reverts with `PendingCatchupSettlement` if any pooled reward token still has pending catch-up periods.
/// Operators must settle backlog first, typically by calling `triggerDrip(token)` in a voted period until
/// `pendingCatchupPeriods(token)` returns zero.
/// @param _newRate New drip rate in basis points (max 10000)
function setDripRate(uint16 _newRate) external;
/// @notice Grant pool top-up role (only owner)
/// @param _account Address that can call `topUpPoolBalance`
function grantTopUpRole(address _account) external;
/// @notice Revoke pool top-up role (only owner)
/// @param _account Address to revoke from pool top-up role
function revokeTopUpRole(address _account) external;
/* public functions */
/// @notice Manually trigger drip release for current period (can be called by anyone)
/// @dev If more than MAX_CATCHUP_PERIODS are pending, call multiple times
/// @param _token The token address to trigger drip for
function triggerDrip(address _token) external;
/// @notice Add rewards directly into pooled drip balance for future periods
/// @dev Restricted to TOP_UP_ROLE. This path bypasses immediate release and bribe scheduling.
/// @param _token The reward token to top up
/// @param _amount The amount to transfer and add to pool balance
function topUpPoolBalance(address _token, uint256 _amount) external;
/// @notice Get the number of periods pending catch-up for a token
/// @param _token The token address
/// @return pending Number of periods pending
/// @return requiresMultipleCalls Whether multiple triggerDrip calls are needed
function pendingCatchupPeriods(address _token) external view returns (uint256 pending, bool requiresMultipleCalls);
}
/IOracleSlippage.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;
interface IOracleSlippage {
function checkOracleSlippage(bytes memory path, uint24 maximumTickDivergence, uint32 secondsAgo) external view;
}
/V4GaugeFactory.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {UUPSUpgradeable} from '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import {Ownable2StepUpgradeable} from '@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol';
import {ERC1967Proxy} from '@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol';
import {IERC1822Proxiable} from '@openzeppelin/contracts/interfaces/draft-IERC1822.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {ERC1967Utils} from '@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol';
import {SafeCast} from '@openzeppelin/contracts/utils/math/SafeCast.sol';
import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import {V4Gauge} from './V4Gauge.sol';
import {IV4EternalFarming} from '@switchx/v4-farming/contracts/interfaces/IV4EternalFarming.sol';
import {IncentiveKey} from '@switchx/v4-farming/contracts/base/IncentiveKey.sol';
import {IV4Pool} from '@switchx/v4-core/contracts/interfaces/IV4Pool.sol';
import {IERC20Minimal} from '@switchx/v4-core/contracts/interfaces/IERC20Minimal.sol';
import {IV4GaugeFactory} from '../interfaces/IV4GaugeFactory.sol';
/// @title V4Gauge factory
/// @notice Factory contract for creating V4Gauge for V4Pool
contract V4GaugeFactory is IV4GaugeFactory, UUPSUpgradeable, Ownable2StepUpgradeable {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
address public implementation;
address public voter;
IV4EternalFarming public eternalFarming;
IERC20Minimal public token;
IERC20Minimal public weth;
EnumerableSet.AddressSet internal gaugeList;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(address _voter, address _eternalFarming, address _token, address _weth, address _initialOwner) public initializer {
__UUPSUpgradeable_init();
__Ownable2Step_init();
__Ownable_init(_initialOwner);
_setImplementation(address(new V4Gauge()));
voter = _voter;
eternalFarming = IV4EternalFarming(_eternalFarming);
token = IERC20Minimal(_token);
weth = IERC20Minimal(_weth);
}
/// @notice Create a new V4Gauge for an V4Pool
/// @param _poolAddress Address of the pool
/// @param _seedAmount Amount of token to seed the gauge
/// @return newGauge Address of the new gauge
function createGauge(address _poolAddress, uint256 _seedAmount) external returns (address) {
if (msg.sender != voter) revert NotVoter();
IV4Pool _pool = IV4Pool(_poolAddress);
IncentiveKey memory _key = IncentiveKey(token, weth, _pool, eternalFarming.numOfIncentives());
IV4EternalFarming.IncentiveParams memory _params;
_params.reward = SafeCast.toUint128(_seedAmount);
IERC20 rewardToken = IERC20(address(token));
rewardToken.safeTransferFrom(msg.sender, address(this), _params.reward);
rewardToken.forceApprove(address(eternalFarming), _params.reward);
// create a new incentive on V4EternalFarming to act as the gauge for an V4Pool
eternalFarming.createEternalFarming(_key, _params, _pool.plugin());
V4Gauge newGauge = V4Gauge(
address(new ERC1967Proxy(implementation, abi.encodeCall(V4Gauge.initialize, (address(this), address(eternalFarming), voter, _key, owner()))))
);
gaugeList.add(address(newGauge));
return address(newGauge);
}
function setImplementation(address _newImplementation) external onlyOwner {
_setImplementation(_newImplementation);
}
/// @notice Set emission rates via V4Gauge
/// @dev V4GaugeFactory should have role keccak256('INCENTIVE_MAKER_ROLE') for setting rates
/// @param _rewardRate token emissions per second
/// @param _bonusRewardRate weth emissions per second
function setRates(IncentiveKey memory _key, uint128 _rewardRate, uint128 _bonusRewardRate) external {
if (gaugeList.contains(msg.sender) == false) revert NotGauge();
eternalFarming.setRates(_key, _rewardRate, _bonusRewardRate);
}
function _setImplementation(address _newImplementation) internal {
if (_newImplementation == address(0)) revert ZeroAddress();
if (_isCompatibleImplementation(_newImplementation) == false) revert InvalidImplementation(_newImplementation);
address oldImplementation = implementation;
implementation = _newImplementation;
emit ImplementationUpdated(oldImplementation, _newImplementation);
}
function _isCompatibleImplementation(address _implementation) internal view returns (bool) {
if (_implementation.code.length == 0) {
return false;
}
try IERC1822Proxiable(_implementation).proxiableUUID() returns (bytes32 slot) {
return slot == ERC1967Utils.IMPLEMENTATION_SLOT;
} catch {
return false;
}
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
// --- Storage gap for future upgrades ---
uint256[50] private __gap;
}
/V4Gauge.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {UUPSUpgradeable} from '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import {Ownable2StepUpgradeable} from '@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {SafeCast} from '@openzeppelin/contracts/utils/math/SafeCast.sol';
import {PeriodLibrary} from '../libraries/PeriodLibrary.sol';
import {V4GaugeFactory} from './V4GaugeFactory.sol';
import {IncentiveKey} from '@switchx/v4-farming/contracts/base/IncentiveKey.sol';
import {IncentiveId} from '@switchx/v4-farming/contracts/libraries/IncentiveId.sol';
import {IV4EternalFarming} from '@switchx/v4-farming/contracts/interfaces/IV4EternalFarming.sol';
import {IV4EternalVirtualPool} from '@switchx/v4-farming/contracts/interfaces/IV4EternalVirtualPool.sol';
import {IVoter} from '../interfaces/IVoter.sol';
import {IV4Gauge} from '../interfaces/IV4Gauge.sol';
/// @title Intermediary gauge wrapper for V4EternalFarming
/// @notice Distribute emissions to V4EternalFarming
contract V4Gauge is IV4Gauge, UUPSUpgradeable, Ownable2StepUpgradeable {
using SafeERC20 for IERC20;
V4GaugeFactory public v4GaugeFactory;
IV4EternalFarming public eternalFarming;
IVoter public voter;
/// @notice Unique key for each gauge
/// @dev rewardToken is token emissions token
/// @dev bonusRewardToken is a bonus rewards token
IncentiveKey public override key;
/// @notice the timestamp emissions end for current period
uint256 public override periodEnd;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(
address _v4GaugeFactory,
address _eternalFarming,
address _voter,
IncentiveKey memory _key,
address _initialOwner
) public initializer {
__UUPSUpgradeable_init();
__Ownable2Step_init();
__Ownable_init(_initialOwner);
v4GaugeFactory = V4GaugeFactory(_v4GaugeFactory);
eternalFarming = IV4EternalFarming(_eternalFarming);
voter = IVoter(_voter);
key = _key;
}
/// @notice Notify token emissions only per period
function notifyRewardAmount(uint256 _emissionsAmount) external {
if (msg.sender != address(voter) && msg.sender != owner()) revert NotVoterOrOwner();
_notifyRewardAmount(_emissionsAmount, 0);
}
/// @notice Set reward rates to 0 when gauge is killed
function killGauge() external {
if (msg.sender != address(voter) && msg.sender != owner()) revert NotVoterOrOwner();
// after rates are set to 0 the pending rewards in V4EternalFarming can be removed with role keccak256('FARMINGS_ADMINISTRATOR_ROLE')
v4GaugeFactory.setRates(key, 0, 0);
}
/// @dev Possible to add a new notifyRewardAmount function to notify bonus rewards in the future
function _notifyRewardAmount(uint256 _rewardAmount, uint256 _bonusRewardAmount) internal {
uint256 periodNext = PeriodLibrary.periodNext(block.timestamp);
uint256 duration = periodNext - block.timestamp;
address eternalFarmingAddress = address(eternalFarming);
IERC20 rewardToken = IERC20(address(key.rewardToken));
IERC20 bonusRewardToken = IERC20(address(key.bonusRewardToken));
// transfers token emissions to V4Gauge
rewardToken.safeTransferFrom(msg.sender, address(this), _rewardAmount);
// optionally transfer bonus rewards
if (_bonusRewardAmount > 0) {
bonusRewardToken.safeTransferFrom(msg.sender, address(this), _bonusRewardAmount);
}
rewardToken.forceApprove(eternalFarmingAddress, _rewardAmount);
bonusRewardToken.forceApprove(eternalFarmingAddress, _bonusRewardAmount);
// add emissions to V4EternalFarming
IV4EternalFarming(eternalFarmingAddress).addRewards(key, SafeCast.toUint128(_rewardAmount), SafeCast.toUint128(_bonusRewardAmount));
// get remaining emissions in current period
(, , address virtualPoolAddress, , , ) = IV4EternalFarming(eternalFarmingAddress).incentives(IncentiveId.compute(key));
(uint128 rewardRate0, uint128 rewardRate1) = IV4EternalVirtualPool(virtualPoolAddress).rewardRates();
// set emission rates per second till next period
uint256 newRewardRate0;
uint256 newRewardRate1;
if (periodEnd > block.timestamp) {
// if period is not over add remaining rewards and update rates
newRewardRate0 = (_rewardAmount + uint256(rewardRate0) * duration) / duration;
newRewardRate1 = (_bonusRewardAmount + uint256(rewardRate1) * duration) / duration;
} else {
// if period is over set new rates
newRewardRate0 = _rewardAmount / duration;
newRewardRate1 = _bonusRewardAmount / duration;
}
v4GaugeFactory.setRates(key, SafeCast.toUint128(newRewardRate0), SafeCast.toUint128(newRewardRate1));
periodEnd = periodNext;
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
// --- Storage gap for future upgrades ---
uint256[50] private __gap;
}
/Path.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import './BytesLib.sol';
/// @title Functions for manipulating path data for multihop swaps
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
library Path {
using BytesLib for bytes;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The offset of a custom pool deployer address
uint256 private constant DEPLOYER_OFFSET = ADDR_SIZE;
/// @dev The offset of a single token address + deployer address
uint256 private constant NEXT_OFFSET = ADDR_SIZE + DEPLOYER_OFFSET;
/// @dev The offset of an encoded pool key
uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
/// @dev The minimum length of an encoding that contains 2 or more pools
uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
/// @notice Returns true if the path contains two or more pools
/// @param path The encoded swap path
/// @return True if path contains two or more pools, otherwise false
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}
/// @notice Returns the number of pools in the path
/// @param path The encoded swap path
/// @return The number of pools in the path
function numPools(bytes memory path) internal pure returns (uint256) {
// Ignore the first token address. From then on every token offset indicates a pool.
return ((path.length - ADDR_SIZE) / NEXT_OFFSET);
}
/// @notice Decodes the first pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return deployer The address of the custom pool deployer
/// @return tokenB The second token of the given pool
function decodeFirstPool(
bytes memory path
) internal pure returns (address tokenA, address deployer, address tokenB) {
tokenA = path.toAddress(0);
deployer = path.toAddress(DEPLOYER_OFFSET);
tokenB = path.toAddress(NEXT_OFFSET);
}
/// @notice Gets the segment corresponding to the first pool in the path
/// @param path The bytes encoded swap path
/// @return The segment containing all data necessary to target the first pool in the path
function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
return path.slice(0, POP_OFFSET);
}
/// @notice Skips a token element from the buffer and returns the remainder
/// @param path The swap path
/// @return The remaining token elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
}
/BytesLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/**
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <goncalo.sa@consensys.net>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity >=0.8.0 <0.9.0;
library BytesLib {
function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
unchecked {
require(_length + 31 >= _length, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
unchecked {
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
}
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
unchecked {
require(_start + 3 >= _start, 'toUint24_overflow');
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
}
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
}
/ISwapRouter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@switchx/v4-core/contracts/interfaces/callback/IV4SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via V4
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface ISwapRouter is IV4SwapCallback {
struct ExactInputSingleParams {
bytes pluginData;
address tokenIn;
address tokenOut;
address deployer;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 limitSqrtPrice;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes[] pluginData;
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
bytes pluginData;
address tokenIn;
address tokenOut;
address deployer;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 limitSqrtPrice;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @dev If native token is used as input, this function should be accompanied by a `refundNativeToken` in multicall to avoid potential loss of native tokens
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes[] pluginData;
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @dev If native token is used as input, this function should be accompanied by a `refundNativeToken` in multicall to avoid potential loss of native tokens
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @dev Unlike standard swaps, handles transferring from user before the actual swap.
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingleSupportingFeeOnTransferTokens(
ExactInputSingleParams calldata params
) external payable returns (uint256 amountOut);
}
/IPoolInitializer.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V4 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @param data Data for plugin initialization
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
address deployer,
uint160 sqrtPriceX96,
bytes calldata data
) external payable returns (address pool);
}
/IERC721Permit.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain separator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
/IncentiveId.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.6;
import '../base/IncentiveKey.sol';
library IncentiveId {
/// @notice Calculate the key for a farming incentive
/// @param key The components used to compute the incentive identifier
/// @return incentiveId The identifier for the incentive
function compute(IncentiveKey memory key) internal pure returns (bytes32 incentiveId) {
return keccak256(abi.encode(key));
}
}
/IV4EternalVirtualPool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
import '@switchx/v4-base-plugin/contracts/interfaces/IV4VirtualPool.sol';
/// @title V4 eternal virtual pool interface
/// @notice Used to track active liquidity in farming and distribute rewards
interface IV4EternalVirtualPool is IV4VirtualPool {
error onlyPlugin();
error onlyFarming();
/// @notice Returns address of the V4EternalFarming
function farmingAddress() external view returns (address);
/// @notice Returns address of the plugin for which this virtual pool was created
function plugin() external view returns (address);
/// @notice Returns data associated with a tick
function ticks(
int24 tickId
)
external
view
returns (
uint256 liquidityTotal,
int128 liquidityDelta,
int24 prevTick,
int24 nextTick,
uint256 outerFeeGrowth0Token,
uint256 outerFeeGrowth1Token
);
/// @notice Returns the current liquidity in virtual pool
function currentLiquidity() external view returns (uint128);
/// @notice Returns the current tick in virtual pool
function globalTick() external view returns (int24);
/// @notice Returns the timestamp after previous virtual pool update
function prevTimestamp() external view returns (uint32);
/// @notice Returns true if virtual pool is deactivated
function deactivated() external view returns (bool);
/// @dev This function is called when anyone changes their farmed liquidity. The position in a virtual pool should be changed accordingly.
/// If the virtual pool is deactivated, does nothing.
/// @param bottomTick The bottom tick of a position
/// @param topTick The top tick of a position
/// @param liquidityDelta The amount of liquidity in a position
/// @param currentTick The current tick in the main pool
function applyLiquidityDeltaToPosition(int24 bottomTick, int24 topTick, int128 liquidityDelta, int24 currentTick) external;
/// @dev This function is called by farming to increase rewards per liquidity accumulator.
/// Can only be called by farming
function distributeRewards() external;
/// @notice Change reward rates
/// @param rate0 The new rate of main token distribution per sec
/// @param rate1 The new rate of bonus token distribution per sec
function setRates(uint128 rate0, uint128 rate1) external;
/// @notice This function is used to deactivate virtual pool
/// @dev Can only be called by farming
function deactivate() external;
/// @notice Top up rewards reserves
/// @param token0Amount The amount of token0
/// @param token1Amount The amount of token1
function addRewards(uint128 token0Amount, uint128 token1Amount) external;
/// @notice Withdraw rewards from reserves directly
/// @param token0Amount The amount of token0
/// @param token1Amount The amount of token1
function decreaseRewards(uint128 token0Amount, uint128 token1Amount) external;
/// @notice Retrieves rewards growth data inside specified range
/// @dev Should only be used for relative comparison of the same range over time
/// @param bottomTick The lower tick boundary of the range
/// @param topTick The upper tick boundary of the range
/// @return rewardGrowthInside0 The all-time reward growth in token0, per unit of liquidity, inside the range's tick boundaries
/// @return rewardGrowthInside1 The all-time reward growth in token1, per unit of liquidity, inside the range's tick boundaries
function getInnerRewardsGrowth(int24 bottomTick, int24 topTick) external view returns (uint256 rewardGrowthInside0, uint256 rewardGrowthInside1);
/// @notice Get reserves of rewards in one call
/// @return reserve0 The reserve of token0
/// @return reserve1 The reserve of token1
function rewardReserves() external view returns (uint128 reserve0, uint128 reserve1);
/// @notice Get rates of rewards in one call
/// @return rate0 The rate of token0, rewards / sec
/// @return rate1 The rate of token1, rewards / sec
function rewardRates() external view returns (uint128 rate0, uint128 rate1);
/// @notice Get reward growth accumulators
/// @return rewardGrowth0 The reward growth for reward0, per unit of liquidity, has only relative meaning
/// @return rewardGrowth1 The reward growth for reward1, per unit of liquidity, has only relative meaning
function totalRewardGrowth() external view returns (uint256 rewardGrowth0, uint256 rewardGrowth1);
}
/IV4EternalFarming.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
import '@switchx/v4-core/contracts/interfaces/IV4Factory.sol';
import '@switchx/v4-periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '../base/IncentiveKey.sol';
/// @title V4 Eternal Farming Interface
/// @notice Allows farming nonfungible liquidity tokens in exchange for reward tokens without locking NFT for incentive time
interface IV4EternalFarming {
/// @notice Lock mode for auto-locked rewards. Unset (0) is the default for unconfigured pools.
/// Once set to MaxLock or BurnLock, the mode is immutable for that pool.
enum LockMode {
Unset, // 0 - not yet configured (default zero value)
MaxLock, // 1 - decaying lock, withdrawable after expiry
BurnLock // 2 - permanent, irreversible burn lock with 2x voting power
}
/// @notice Details of the incentive to create
struct IncentiveParams {
uint128 reward; // The amount of reward tokens to be distributed
uint128 bonusReward; // The amount of bonus reward tokens to be distributed
uint128 rewardRate; // The rate of reward distribution per second
uint128 bonusRewardRate; // The rate of bonus reward distribution per second
uint24 minimalPositionWidth; // The minimal allowed width of position (tickUpper - tickLower)
}
error farmDoesNotExist();
error tokenAlreadyFarmed();
error incentiveNotExist();
error incentiveStopped();
error anotherFarmingIsActive();
error pluginNotConnected();
error minimalPositionWidthTooWide();
error zeroRewardAmount();
error positionIsTooNarrow();
error zeroLiquidity();
error invalidPool();
error claimToZeroAddress();
error invalidTokenAmount();
error callerIsNotFarmingCenter();
error unauthorizedCaller();
error addressUnchanged();
error statusUnchanged();
error invalidRewardTransfer();
error emergencyActivated();
error reentrancyLock();
error poolReentrancyLock();
error invalidAutoLockPercentage();
error votingEscrowNotSet();
error autoLockManagerNotSet();
error lockModeImmutable();
/// @notice Returns hash of 'INCENTIVE_MAKER_ROLE', used as role for incentive creation
function INCENTIVE_MAKER_ROLE() external view returns (bytes32);
/// @notice Returns hash of 'FARMINGS_ADMINISTRATOR_ROLE', used as role for permissioned actions in farming
function FARMINGS_ADMINISTRATOR_ROLE() external view returns (bytes32);
/// @notice Returns hash of 'AUTO_LOCK_EXEMPT_ROLE', used as role for addresses exempt from farm-level auto-locking
function AUTO_LOCK_EXEMPT_ROLE() external view returns (bytes32);
/// @notice Returns the maximum auto-lock percentage in basis points (10000 = 100%)
function MAX_AUTO_LOCK_PERCENTAGE() external view returns (uint16);
/// @notice Returns whether an account is exempt from farm-level auto-locking
function isAutoLockExempt(address account) external view returns (bool);
/// @notice The nonfungible position manager with which this farming contract is compatible
function nonfungiblePositionManager() external view returns (INonfungiblePositionManager);
/// @notice Returns the V4Factory used for access control
function factory() external view returns (IV4Factory);
/// @notice Represents a farming incentive
/// @param incentiveId The ID of the incentive computed from its parameters
function incentives(
bytes32 incentiveId
)
external
view
returns (
uint128 totalReward,
uint128 bonusReward,
address virtualPoolAddress,
uint24 minimalPositionWidth,
bool deactivated,
address pluginAddress
);
/// @notice Check if incentive is deactivated (manually or automatically)
/// @dev Does not check if the incentive is indeed currently connected to the V4 pool or not
/// @param incentiveId The ID of the incentive computed from its parameters
/// @return True if incentive is deactivated (manually or automatically)
function isIncentiveDeactivated(bytes32 incentiveId) external view returns (bool);
/// @notice Returns address of current farmingCenter
function farmingCenter() external view returns (address);
/// @notice Users can withdraw liquidity without any checks if active.
function isEmergencyWithdrawActivated() external view returns (bool);
/// @notice Detach incentive from the pool and deactivate it
/// @param key The key of the incentive
function deactivateIncentive(IncentiveKey memory key) external;
/// @notice Add rewards for incentive
/// @param key The key of the incentive
/// @param rewardAmount The amount of token0
/// @param bonusRewardAmount The amount of token1
function addRewards(IncentiveKey memory key, uint128 rewardAmount, uint128 bonusRewardAmount) external;
/// @notice Decrease rewards for incentive and withdraw
/// @param key The key of the incentive
/// @param rewardAmount The amount of token0
/// @param bonusRewardAmount The amount of token1
function decreaseRewardsAmount(IncentiveKey memory key, uint128 rewardAmount, uint128 bonusRewardAmount) external;
/// @notice Changes `isEmergencyWithdrawActivated`. Users can withdraw liquidity without any checks if activated.
/// User cannot enter to farmings if activated.
/// _Must_ only be used in emergency situations. Farmings may be unusable after activation.
/// @dev only farmings administrator
/// @param newStatus The new status of `isEmergencyWithdrawActivated`.
function setEmergencyWithdrawStatus(bool newStatus) external;
/// @notice Returns amount of created incentives
function numOfIncentives() external view returns (uint256);
/// @notice Returns free (unlocked) reward tokens owed to a given address according to the last time all farms were updated
/// @dev This returns only the free portion. Use claimable() to see both free and locked amounts.
/// @param owner The owner for which the rewards owed are checked
/// @param rewardToken The token for which to check rewards
/// @return rewardsOwed The amount of free (unlocked) reward tokens claimable by the owner
function rewards(address owner, IERC20Minimal rewardToken) external view returns (uint256 rewardsOwed);
/// @notice Updates farming center address
/// @param _farmingCenter The new farming center contract address
function setFarmingCenterAddress(address _farmingCenter) external;
/// @notice Returns the address of the VotingEscrow contract
function votingEscrow() external view returns (address);
/// @notice Returns the shared auto-lock manager
function autoLockManager() external view returns (address);
/// @notice Returns the auto-lock percentage
/// @param pool The pool address
function getAutoLockPercentage(address pool) external view returns (uint16);
/// @notice Returns the full auto-lock configuration for a pool
/// @param pool The pool address
/// @return percentage The auto-lock percentage in basis points
/// @return enabled Whether the per-pool override is enabled
/// @return lockMode The lock mode (MaxLock or BurnLock)
function autoLockConfigByPool(address pool) external view returns (uint16 percentage, bool enabled, LockMode lockMode);
/// @notice Returns the full auto-lock configuration for a pool (typed return)
/// @param pool The pool address
/// @return percentage The auto-lock percentage in basis points
/// @return enabled Whether the pool-specific percentage override is enabled
/// @return lockMode The explicitly configured lock mode, or Unset when the pool has not been configured yet
function getAutoLockConfig(address pool) external view returns (uint16 percentage, bool enabled, LockMode lockMode);
/// @notice Returns the default auto-lock percentage used when pool is unset
function defaultAutoLockPercentage() external view returns (uint16);
/// @notice Returns free, aggregate locked, and total claimable rewards for a user and token
/// @param owner The user address
/// @param rewardToken The reward token address
/// @return free The free amount that will be transferred
/// @return locked The aggregate pre-claim locked amount (max-lock plus burn-lock buckets)
/// @return total The sum of free and locked amounts
function claimable(address owner, IERC20Minimal rewardToken) external view returns (uint256 free, uint256 locked, uint256 total);
/// @notice Sets the shared auto-lock manager contract
/// @dev only farmings administrator
function setAutoLockManager(address _autoLockManager) external;
/// @notice Sets the VotingEscrow contract address
/// @param _votingEscrow The address of the VotingEscrow contract
function setVotingEscrow(address _votingEscrow) external;
/// @notice Sets the auto-lock configuration for a pool
/// @param pool The pool
/// @param _percentage The percentage in basis points (0-10000, where 10000 = 100%)
/// @param _enabled Whether the pool-specific percentage override is enabled
/// @param _lockMode The lock mode (MaxLock or BurnLock)
function setAutoLockConfigForPool(IV4Pool pool, uint16 _percentage, bool _enabled, LockMode _lockMode) external;
/// @notice Sets the default auto-lock percentage used when pool is unset
/// @param _percentage The percentage in basis points (0-10000)
function setDefaultAutoLockPercentage(uint16 _percentage) external;
/// @notice enter farming for V4 LP token
/// @param key The key of the incentive for which to enter farming
/// @param tokenId The ID of the token to enter farming
function enterFarming(IncentiveKey memory key, uint256 tokenId) external;
/// @notice exitFarmings for V4 LP token
/// @param key The key of the incentive for which to exit farming
/// @param tokenId The ID of the token to exit farming
/// @param _owner Owner of the token
function exitFarming(IncentiveKey memory key, uint256 tokenId, address _owner) external;
/// @notice Transfers `amountRequested` of accrued FREE `rewardToken` rewards from the contract to the recipient `to`
/// @dev Only for FarmingCenter
/// @param rewardToken The token being distributed as a reward
/// @param from The address of position owner
/// @param to The address where claimed rewards will be sent to
/// @param amountRequested The amount of free reward tokens to claim. Claims all free rewards if set to 0.
/// @return totalClaimed The total amount of rewards claimed
function claimRewardFrom(IERC20Minimal rewardToken, address from, address to, uint256 amountRequested) external returns (uint256 totalClaimed);
/// @notice Transfers `amountRequested` of accrued LOCKED `rewardToken` rewards, locking them in VotingEscrow if active
/// @dev Only for FarmingCenter
/// @param rewardToken The token being distributed as a reward
/// @param from The address of position owner
/// @param to The address where claimed rewards will be sent to (or locked for)
/// @param amountRequested The amount of locked reward tokens to claim. Claims all locked rewards if set to 0.
/// @param lockImmediately If true, attempt immediate VE lock for locked rewards; if false, reserve as credits
/// @return totalClaimed The total amount of rewards claimed
function claimLockedRewardFrom(
IERC20Minimal rewardToken,
address from,
address to,
uint256 amountRequested,
bool lockImmediately
) external returns (uint256 totalClaimed);
/// @notice Transfers specified amounts of FREE and LOCKED `rewardToken` rewards
/// @dev Only for FarmingCenter
/// @param rewardToken The token being distributed as a reward
/// @param from The address of position owner
/// @param to The address where claimed rewards will be sent to
/// @param freeAmountRequested The amount of free reward tokens to claim. Claims all free rewards if set to 0.
/// @param lockedAmountRequested The amount of locked reward tokens to claim. Claims all locked rewards if set to 0.
/// @param lockImmediately If true, attempt immediate VE lock for locked rewards; if false, reserve as credits
/// @return totalClaimed The total amount of rewards claimed (free + locked)
function claimRewardsFrom(
IERC20Minimal rewardToken,
address from,
address to,
uint256 freeAmountRequested,
uint256 lockedAmountRequested,
bool lockImmediately
) external returns (uint256 totalClaimed);
/// @notice Calculates the reward amount that will be received for the given farm
/// @param key The key of the incentive
/// @param tokenId The ID of the token
/// @return reward The reward accrued to the NFT for the given incentive thus far
/// @return bonusReward The bonus reward accrued to the NFT for the given incentive thus far
function getRewardInfo(IncentiveKey memory key, uint256 tokenId) external returns (uint256 reward, uint256 bonusReward);
/// @notice Returns information about a farmed liquidity NFT
/// @param tokenId The ID of the farmed token
/// @param incentiveId The ID of the incentive for which the token is farmed
/// @return liquidity The amount of liquidity in the NFT as of the last time the rewards were computed,
/// @return tickLower The lower tick of position,
/// @return tickUpper The upper tick of position,
/// @return innerRewardGrowth0 The last saved reward0 growth inside position,
/// @return innerRewardGrowth1 The last saved reward1 growth inside position
function farms(
uint256 tokenId,
bytes32 incentiveId
) external view returns (uint128 liquidity, int24 tickLower, int24 tickUpper, uint256 innerRewardGrowth0, uint256 innerRewardGrowth1);
/// @notice Returns connected to pool incentive key
function incentiveKeys(
address poolAddress
) external view returns (IERC20Minimal rewardToken, IERC20Minimal bonusRewardToken, IV4Pool pool, uint256 nonce);
/// @notice Creates a new liquidity farming incentive program
/// @param key Details of the incentive to create
/// @param params Params of incentive
/// @param plugin The address of corresponding plugin
/// @return virtualPool The created virtual pool
function createEternalFarming(IncentiveKey memory key, IncentiveParams memory params, address plugin) external returns (address virtualPool);
/// @notice Change reward rates for incentive
/// @param key The key of incentive
/// @param rewardRate The new rate of main token (token0) distribution per sec
/// @param bonusRewardRate The new rate of bonus token (token1) distribution per sec
function setRates(IncentiveKey memory key, uint128 rewardRate, uint128 bonusRewardRate) external;
/// @notice Collect rewards for tokenId
/// @dev only FarmingCenter
/// @param key The key of incentive
/// @param tokenId The ID of the token to exit farming
/// @param _owner Owner of the token
/// @return reward The amount of main token (token0) collected
/// @param bonusReward The amount of bonus token (token1) collected
function collectRewards(IncentiveKey memory key, uint256 tokenId, address _owner) external returns (uint256 reward, uint256 bonusReward);
/// @notice Event emitted when a liquidity mining incentive has been stopped from the outside
/// @param incentiveId The stopped incentive
event IncentiveDeactivated(bytes32 indexed incentiveId);
/// @notice Event emitted when a V4 LP token has been farmed
/// @param tokenId The unique identifier of an V4 LP token
/// @param incentiveId The incentive in which the token is farming
/// @param liquidity The amount of liquidity farmed
event FarmEntered(uint256 indexed tokenId, bytes32 indexed incentiveId, uint128 liquidity);
/// @notice Event emitted when a V4 LP token exited from farming
/// @param tokenId The unique identifier of an V4 LP token
/// @param incentiveId The incentive in which the token is farming
/// @param rewardAddress The token being distributed as a reward
/// @param bonusRewardToken The token being distributed as a bonus reward
/// @param owner The address where claimed rewards were sent to
/// @param reward The amount of reward tokens to be claimed
/// @param bonusReward The amount of bonus reward tokens to be claimed
event FarmEnded(
uint256 indexed tokenId,
bytes32 indexed incentiveId,
address indexed rewardAddress,
address bonusRewardToken,
address owner,
uint256 reward,
uint256 bonusReward
);
/// @notice Emitted when the farming center is changed
/// @param farmingCenter The farming center after the address was changed
event FarmingCenter(address indexed farmingCenter);
/// @notice Event emitted when rewards were added
/// @param rewardAmount The additional amount of main token
/// @param bonusRewardAmount The additional amount of bonus token
/// @param incentiveId The ID of the incentive for which rewards were added
event RewardsAdded(uint256 rewardAmount, uint256 bonusRewardAmount, bytes32 incentiveId);
/// @notice Event emitted when rewards were decreased
/// @param rewardAmount The withdrawn amount of main token
/// @param bonusRewardAmount The withdrawn amount of bonus token
/// @param incentiveId The ID of the incentive for which rewards were decreased
event RewardAmountsDecreased(uint256 rewardAmount, uint256 bonusRewardAmount, bytes32 incentiveId);
/// @notice Event emitted when a reward token has been claimed
/// @param to The address where claimed rewards were sent to
/// @param reward The amount of reward tokens claimed
/// @param rewardAddress The token reward address
/// @param owner The address where claimed rewards were claimed from
event RewardClaimed(address indexed to, uint256 reward, address indexed rewardAddress, address indexed owner);
/// @notice Event emitted when reward rates were changed
/// @param rewardRate The new rate of main token (token0) distribution per sec
/// @param bonusRewardRate The new rate of bonus token (token1) distribution per sec
/// @param incentiveId The ID of the incentive for which rates were changed
event RewardsRatesChanged(uint128 rewardRate, uint128 bonusRewardRate, bytes32 incentiveId);
/// @notice Event emitted when rewards were collected
/// @param tokenId The ID of the token for which rewards were collected
/// @param incentiveId The ID of the incentive for which rewards were collected
/// @param rewardAmount Collected amount of reward
/// @param bonusRewardAmount Collected amount of bonus reward
event RewardsCollected(uint256 tokenId, bytes32 incentiveId, uint256 rewardAmount, uint256 bonusRewardAmount);
/// @notice Event emitted when a liquidity mining incentive has been created
/// @param rewardToken The token being distributed as a reward
/// @param bonusRewardToken The token being distributed as a bonus reward
/// @param pool The V4 pool
/// @param virtualPool The virtual pool address
/// @param nonce The nonce of new farming
/// @param reward The amount of reward tokens to be distributed
/// @param bonusReward The amount of bonus reward tokens to be distributed
/// @param minimalAllowedPositionWidth The minimal allowed position width (tickUpper - tickLower)
event EternalFarmingCreated(
IERC20Minimal indexed rewardToken,
IERC20Minimal indexed bonusRewardToken,
IV4Pool indexed pool,
address virtualPool,
uint256 nonce,
uint256 reward,
uint256 bonusReward,
uint24 minimalAllowedPositionWidth
);
/// @notice Emitted when status of `isEmergencyWithdrawActivated` changes
/// @param newStatus New value of `isEmergencyWithdrawActivated`. Users can withdraw liquidity without any checks if active.
event EmergencyWithdraw(bool newStatus);
/// @notice Event emitted when the VotingEscrow address is set
/// @param votingEscrow The new VotingEscrow contract address
event VotingEscrowSet(address indexed votingEscrow);
/// @notice Event emitted when the shared auto-lock manager address is set
/// @param autoLockManager The new auto-lock manager contract address
event AutoLockManagerSet(address indexed autoLockManager);
/// @notice Event emitted when a pool's auto-lock configuration is set
/// @param pool The pool address
/// @param percentage The auto-lock percentage in basis points
/// @param enabled Whether the per-pool override is enabled
/// @param lockMode The lock mode (MaxLock or BurnLock)
event AutoLockPoolConfigSet(address indexed pool, uint16 percentage, bool enabled, LockMode lockMode);
/// @notice Event emitted when the default auto-lock percentage is set
/// @param percentage The default auto-lock percentage in basis points
event DefaultAutoLockPercentageSet(uint16 percentage);
/// @notice Event emitted when farm-level auto-lock exemption is updated
/// @param target Address updated
/// @param status New exemption status
event AutoLockExemptSet(address indexed target, bool status);
}
/IncentiveKey.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.6;
pragma abicoder v2;
import '@switchx/v4-core/contracts/interfaces/IERC20Minimal.sol';
import '@switchx/v4-core/contracts/interfaces/IV4Pool.sol';
/// @param rewardToken The token being distributed as a reward (token0)
/// @param bonusRewardToken The bonus token being distributed as a reward (token1)
/// @param pool The V4 pool
/// @param nonce The nonce of incentive
struct IncentiveKey {
IERC20Minimal rewardToken;
IERC20Minimal bonusRewardToken;
IV4Pool pool;
uint256 nonce;
}
/vault/IV4VaultFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the V4 Vault Factory
/// @notice This contract can be used for automatic vaults creation
/// @dev Version: V4 Dex
interface IV4VaultFactory {
/// @notice Emitted when a vault is created for a pool
/// @param communityFeeVault The address of the community fee vault
/// @param pool The address of the V4 Dex pool
/// @param creator The address of the creator
/// @param deployer The address of the deployer
/// @param token0 The address of the first token
/// @param token1 The address of the second token
event VaultCreated(
address indexed communityFeeVault,
address indexed pool,
address indexed creator,
address deployer,
address token0,
address token1
);
/// @notice Emitted when the default v4 fee manager is changed
/// @param v4FeeManager The new default v4 fee manager
event DefaultV4FeeManager(address v4FeeManager);
/// @notice Thrown when a vault is already created for a pool
error vaultAlreadyExists();
/// @notice Thrown when an address input/configuration is invalid
error InvalidAddress();
/// @notice Thrown when caller lacks required administrator/factory permission
error OnlyAdministrator();
/// @notice returns address of the community fee vault for the pool
/// @param pool the address of V4 Dex pool
/// @return communityFeeVault the address of community fee vault
function getVaultForPool(address pool) external view returns (address communityFeeVault);
/// @notice creates the community fee vault for the pool if needed
/// @param pool the address of V4 Dex pool
/// @return communityFeeVault the address of community fee vault
function createVaultForPool(
address pool,
address creator,
address deployer,
address token0,
address token1
) external returns (address communityFeeVault);
/// @notice Sets default v4 fee manager applied to newly created community vaults
/// @param newV4FeeManager The default manager address (zero address clears explicit default)
function setDefaultV4FeeManager(address newV4FeeManager) external;
}
/vault/IV4CommunityVault.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the V4 community fee vault
/// @notice Community fee from pools is sent here, if it is enabled
/// @dev Version: V4 Dex
interface IV4CommunityVault {
/// @notice Event emitted when a fees has been claimed
/// @param token The address of token fee
/// @param to The address where claimed rewards were sent to
/// @param amount The amount of fees tokens claimed by communityFeeReceiver
event TokensWithdrawal(address indexed token, address indexed to, uint256 amount);
/// @notice Event emitted when a fees has been claimed
/// @param token The address of token fee
/// @param to The address where claimed rewards were sent to
/// @param amount The amount of fees tokens claimed by V4
event V4TokensWithdrawal(address indexed token, address indexed to, uint256 amount);
/// @notice Emitted when a V4FeeReceiver address changed
/// @param newV4FeeReceiver New V4 fee receiver address
event V4FeeReceiver(address newV4FeeReceiver);
/// @notice Emitted when a V4FeeManager address change proposed
/// @param pendingV4FeeManager New pending V4 fee manager address
event PendingV4FeeManager(address pendingV4FeeManager);
/// @notice Emitted when a new V4 fee value proposed
/// @param proposedNewV4Fee The new proposed V4 fee value
event V4FeeProposal(uint16 proposedNewV4Fee);
/// @notice Emitted when a V4 fee proposal canceled
event CancelV4FeeProposal();
/// @notice Emitted when a V4FeeManager address changed
/// @param newV4FeeManager New V4 fee manager address
event V4FeeManager(address newV4FeeManager);
/// @notice Emitted when the V4 fee is changed
/// @param newV4Fee The new V4 fee value
event V4Fee(uint16 newV4Fee);
/// @notice Emitted when a CommunityFeeReceiver address changed
/// @param newCommunityFeeReceiver New fee receiver address
event CommunityFeeReceiver(address newCommunityFeeReceiver);
error InvalidAddress();
/// @notice Current community fee receiver
function communityFeeReceiver() external view returns (address);
/// @notice Current v4 fee receiver
function v4FeeReceiver() external view returns (address);
/// @notice Current v4 fee in thousandths (1000 = 100%)
function v4Fee() external view returns (uint16);
/// @notice Whether a v4 fee proposal is currently active
function hasNewV4FeeProposal() external view returns (bool);
/// @notice Withdraw protocol fees from vault
/// @dev Can only be called by v4FeeManager or communityFeeReceiver
/// @param token The token address
/// @param amount The amount of token
function withdraw(address token, uint256 amount) external;
struct WithdrawTokensParams {
address token;
uint256 amount;
}
/// @notice Withdraw protocol fees from vault. Used to claim fees for multiple tokens
/// @dev Can be called by v4FeeManager or communityFeeReceiver
/// @param params Array of WithdrawTokensParams objects containing token addresses and amounts to withdraw
function withdrawTokens(WithdrawTokensParams[] calldata params) external;
// ### V4 factory owner permissioned actions ###
/// @notice Accepts the proposed new V4 fee
/// @dev Can only be called by the factory owner.
/// The new value will also be used for previously accumulated tokens that have not yet been withdrawn
/// @param newV4Fee New V4 fee value
function acceptV4FeeChangeProposal(uint16 newV4Fee) external;
/// @notice Change community fee receiver address
/// @dev Can only be called by the factory owner
/// @param newCommunityFeeReceiver New community fee receiver address
function changeCommunityFeeReceiver(address newCommunityFeeReceiver) external;
// ### V4 fee manager permissioned actions ###
/// @notice Transfers V4 fee manager role
/// @param _newV4FeeManager new V4 fee manager address
function transferV4FeeManagerRole(address _newV4FeeManager) external;
/// @notice accept V4 FeeManager role
function acceptV4FeeManagerRole() external;
/// @notice Proposes new V4 fee value for protocol
/// @dev the new value will also be used for previously accumulated tokens that have not yet been withdrawn
/// @param newV4Fee new V4 fee value
function proposeV4FeeChange(uint16 newV4Fee) external;
/// @notice Cancels V4 fee change proposal
function cancelV4FeeChangeProposal() external;
/// @notice Change V4 community fee part receiver
/// @param newV4FeeReceiver The address of new V4 fee receiver
function changeV4FeeReceiver(address newV4FeeReceiver) external;
}
/pool/IV4PoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @dev Important security note: when using this data by external contracts, it is necessary to take into account the possibility
/// of manipulation (including read-only reentrancy).
/// This interface is based on the UniswapV3 interface, credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4PoolState {
/// @notice Safely get most important state values of V4 Dex AMM
/// @dev Several values exposed as a single method to save gas when accessed externally.
/// **Important security note: this method checks reentrancy lock and should be preferred in most cases**.
/// @return sqrtPrice The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return tick The current global tick of the pool. May not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return activeLiquidity The currently in-range liquidity available to the pool
/// @return nextTick The next initialized tick after current global tick
/// @return previousTick The previous initialized tick before (or at) current global tick
function safelyGetStateOfAMM()
external
view
returns (uint160 sqrtPrice, int24 tick, uint16 lastFee, uint8 pluginConfig, uint128 activeLiquidity, int24 nextTick, int24 previousTick);
/// @notice Allows to easily get current reentrancy lock status
/// @dev can be used to prevent read-only reentrancy.
/// This method just returns `globalState.unlocked` value
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function isUnlocked() external view returns (bool unlocked);
// ! IMPORTANT security note: the pool state can be manipulated.
// ! The following methods do not check reentrancy lock themselves.
/// @notice The globalState structure in the pool stores many values but requires only one slot
/// and is exposed as a single method to save gas when accessed externally.
/// @dev **important security note: caller should check `unlocked` flag to prevent read-only reentrancy**
/// @return price The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return tick The current tick of the pool, i.e. according to the last tick transition that was run
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return communityFee The community fee represented as a percent of all collected fee in thousandths, i.e. 1e-3 (so 100 is 10%)
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function globalState() external view returns (uint160 price, int24 tick, uint16 lastFee, uint8 pluginConfig, uint16 communityFee, bool unlocked);
/// @notice Look up information about a specific tick in the pool
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param tick The tick to look up
/// @return liquidityTotal The total amount of position liquidity that uses the pool either as tick lower or tick upper
/// @return liquidityDelta How much liquidity changes when the pool price crosses the tick
/// @return prevTick The previous tick in tick list
/// @return nextTick The next tick in tick list
/// @return outerFeeGrowth0Token The fee growth on the other side of the tick from the current tick in token0
/// @return outerFeeGrowth1Token The fee growth on the other side of the tick from the current tick in token1
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(
int24 tick
)
external
view
returns (
uint256 liquidityTotal,
int128 liquidityDelta,
int24 prevTick,
int24 nextTick,
uint256 outerFeeGrowth0Token,
uint256 outerFeeGrowth1Token
);
/// @notice The timestamp of the last sending of community fees to the vault
/// @return The timestamp truncated to 32 bits
function lastCommunityFeeTimestamp() external view returns (uint32);
/// @notice The timestamp of the last sending of plugin fees to the plugin
/// @return The timestamp truncated to 32 bits
function lastPluginFeeTimestamp() external view returns (uint32);
/// @notice The amounts of token0 and token1 that will be sent to the vault
/// @dev Will be sent FEE_TRANSFER_FREQUENCY after lastCommunityFeeTimestamp
/// @return communityFeePending0 The amount of token0 that will be sent to the vault
/// @return communityFeePending1 The amount of token1 that will be sent to the vault
function getCommunityFeePending() external view returns (uint128 communityFeePending0, uint128 communityFeePending1);
/// @notice The amounts of token0 and token1 that will be sent to the plugin
/// @dev Will be sent FEE_TRANSFER_FREQUENCY after lastPluginFeeTimestamp
/// @return pluginFeePending0 The amount of token0 that will be sent to the plugin
/// @return pluginFeePending1 The amount of token1 that will be sent to the plugin
function getPluginFeePending() external view returns (uint128 pluginFeePending0, uint128 pluginFeePending1);
/// @notice Returns the address of currently used plugin
/// @dev The plugin is subject to change
/// @return pluginAddress The address of currently used plugin
function plugin() external view returns (address pluginAddress);
/// @notice The contract to which community fees are transferred
/// @return communityVaultAddress The communityVault address
function communityVault() external view returns (address communityVaultAddress);
/// @notice Returns 256 packed tick initialized boolean values. See TickTree for more information
/// @param wordPosition Index of 256-bits word with ticks
/// @return The 256-bits word with packed ticks info
function tickTable(int16 wordPosition) external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
/// @return The fee growth accumulator for token0
function totalFeeGrowth0Token() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
/// @return The fee growth accumulator for token1
function totalFeeGrowth1Token() external view returns (uint256);
/// @notice The current pool fee value
/// @dev In case dynamic fee is enabled in the pool, this method will call the plugin to get the current fee.
/// If the plugin implements complex fee logic, this method may return an incorrect value or revert.
/// In this case, see the plugin implementation and related documentation.
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return currentFee The current pool fee value in hundredths of a bip, i.e. 1e-6
function fee() external view returns (uint16 currentFee);
/// @notice The tracked token0 and token1 reserves of pool
/// @dev If at any time the real balance is larger, the excess will be transferred to liquidity providers as additional fee.
/// If the balance exceeds uint128, the excess will be sent to the communityVault.
/// @return reserve0 The last known reserve of token0
/// @return reserve1 The last known reserve of token1
function getReserves() external view returns (uint128 reserve0, uint128 reserve1);
/// @notice Returns the information about a position by the position's key
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param key The position's key is a packed concatenation of the owner address, bottomTick and topTick indexes
/// @return liquidity The amount of liquidity in the position
/// @return innerFeeGrowth0Token Fee growth of token0 inside the tick range as of the last mint/burn/poke
/// @return innerFeeGrowth1Token Fee growth of token1 inside the tick range as of the last mint/burn/poke
/// @return fees0 The computed amount of token0 owed to the position as of the last mint/burn/poke
/// @return fees1 The computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(
bytes32 key
) external view returns (uint256 liquidity, uint256 innerFeeGrowth0Token, uint256 innerFeeGrowth1Token, uint128 fees0, uint128 fees1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks.
/// Returned value cannot exceed type(uint128).max
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The current in range liquidity
function liquidity() external view returns (uint128);
/// @notice The current tick spacing
/// @dev Ticks can only be initialized by new mints at multiples of this value
/// e.g.: a tickSpacing of 60 means ticks can be initialized every 60th tick, i.e., ..., -120, -60, 0, 60, 120, ...
/// However, tickspacing can be changed after the ticks have been initialized.
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The current tick spacing
function tickSpacing() external view returns (int24);
/// @notice The previous initialized tick before (or at) current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The previous initialized tick
function prevTickGlobal() external view returns (int24);
/// @notice The next initialized tick after current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The next initialized tick
function nextTickGlobal() external view returns (int24);
/// @notice The root of tick search tree
/// @dev Each bit corresponds to one node in the second layer of tick tree: '1' if node has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The root of tick search tree as bitmap
function tickTreeRoot() external view returns (uint32);
/// @notice The second layer of tick search tree
/// @dev Each bit in node corresponds to one node in the leafs layer (`tickTable`) of tick tree: '1' if leaf has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The node of tick search tree second layer
function tickTreeSecondLayer(int16) external view returns (uint256);
}
/pool/IV4PoolPermissionedActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by permissioned addresses
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4PoolPermissionedActions {
/// @notice Set the community's % share of the fees. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newCommunityFee The new community fee percent in thousandths (1e-3)
function setCommunityFee(uint16 newCommunityFee) external;
/// @notice Set the new tick spacing values. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newTickSpacing The new tick spacing value
function setTickSpacing(int24 newTickSpacing) external;
/// @notice Set the new plugin address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newPluginAddress The new plugin address
function setPlugin(address newPluginAddress) external;
/// @notice Set new plugin config. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newConfig In the new configuration of the plugin,
/// each bit of which is responsible for a particular hook.
function setPluginConfig(uint8 newConfig) external;
/// @notice Set new community fee vault address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @dev Community fee vault receives collected community fees.
/// **accumulated but not yet sent to the vault community fees once will be sent to the `newCommunityVault` address**
/// @param newCommunityVault The address of new community fee vault
function setCommunityVault(address newCommunityVault) external;
/// @notice Set new pool fee. Can be called by owner if dynamic fee is disabled.
/// Called by the plugin if dynamic fee is enabled
/// @param newFee The new fee value
function setFee(uint16 newFee) external;
/// @notice Forces balances to match reserves. Excessive tokens will be distributed between active LPs
/// @dev Only plugin can call this function
function sync() external;
/// @notice Forces balances to match reserves. Excessive tokens will be sent to msg.sender
/// @dev Only plugin can call this function
function skim() external;
}
/pool/IV4PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4PoolImmutables {
/// @notice The V4 factory contract, which must adhere to the IV4Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
/pool/IV4PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swaps cannot be emitted by the pool before Initialize
/// @param price The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 price, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed bottomTick,
int24 indexed topTick,
uint128 liquidityAmount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @param owner The owner of the position for which fees are collected
/// @param recipient The address that received fees
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(address indexed owner, address recipient, int24 indexed bottomTick, int24 indexed topTick, uint128 amount0, uint128 amount1);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(address indexed owner, int24 indexed bottomTick, int24 indexed topTick, uint128 liquidityAmount, uint256 amount0, uint256 amount1);
/// @notice Emitted when a plugin fee is applied during a burn
/// @param owner The owner of the position
/// @param pluginFee The fee to be sent to the plugin
event BurnFee(address indexed owner, uint24 pluginFee);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param price The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 price, uint128 liquidity, int24 tick);
/// @notice Emitted by the pool after any swaps
/// @param sender The address that initiated the swap
/// @param overrideFee The fee to be applied to the trade
/// @param pluginFee The fee to be sent to the plugin
event SwapFee(address indexed sender, uint24 overrideFee, uint24 pluginFee);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);
/// @notice Emitted when the pool has higher balances than expected.
/// Any excess of tokens will be distributed between liquidity providers as fee.
/// @dev Fees after flash also will trigger this event due to mechanics of flash.
/// @param amount0 The excess of token0
/// @param amount1 The excess of token1
event ExcessTokens(uint256 amount0, uint256 amount1);
/// @notice Emitted when the community fee is changed by the pool
/// @param communityFeeNew The updated value of the community fee in thousandths (1e-3)
event CommunityFee(uint16 communityFeeNew);
/// @notice Emitted when the tick spacing changes
/// @param newTickSpacing The updated value of the new tick spacing
event TickSpacing(int24 newTickSpacing);
/// @notice Emitted when the plugin address changes
/// @param newPluginAddress New plugin address
event Plugin(address newPluginAddress);
/// @notice Emitted when the plugin config changes
/// @param newPluginConfig New plugin config
event PluginConfig(uint8 newPluginConfig);
/// @notice Emitted when the fee changes inside the pool
/// @param fee The current fee in hundredths of a bip, i.e. 1e-6
event Fee(uint16 fee);
/// @notice Emitted when the community vault address changes
/// @param newCommunityVault New community vault
event CommunityVault(address newCommunityVault);
/// @notice Emitted when the plugin does skim the excess of tokens
/// @param to THe receiver of tokens (plugin)
/// @param amount0 The amount of token0
/// @param amount1 The amount of token1
event Skim(address indexed to, uint256 amount0, uint256 amount1);
/// @notice Emitted when fees are transferred to a recipient (community vault or plugin)
/// @param recipient The address receiving fees (community vault or plugin)
/// @param amount0 The amount of token0 fees transferred
/// @param amount1 The amount of token1 fees transferred
event FeeTransferred(address indexed recipient, uint256 amount0, uint256 amount1);
}
/pool/IV4PoolErrors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
/// @title Errors emitted by a pool
/// @notice Contains custom errors emitted by the pool
/// @dev Custom errors are separated from the common pool interface for compatibility with older versions of Solidity
interface IV4PoolErrors {
// #### pool errors ####
/// @notice Emitted by the reentrancy guard
error locked();
/// @notice Emitted if arithmetic error occurred
error arithmeticError();
/// @notice Emitted if an attempt is made to initialize the pool twice
error alreadyInitialized();
/// @notice Emitted if an attempt is made to mint or swap in uninitialized pool
error notInitialized();
/// @notice Emitted if 0 is passed as amountRequired to swap function
error zeroAmountRequired();
/// @notice Emitted if invalid amount is passed as amountRequired to swap function
error invalidAmountRequired();
/// @notice Emitted if plugin fee param greater than fee/override fee
error incorrectPluginFee();
/// @notice Emitted if the pool received fewer tokens than it should have
error insufficientInputAmount();
/// @notice Emitted if there was an attempt to mint zero liquidity
error zeroLiquidityDesired();
/// @notice Emitted if actual amount of liquidity is zero (due to insufficient amount of tokens received)
error zeroLiquidityActual();
/// @notice Emitted if the pool received fewer tokens0 after flash than it should have
error flashInsufficientPaid0();
/// @notice Emitted if the pool received fewer tokens1 after flash than it should have
error flashInsufficientPaid1();
/// @notice Emitted if limitSqrtPrice param is incorrect
error invalidLimitSqrtPrice();
/// @notice Tick must be divisible by tickspacing
error tickIsNotSpaced();
/// @notice Emitted if a method is called that is accessible only to the factory owner or dedicated role
error notAllowed();
/// @notice Emitted if new tick spacing exceeds max allowed value
error invalidNewTickSpacing();
/// @notice Emitted if new community fee exceeds max allowed value
error invalidNewCommunityFee();
/// @notice Emitted if an attempt is made to manually change the fee value, but dynamic fee is enabled
error dynamicFeeActive();
/// @notice Emitted if an attempt is made by plugin to change the fee value, but dynamic fee is disabled
error dynamicFeeDisabled();
/// @notice Emitted if an attempt is made to change the plugin configuration, but the plugin is not connected
error pluginIsNotConnected();
/// @notice Emitted if an attempt is made to set plugin to zero while there are pending plugin fees
error pluginFeesPendingToCollect();
/// @notice Emitted if an attempt is made to set community vault to zero while there are pending community fees
error communityFeesPendingToCollect();
/// @notice Emitted if a plugin returns invalid selector after hook call
/// @param expectedSelector The expected selector
error invalidHookResponse(bytes4 expectedSelector);
// #### LiquidityMath errors ####
/// @notice Emitted if liquidity underflows
error liquiditySub();
/// @notice Emitted if liquidity overflows
error liquidityAdd();
// #### TickManagement errors ####
/// @notice Emitted if the topTick param not greater then the bottomTick param
error topTickLowerOrEqBottomTick();
/// @notice Emitted if the bottomTick param is lower than min allowed value
error bottomTickLowerThanMIN();
/// @notice Emitted if the topTick param is greater than max allowed value
error topTickAboveMAX();
/// @notice Emitted if the liquidity value associated with the tick exceeds MAX_LIQUIDITY_PER_TICK
error liquidityOverflow();
/// @notice Emitted if an attempt is made to interact with an uninitialized tick
error tickIsNotInitialized();
/// @notice Emitted if there is an attempt to insert a new tick into the list of ticks with incorrect indexes of the previous and next ticks
error tickInvalidLinks();
// #### SafeTransfer errors ####
/// @notice Emitted if token transfer failed internally
error transferFailed();
// #### TickMath errors ####
/// @notice Emitted if tick is greater than the maximum or less than the minimum allowed value
error tickOutOfRange();
/// @notice Emitted if price is greater than the maximum or less than the minimum allowed value
error priceOutOfRange();
}
/pool/IV4PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @dev Initialization should be done in one transaction with pool creation to avoid front-running
/// @param initialPrice The initial sqrt price of the pool as a Q64.96
function initialize(uint160 initialPrice) external;
/// @notice Adds liquidity for the given recipient/bottomTick/topTick position
/// @dev The caller of this method receives a callback in the form of IV4MintCallback#v4MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on bottomTick, topTick, the amount of liquidity, and the current price.
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address for which the liquidity will be created
/// @param bottomTick The lower tick of the position in which to add liquidity
/// @param topTick The upper tick of the position in which to add liquidity
/// @param liquidityDesired The desired amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return liquidityActual The actual minted amount of liquidity
function mint(
address leftoversRecipient,
address recipient,
int24 bottomTick,
int24 topTick,
uint128 liquidityDesired,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1, uint128 liquidityActual);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param bottomTick The lower tick of the position for which to collect fees
/// @param topTick The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 bottomTick,
int24 topTick,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param bottomTick The lower tick of the position for which to burn liquidity
/// @param topTick The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @param data Any data that should be passed through to the plugin
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(int24 bottomTick, int24 topTick, uint128 amount, bytes calldata data) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IV4SwapCallback#v4SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback. If using the Router it should contain SwapRouter#SwapCallbackData
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Swap token0 for token1, or token1 for token0 with prepayment
/// @dev The caller of this method receives a callback in the form of IV4SwapCallback#v4SwapCallback
/// caller must send tokens in callback before swap calculation
/// the actually sent amount of tokens is used for further calculations
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountToSell The amount of the swap, only positive (exact input) amount allowed
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback. If using the Router it should contain SwapRouter#SwapCallbackData
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swapWithPaymentInAdvance(
address leftoversRecipient,
address recipient,
bool zeroToOne,
int256 amountToSell,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IV4FlashCallback#v4FlashCallback
/// @dev All excess tokens paid in the callback are distributed to currently in-range liquidity providers as an additional fee.
/// If there are no in-range liquidity providers, the fee will be transferred to the first active provider in the future
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external;
}
/plugin/IV4PluginFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title An interface for a contract that is capable of deploying V4 plugins
/// @dev Such a factory can be used for automatic plugin creation for new pools.
/// Also a factory be used as an entry point for custom (additional) pools creation
interface IV4PluginFactory {
/// @notice Deploys new plugin contract for pool
/// @param pool The address of the new pool
/// @param creator The address that initiated the pool creation
/// @param deployer The plugin factory address (0 if not used)
/// @param token0 First token of the pool
/// @param token1 Second token of the pool
/// @return New plugin address
function beforeCreatePoolHook(
address pool,
address creator,
address deployer,
address token0,
address token1,
bytes calldata data
) external returns (address);
/// @notice Called after the pool is created
/// @param plugin The plugin address
/// @param pool The address of the new pool
/// @param deployer The plugin factory address (0 if not used)
function afterCreatePoolHook(address plugin, address pool, address deployer) external;
}
/IV4Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
import './pool/IV4PoolImmutables.sol';
import './pool/IV4PoolState.sol';
import './pool/IV4PoolActions.sol';
import './pool/IV4PoolPermissionedActions.sol';
import './pool/IV4PoolEvents.sol';
import './pool/IV4PoolErrors.sol';
/// @title The interface for a V4 Pool
/// @dev The pool interface is broken up into many smaller pieces.
/// This interface includes custom error definitions and cannot be used in older versions of Solidity.
/// For older versions of Solidity use #IV4PoolLegacy
/// Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4Pool is IV4PoolImmutables, IV4PoolState, IV4PoolActions, IV4PoolPermissionedActions, IV4PoolEvents, IV4PoolErrors {
// used only for combining interfaces
}
/IV4Factory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
import './plugin/IV4PluginFactory.sol';
import './vault/IV4VaultFactory.sol';
/// @title The interface for the V4 Factory
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4Factory {
/// @notice Emitted when a process of ownership renounce is started
/// @param timestamp The timestamp of event
/// @param finishTimestamp The timestamp when ownership renounce will be possible to finish
event RenounceOwnershipStart(uint256 timestamp, uint256 finishTimestamp);
/// @notice Emitted when a process of ownership renounce cancelled
/// @param timestamp The timestamp of event
event RenounceOwnershipStop(uint256 timestamp);
/// @notice Emitted when a process of ownership renounce finished
/// @param timestamp The timestamp of ownership renouncement
event RenounceOwnershipFinish(uint256 timestamp);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param pool The address of the created pool
event Pool(address indexed token0, address indexed token1, address pool);
/// @notice Emitted when a pool is created
/// @param deployer The corresponding custom deployer contract
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param pool The address of the created pool
event CustomPool(address indexed deployer, address indexed token0, address indexed token1, address pool);
/// @notice Emitted when the default community fee is changed
/// @param newDefaultCommunityFee The new default community fee value
event DefaultCommunityFee(uint16 newDefaultCommunityFee);
/// @notice Emitted when the default tickspacing is changed
/// @param newDefaultTickspacing The new default tickspacing value
event DefaultTickspacing(int24 newDefaultTickspacing);
/// @notice Emitted when the default fee is changed
/// @param newDefaultFee The new default fee value
event DefaultFee(uint16 newDefaultFee);
/// @notice Emitted when the defaultPluginFactory address is changed
/// @param defaultPluginFactoryAddress The new defaultPluginFactory address
event DefaultPluginFactory(address defaultPluginFactoryAddress);
/// @notice Emitted when the vaultFactory address is changed
/// @param newVaultFactory The new vaultFactory address
event VaultFactory(address newVaultFactory);
/// @notice role that can change communityFee and tickspacing in pools
/// @return The hash corresponding to this role
function POOLS_ADMINISTRATOR_ROLE() external view returns (bytes32);
/// @notice role that can call `createCustomPool` function
/// @return The hash corresponding to this role
function CUSTOM_POOL_DEPLOYER() external view returns (bytes32);
/// @notice Returns `true` if `account` has been granted `role` or `account` is owner.
/// @param role The hash corresponding to the role
/// @param account The address for which the role is checked
/// @return bool Whether the address has this role or the owner role or not
function hasRoleOrOwner(bytes32 role, address account) external view returns (bool);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via transferOwnership(address newOwner)
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the current poolDeployerAddress
/// @return The address of the poolDeployer
function poolDeployer() external view returns (address);
/// @notice Returns the default community fee
/// @return Fee which will be set at the creation of the pool
function defaultCommunityFee() external view returns (uint16);
/// @notice Returns the default fee
/// @return Fee which will be set at the creation of the pool
function defaultFee() external view returns (uint16);
/// @notice Returns the default tickspacing
/// @return Tickspacing which will be set at the creation of the pool
function defaultTickspacing() external view returns (int24);
/// @notice Return the current pluginFactory address
/// @dev This contract is used to automatically set a plugin address in new liquidity pools
/// @return V4 plugin factory
function defaultPluginFactory() external view returns (IV4PluginFactory);
/// @notice Return the current vaultFactory address
/// @dev This contract is used to automatically set a vault address in new liquidity pools
/// @return V4 vault factory
function vaultFactory() external view returns (IV4VaultFactory);
/// @notice Returns the default communityFee, tickspacing, fee and communityFeeVault for pool
/// @return communityFee which will be set at the creation of the pool
/// @return tickSpacing which will be set at the creation of the pool
/// @return fee which will be set at the creation of the pool
function defaultConfigurationForPool() external view returns (uint16 communityFee, int24 tickSpacing, uint16 fee);
/// @notice Deterministically computes the pool address given the token0 and token1
/// @dev The method does not check if such a pool has been created
/// @param token0 first token
/// @param token1 second token
/// @return pool The contract address of the V4 pool
function computePoolAddress(address token0, address token1) external view returns (address pool);
/// @notice Deterministically computes the custom pool address given the customDeployer, token0 and token1
/// @dev The method does not check if such a pool has been created
/// @param customDeployer the address of the custom plugin factory used to namespace pools
/// @param token0 first token
/// @param token1 second token
/// @return customPool The contract address of the V4 pool
function computeCustomPoolAddress(address customDeployer, address token0, address token1) external view returns (address customPool);
/// @notice Returns the pool address for a given pair of tokens, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @return pool The pool address
function poolByPair(address tokenA, address tokenB) external view returns (address pool);
/// @notice Returns the custom pool address for a customDeployer and a given pair of tokens, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param customDeployer The custom plugin factory address used to namespace custom pools
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @return customPool The pool address
function customPoolByPair(address customDeployer, address tokenA, address tokenB) external view returns (address customPool);
/// @notice returns keccak256 of V4Pool init bytecode.
/// @dev the hash value changes with any change in the pool bytecode
/// @return Keccak256 hash of V4Pool contract init bytecode
function POOL_INIT_CODE_HASH() external view returns (bytes32);
/// @return timestamp The timestamp of the beginning of the renounceOwnership process
function renounceOwnershipStartTimestamp() external view returns (uint256 timestamp);
/// @notice Creates a pool for the given two tokens
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param data Data for plugin creation
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
/// The call will revert if the pool already exists or the token arguments are invalid.
/// @return pool The address of the newly created pool
function createPool(address tokenA, address tokenB, bytes calldata data) external returns (address pool);
/// @notice Creates a custom pool for the given two tokens using `deployer` contract
/// @dev `msg.sender` is expected to be the plugin entry point (e.g. V4CustomPoolEntryPoint) that implements
/// IV4PluginFactory hooks. The `deployer` argument is forwarded to that entry point and used as the namespace
/// for deterministic pool address calculation and as the ultimate plugin factory address.
/// @param deployer The address of the custom plugin factory; used for namespacing and forwarded to hooks by the caller
/// @param creator The initiator of custom pool creation
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param data The additional data bytes
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
/// The call will revert if the pool already exists or the token arguments are invalid.
/// @return customPool The address of the newly created custom pool
function createCustomPool(
address deployer,
address creator,
address tokenA,
address tokenB,
bytes calldata data
) external returns (address customPool);
/// @dev updates default community fee for new pools
/// @param newDefaultCommunityFee The new community fee, _must_ be <= MAX_COMMUNITY_FEE
function setDefaultCommunityFee(uint16 newDefaultCommunityFee) external;
/// @dev updates default fee for new pools
/// @param newDefaultFee The new fee, _must_ be <= MAX_DEFAULT_FEE
function setDefaultFee(uint16 newDefaultFee) external;
/// @dev updates default tickspacing for new pools
/// @param newDefaultTickspacing The new tickspacing, _must_ be <= MAX_TICK_SPACING and >= MIN_TICK_SPACING
function setDefaultTickspacing(int24 newDefaultTickspacing) external;
/// @dev updates pluginFactory address
/// @param newDefaultPluginFactory address of new plugin factory
function setDefaultPluginFactory(address newDefaultPluginFactory) external;
/// @dev updates vaultFactory address
/// @param newVaultFactory address of new vault factory
function setVaultFactory(address newVaultFactory) external;
/// @notice Starts process of renounceOwnership. After that, a certain period
/// of time must pass before the ownership renounce can be completed.
function startRenounceOwnership() external;
/// @notice Stops process of renounceOwnership and removes timer.
function stopRenounceOwnership() external;
}
/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
/IERC20Minimal.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Minimal ERC20 interface for V4
/// @notice Contains a subset of the full ERC20 interface that is used in V4
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IERC20Minimal {
/// @notice Returns the balance of a token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/callback/IV4SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IV4PoolActions#swap
/// @notice Any contract that calls IV4PoolActions#swap must implement this interface
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IV4Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method _must_ be checked to be a V4Pool deployed by the canonical V4Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IV4PoolActions#swap call
function v4SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}
/IV4VirtualPool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the virtual pool
/// @dev Used to calculate active liquidity in farmings
interface IV4VirtualPool {
/// @dev This function is called by the main pool if an initialized ticks are crossed by swap.
/// If any one of crossed ticks is also initialized in a virtual pool it should be crossed too
/// @param targetTick The target tick up to which we need to cross all active ticks
/// @param zeroToOne Swap direction
function crossTo(int24 targetTick, bool zeroToOne) external returns (bool success);
}
/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
import {Arrays} from "../Arrays.sol";
import {Math} from "../math/Math.sol";
/**
* @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.
* - Set can be cleared (all elements removed) in O(n).
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* The following types are supported:
*
* - `bytes32` (`Bytes32Set`) since v3.3.0
* - `address` (`AddressSet`) since v3.3.0
* - `uint256` (`UintSet`) since v3.3.0
* - `string` (`StringSet`) since v5.4.0
* - `bytes` (`BytesSet`) since v5.4.0
*
* [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 Removes all the values from a set. O(n).
*
* WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that
* using it may render the function uncallable if the set grows to the point where clearing it consumes too much
* gas to fit in a block.
*/
function _clear(Set storage set) private {
uint256 len = _length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @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;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) private view returns (bytes32[] memory) {
unchecked {
end = Math.min(end, _length(set));
start = Math.min(start, end);
uint256 len = end - start;
bytes32[] memory result = new bytes32[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
// 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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32Set storage set) internal {
_clear(set._inner);
}
/**
* @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;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressSet storage set) internal {
_clear(set._inner);
}
/**
* @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;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintSet storage set) internal {
_clear(set._inner);
}
/**
* @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;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
struct StringSet {
// Storage of set values
string[] _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(string 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(StringSet storage set, string memory value) internal 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(StringSet storage set, string memory value) internal 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) {
string memory 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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(StringSet storage set) internal {
uint256 len = length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(StringSet storage set, string memory value) internal view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(StringSet storage set) internal 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(StringSet storage set, uint256 index) internal view returns (string memory) {
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(StringSet storage set) internal view returns (string[] memory) {
return set._values;
}
/**
* @dev Return a slice of the 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(StringSet storage set, uint256 start, uint256 end) internal view returns (string[] memory) {
unchecked {
end = Math.min(end, length(set));
start = Math.min(start, end);
uint256 len = end - start;
string[] memory result = new string[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
struct BytesSet {
// Storage of set values
bytes[] _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(bytes 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(BytesSet storage set, bytes memory value) internal 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(BytesSet storage set, bytes memory value) internal 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) {
bytes memory 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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(BytesSet storage set) internal {
uint256 len = length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(BytesSet storage set, bytes memory value) internal view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(BytesSet storage set) internal 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(BytesSet storage set, uint256 index) internal view returns (bytes memory) {
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(BytesSet storage set) internal view returns (bytes[] memory) {
return set._values;
}
/**
* @dev Return a slice of the 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(BytesSet storage set, uint256 start, uint256 end) internal view returns (bytes[] memory) {
unchecked {
end = Math.min(end, length(set));
start = Math.min(start, end);
uint256 len = end - start;
bytes[] memory result = new bytes[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
}
/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
(1 << 0x08) | // backspace
(1 << 0x09) | // tab
(1 << 0x0a) | // newline
(1 << 0x0c) | // form feed
(1 << 0x0d) | // carriage return
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(add(buffer, 0x20), length)
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
* RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
* characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
bytes memory output = new bytes(2 * buffer.length); // worst case scenario
uint256 outputLength = 0;
for (uint256 i; i < buffer.length; ++i) {
bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
output[outputLength++] = "\\";
if (char == 0x08) output[outputLength++] = "b";
else if (char == 0x09) output[outputLength++] = "t";
else if (char == 0x0a) output[outputLength++] = "n";
else if (char == 0x0c) output[outputLength++] = "f";
else if (char == 0x0d) output[outputLength++] = "r";
else if (char == 0x5c) output[outputLength++] = "\\";
else if (char == 0x22) {
// solhint-disable-next-line quotes
output[outputLength++] = '"';
}
} else {
output[outputLength++] = char;
}
}
// write the actual length and deallocate unused memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
/SlotDerivation.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.
pragma solidity ^0.8.20;
/**
* @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
* corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
* the solidity language / compiler.
*
* See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
*
* Example usage:
* ```solidity
* contract Example {
* // Add the library methods
* using StorageSlot for bytes32;
* using SlotDerivation for bytes32;
*
* // Declare a namespace
* string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
*
* function setValueInNamespace(uint256 key, address newValue) internal {
* _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
* }
*
* function getValueInNamespace(uint256 key) internal view returns (address) {
* return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
* }
* }
* ```
*
* TIP: Consider using this library along with {StorageSlot}.
*
* NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
* upgrade safety will ignore the slots accessed through this library.
*
* _Available since v5.1._
*/
library SlotDerivation {
/**
* @dev Derive an ERC-7201 slot from a string (namespace).
*/
function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
assembly ("memory-safe") {
mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
slot := and(keccak256(0x00, 0x20), not(0xff))
}
}
/**
* @dev Add an offset to a slot to get the n-th element of a structure or an array.
*/
function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
unchecked {
return bytes32(uint256(slot) + pos);
}
}
/**
* @dev Derive the location of the first element in an array from the slot where the length is stored.
*/
function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, slot)
result := keccak256(0x00, 0x20)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, and(key, shr(96, not(0))))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, iszero(iszero(key)))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
}
/ShortStrings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/ShortStrings.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
assembly ("memory-safe") {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {toShortStringWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using
* {toShortStringWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}
/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
/Nonces.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides tracking nonces for addresses. Nonces will only increment.
*/
abstract contract Nonces {
/**
* @dev The nonce used for an `account` is not the expected current nonce.
*/
error InvalidAccountNonce(address account, uint256 currentNonce);
mapping(address account => uint256) private _nonces;
/**
* @dev Returns the next unused nonce for an address.
*/
function nonces(address owner) public view virtual returns (uint256) {
return _nonces[owner];
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256) {
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
// decremented or reset. This guarantees that the nonce never overflows.
unchecked {
// It is important to do x++ and not ++x here.
return _nonces[owner]++;
}
}
/**
* @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
*/
function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
uint256 current = _useNonce(owner);
if (nonce != current) {
revert InvalidAccountNonce(owner, current);
}
}
}
/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @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);
}
/MessageHashUtils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
*/
function toDataWithIntendedValidatorHash(
address validator,
bytes32 messageHash
) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, hex"19_00")
mstore(0x02, shl(96, validator))
mstore(0x16, messageHash)
digest := keccak256(0x00, 0x36)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
/EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable
*/
abstract contract EIP712 is IERC5267 {
using ShortStrings for *;
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
// slither-disable-next-line constable-states
string private _nameFallback;
// slither-disable-next-line constable-states
string private _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/// @inheritdoc IERC5267
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: By default this function reads _name which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Name() internal view returns (string memory) {
return _name.toStringWithFallback(_nameFallback);
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: By default this function reads _version which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Version() internal view returns (string memory) {
return _version.toStringWithFallback(_versionFallback);
}
}
/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
/Context.sol
// 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;
}
}
/Comparators.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to compare values.
*
* _Available since v5.1._
*/
library Comparators {
function lt(uint256 a, uint256 b) internal pure returns (bool) {
return a < b;
}
function gt(uint256 a, uint256 b) internal pure returns (bool) {
return a > b;
}
}
/Arrays.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.
pragma solidity ^0.8.20;
import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
using SlotDerivation for bytes32;
using StorageSlot for bytes32;
/**
* @dev Sort an array of uint256 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
uint256[] memory array,
function(uint256, uint256) pure returns (bool) comp
) internal pure returns (uint256[] memory) {
_quickSort(_begin(array), _end(array), comp);
return array;
}
/**
* @dev Variant of {sort} that sorts an array of uint256 in increasing order.
*/
function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
sort(array, Comparators.lt);
return array;
}
/**
* @dev Sort an array of address (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
address[] memory array,
function(address, address) pure returns (bool) comp
) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of address in increasing order.
*/
function sort(address[] memory array) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Sort an array of bytes32 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
bytes32[] memory array,
function(bytes32, bytes32) pure returns (bool) comp
) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
*/
function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
* at end (exclusive). Sorting follows the `comp` comparator.
*
* Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
*
* IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
* be used only if the limits are within a memory array.
*/
function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
unchecked {
if (end - begin < 0x40) return;
// Use first element as pivot
uint256 pivot = _mload(begin);
// Position where the pivot should be at the end of the loop
uint256 pos = begin;
for (uint256 it = begin + 0x20; it < end; it += 0x20) {
if (comp(_mload(it), pivot)) {
// If the value stored at the iterator's position comes before the pivot, we increment the
// position of the pivot and move the value there.
pos += 0x20;
_swap(pos, it);
}
}
_swap(begin, pos); // Swap pivot into place
_quickSort(begin, pos, comp); // Sort the left side of the pivot
_quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
}
}
/**
* @dev Pointer to the memory location of the first element of `array`.
*/
function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
assembly ("memory-safe") {
ptr := add(array, 0x20)
}
}
/**
* @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
* that comes just after the last element of the array.
*/
function _end(uint256[] memory array) private pure returns (uint256 ptr) {
unchecked {
return _begin(array) + array.length * 0x20;
}
}
/**
* @dev Load memory word (as a uint256) at location `ptr`.
*/
function _mload(uint256 ptr) private pure returns (uint256 value) {
assembly {
value := mload(ptr)
}
}
/**
* @dev Swaps the elements memory location `ptr1` and `ptr2`.
*/
function _swap(uint256 ptr1, uint256 ptr2) private pure {
assembly {
let value1 := mload(ptr1)
let value2 := mload(ptr2)
mstore(ptr1, value2)
mstore(ptr2, value1)
}
}
/// @dev Helper: low level cast address memory array to uint256 memory array
function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 memory array to uint256 memory array
function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast address comp function to uint256 comp function
function _castToUint256Comp(
function(address, address) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 comp function to uint256 comp function
function _castToUint256Comp(
function(bytes32, bytes32) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* NOTE: The `array` is expected to be sorted in ascending order, and to
* contain no repeated elements.
*
* IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
* support for repeated elements in the array. The {lowerBound} function should
* be used instead.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && unsafeAccess(array, low - 1).value == element) {
return low - 1;
} else {
return low;
}
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value greater or equal than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
*/
function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value strictly greater than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
*/
function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Same as {lowerBound}, but with an array in memory.
*/
function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Same as {upperBound}, but with an array in memory.
*/
function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getAddressSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytes32Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getUint256Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytesSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getStringSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(address[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(uint256[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(string[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
}
/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
} else {
revert Errors.FailedCall();
}
}
}
/utils/ERC721Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/utils/ERC721Utils.sol)
pragma solidity ^0.8.20;
import {IERC721Receiver} from "../IERC721Receiver.sol";
import {IERC721Errors} from "../../../interfaces/draft-IERC6093.sol";
/**
* @dev Library that provide common ERC-721 utility functions.
*
* See https://eips.ethereum.org/EIPS/eip-721[ERC-721].
*
* _Available since v5.1._
*/
library ERC721Utils {
/**
* @dev Performs an acceptance check for the provided `operator` by calling {IERC721Receiver-onERC721Received}
* on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
*
* The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
* Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept
* the transfer.
*/
function checkOnERC721Received(
address operator,
address from,
address to,
uint256 tokenId,
bytes memory data
) internal {
if (to.code.length > 0) {
try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {
if (retval != IERC721Receiver.onERC721Received.selector) {
// Token rejected
revert IERC721Errors.ERC721InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
// non-IERC721Receiver implementer
revert IERC721Errors.ERC721InvalidReceiver(to);
} else {
assembly ("memory-safe") {
revert(add(reason, 0x20), mload(reason))
}
}
}
}
}
}
/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity >=0.5.0;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)
pragma solidity >=0.6.2;
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);
}
/extensions/IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity >=0.6.2;
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);
}
/extensions/IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity >=0.6.2;
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);
}
/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @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);
}
/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/extensions/ERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.20;
import {IERC20Permit} from "./IERC20Permit.sol";
import {ERC20} from "../ERC20.sol";
import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
import {EIP712} from "../../../utils/cryptography/EIP712.sol";
import {Nonces} from "../../../utils/Nonces.sol";
/**
* @dev Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
bytes32 private constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Permit deadline has expired.
*/
error ERC2612ExpiredSignature(uint256 deadline);
/**
* @dev Mismatched signature.
*/
error ERC2612InvalidSigner(address signer, address owner);
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC-20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/// @inheritdoc IERC20Permit
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > deadline) {
revert ERC2612ExpiredSignature(deadline);
}
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
if (signer != owner) {
revert ERC2612InvalidSigner(signer, owner);
}
_approve(owner, spender, value);
}
/// @inheritdoc IERC20Permit
function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
return super.nonces(owner);
}
/// @inheritdoc IERC20Permit
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
return _domainSeparatorV4();
}
}
/extensions/ERC20Burnable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.20;
import {ERC20} from "../ERC20.sol";
import {Context} from "../../../utils/Context.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys a `value` amount of tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 value) public virtual {
_burn(_msgSender(), value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, deducting from
* the caller's allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `value`.
*/
function burnFrom(address account, uint256 value) public virtual {
_spendAllowance(account, _msgSender(), value);
_burn(account, value);
}
}
/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
/Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)
pragma solidity ^0.8.20;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback
* function and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
}
/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
/ERC1967Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.22;
import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
* encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
constructor(address implementation, bytes memory _data) payable {
ERC1967Utils.upgradeToAndCall(implementation, _data);
}
/**
* @dev Returns the current implementation address.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function _implementation() internal view virtual override returns (address) {
return ERC1967Utils.getImplementation();
}
}
/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)
pragma solidity >=0.4.16;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
/IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC5267.sol)
pragma solidity >=0.4.16;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)
pragma solidity >=0.4.11;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)
pragma solidity >=0.4.16;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @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 to signal 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;
}
/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.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 {
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/ContextUpgradeable.sol
// 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;
}
}
/extensions/ERC721EnumerableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.20;
import {ERC721Upgradeable} from "../ERC721Upgradeable.sol";
import {IERC721Enumerable} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the ERC that adds enumerability
* of all the token ids in the contract as well as all token ids owned by each account.
*
* CAUTION: {ERC721} extensions that implement custom `balanceOf` logic, such as {ERC721Consecutive},
* interfere with enumerability and should not be used together with {ERC721Enumerable}.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721Enumerable {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC721Enumerable
struct ERC721EnumerableStorage {
mapping(address owner => mapping(uint256 index => uint256)) _ownedTokens;
mapping(uint256 tokenId => uint256) _ownedTokensIndex;
uint256[] _allTokens;
mapping(uint256 tokenId => uint256) _allTokensIndex;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC721Enumerable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC721EnumerableStorageLocation = 0x645e039705490088daad89bae25049a34f4a9072d398537b1ab2425f24cbed00;
function _getERC721EnumerableStorage() private pure returns (ERC721EnumerableStorage storage $) {
assembly {
$.slot := ERC721EnumerableStorageLocation
}
}
/**
* @dev An `owner`'s token query was out of bounds for `index`.
*
* NOTE: The owner being `address(0)` indicates a global out of bounds index.
*/
error ERC721OutOfBoundsIndex(address owner, uint256 index);
/**
* @dev Batch mint is not allowed.
*/
error ERC721EnumerableForbiddenBatchMint();
function __ERC721Enumerable_init() internal onlyInitializing {
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/// @inheritdoc IERC721Enumerable
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {
ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();
if (index >= balanceOf(owner)) {
revert ERC721OutOfBoundsIndex(owner, index);
}
return $._ownedTokens[owner][index];
}
/// @inheritdoc IERC721Enumerable
function totalSupply() public view virtual returns (uint256) {
ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();
return $._allTokens.length;
}
/// @inheritdoc IERC721Enumerable
function tokenByIndex(uint256 index) public view virtual returns (uint256) {
ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();
if (index >= totalSupply()) {
revert ERC721OutOfBoundsIndex(address(0), index);
}
return $._allTokens[index];
}
/// @inheritdoc ERC721Upgradeable
function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {
address previousOwner = super._update(to, tokenId, auth);
if (previousOwner == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (previousOwner != to) {
_removeTokenFromOwnerEnumeration(previousOwner, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (previousOwner != to) {
_addTokenToOwnerEnumeration(to, tokenId);
}
return previousOwner;
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();
uint256 length = balanceOf(to) - 1;
$._ownedTokens[to][length] = tokenId;
$._ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();
$._allTokensIndex[tokenId] = $._allTokens.length;
$._allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = balanceOf(from);
uint256 tokenIndex = $._ownedTokensIndex[tokenId];
mapping(uint256 index => uint256) storage _ownedTokensByOwner = $._ownedTokens[from];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokensByOwner[lastTokenIndex];
_ownedTokensByOwner[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
$._ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete $._ownedTokensIndex[tokenId];
delete _ownedTokensByOwner[lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
ERC721EnumerableStorage storage $ = _getERC721EnumerableStorage();
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = $._allTokens.length - 1;
uint256 tokenIndex = $._allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = $._allTokens[lastTokenIndex];
$._allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
$._allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete $._allTokensIndex[tokenId];
$._allTokens.pop();
}
/**
* See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch
*/
function _increaseBalance(address account, uint128 amount) internal virtual override {
if (amount > 0) {
revert ERC721EnumerableForbiddenBatchMint();
}
super._increaseBalance(account, amount);
}
}
/ERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.20;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import {ERC721Utils} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Utils.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../../utils/introspection/ERC165Upgradeable.sol";
import {IERC721Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
abstract contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721, IERC721Metadata, IERC721Errors {
using Strings for uint256;
/// @custom:storage-location erc7201:openzeppelin.storage.ERC721
struct ERC721Storage {
// Token name
string _name;
// Token symbol
string _symbol;
mapping(uint256 tokenId => address) _owners;
mapping(address owner => uint256) _balances;
mapping(uint256 tokenId => address) _tokenApprovals;
mapping(address owner => mapping(address operator => bool)) _operatorApprovals;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC721")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC721StorageLocation = 0x80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab0079300;
function _getERC721Storage() private pure returns (ERC721Storage storage $) {
assembly {
$.slot := ERC721StorageLocation
}
}
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC721Storage storage $ = _getERC721Storage();
$._name = name_;
$._symbol = symbol_;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @inheritdoc IERC721
function balanceOf(address owner) public view virtual returns (uint256) {
ERC721Storage storage $ = _getERC721Storage();
if (owner == address(0)) {
revert ERC721InvalidOwner(address(0));
}
return $._balances[owner];
}
/// @inheritdoc IERC721
function ownerOf(uint256 tokenId) public view virtual returns (address) {
return _requireOwned(tokenId);
}
/// @inheritdoc IERC721Metadata
function name() public view virtual returns (string memory) {
ERC721Storage storage $ = _getERC721Storage();
return $._name;
}
/// @inheritdoc IERC721Metadata
function symbol() public view virtual returns (string memory) {
ERC721Storage storage $ = _getERC721Storage();
return $._symbol;
}
/// @inheritdoc IERC721Metadata
function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
_requireOwned(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/// @inheritdoc IERC721
function approve(address to, uint256 tokenId) public virtual {
_approve(to, tokenId, _msgSender());
}
/// @inheritdoc IERC721
function getApproved(uint256 tokenId) public view virtual returns (address) {
_requireOwned(tokenId);
return _getApproved(tokenId);
}
/// @inheritdoc IERC721
function setApprovalForAll(address operator, bool approved) public virtual {
_setApprovalForAll(_msgSender(), operator, approved);
}
/// @inheritdoc IERC721
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
ERC721Storage storage $ = _getERC721Storage();
return $._operatorApprovals[owner][operator];
}
/// @inheritdoc IERC721
function transferFrom(address from, address to, uint256 tokenId) public virtual {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
// Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
// (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
address previousOwner = _update(to, tokenId, _msgSender());
if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/// @inheritdoc IERC721
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/// @inheritdoc IERC721
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
transferFrom(from, to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*
* IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
* core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances
* consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
* `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
ERC721Storage storage $ = _getERC721Storage();
return $._owners[tokenId];
}
/**
* @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
*/
function _getApproved(uint256 tokenId) internal view virtual returns (address) {
ERC721Storage storage $ = _getERC721Storage();
return $._tokenApprovals[tokenId];
}
/**
* @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
* particular (ignoring whether it is owned by `owner`).
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
return
spender != address(0) &&
(owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
}
/**
* @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
* Reverts if:
* - `spender` does not have approval from `owner` for `tokenId`.
* - `spender` does not have approval to manage all of `owner`'s assets.
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
if (!_isAuthorized(owner, spender, tokenId)) {
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else {
revert ERC721InsufficientApproval(spender, tokenId);
}
}
}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
* a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
*
* WARNING: Increasing an account's balance using this function tends to be paired with an override of the
* {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
* remain consistent with one another.
*/
function _increaseBalance(address account, uint128 value) internal virtual {
ERC721Storage storage $ = _getERC721Storage();
unchecked {
$._balances[account] += value;
}
}
/**
* @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
* (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that
* `auth` is either the owner of the token, or approved to operate on the token (by the owner).
*
* Emits a {Transfer} event.
*
* NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
*/
function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
ERC721Storage storage $ = _getERC721Storage();
address from = _ownerOf(tokenId);
// Perform (optional) operator check
if (auth != address(0)) {
_checkAuthorized(from, auth, tokenId);
}
// Execute the update
if (from != address(0)) {
// Clear approval. No need to re-authorize or emit the Approval event
_approve(address(0), tokenId, address(0), false);
unchecked {
$._balances[from] -= 1;
}
}
if (to != address(0)) {
unchecked {
$._balances[to] += 1;
}
}
$._owners[tokenId] = to;
emit Transfer(from, to, tokenId);
return from;
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner != address(0)) {
revert ERC721InvalidSender(address(0));
}
}
/**
* @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
_mint(to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal {
address previousOwner = _update(address(0), tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
* are aware of the ERC-721 standard to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is like {safeTransferFrom} in the sense that it invokes
* {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `tokenId` token must exist and be owned by `from`.
* - `to` cannot be the zero address.
* - `from` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId) internal {
_safeTransfer(from, to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
_transfer(from, to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
* either the owner of the token, or approved to operate on all tokens held by this owner.
*
* Emits an {Approval} event.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address to, uint256 tokenId, address auth) internal {
_approve(to, tokenId, auth, true);
}
/**
* @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
* emitted in the context of transfers.
*/
function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
ERC721Storage storage $ = _getERC721Storage();
// Avoid reading the owner unless necessary
if (emitEvent || auth != address(0)) {
address owner = _requireOwned(tokenId);
// We do not use _isAuthorized because single-token approvals should not be able to call approve
if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
revert ERC721InvalidApprover(auth);
}
if (emitEvent) {
emit Approval(owner, to, tokenId);
}
}
$._tokenApprovals[tokenId] = to;
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Requirements:
* - operator can't be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
ERC721Storage storage $ = _getERC721Storage();
if (operator == address(0)) {
revert ERC721InvalidOperator(operator);
}
$._operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
* Returns the owner.
*
* Overrides to ownership logic should be done to {_ownerOf}.
*/
function _requireOwned(uint256 tokenId) internal view returns (address) {
address owner = _ownerOf(tokenId);
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
return owner;
}
}
/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 reinitialization) 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 Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/Ownable2StepUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {OwnableUpgradeable} from "./OwnableUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step
struct Ownable2StepStorage {
address _pendingOwner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable2Step")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant Ownable2StepStorageLocation = 0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00;
function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) {
assembly {
$.slot := Ownable2StepStorageLocation
}
}
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
function __Ownable2Step_init() internal onlyInitializing {
}
function __Ownable2Step_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
return $._pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
$._pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
delete $._pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.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 {
}
/// @inheritdoc IERC165
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` from `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;
}
}
}
Compiler Settings
{"viaIR":true,"remappings":[],"optimizer":{"runs":1000,"enabled":true},"metadata":{"bytecodeHash":"none"},"libraries":{},"evmVersion":"paris","compilationTarget":{"contracts/Minter.sol":"Minter"}}
Contract ABI
[{"type":"constructor","stateMutability":"nonpayable","inputs":[]},{"type":"error","name":"AddressEmptyCode","inputs":[{"type":"address","name":"target","internalType":"address"}]},{"type":"error","name":"BudgetExceedsCap","inputs":[]},{"type":"error","name":"ERC1967InvalidImplementation","inputs":[{"type":"address","name":"implementation","internalType":"address"}]},{"type":"error","name":"ERC1967NonPayable","inputs":[]},{"type":"error","name":"FailedCall","inputs":[]},{"type":"error","name":"InvalidInitialization","inputs":[]},{"type":"error","name":"NotInitializing","inputs":[]},{"type":"error","name":"NotVoter","inputs":[]},{"type":"error","name":"OwnableInvalidOwner","inputs":[{"type":"address","name":"owner","internalType":"address"}]},{"type":"error","name":"OwnableUnauthorizedAccount","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"error","name":"ReentrancyGuardReentrantCall","inputs":[]},{"type":"error","name":"SafeERC20FailedOperation","inputs":[{"type":"address","name":"token","internalType":"address"}]},{"type":"error","name":"TreasuryRateTooHigh","inputs":[]},{"type":"error","name":"UUPSUnauthorizedCallContext","inputs":[]},{"type":"error","name":"UUPSUnsupportedProxiableUUID","inputs":[{"type":"bytes32","name":"slot","internalType":"bytes32"}]},{"type":"error","name":"ZeroAddress","inputs":[]},{"type":"event","name":"Initialized","inputs":[{"type":"uint64","name":"version","internalType":"uint64","indexed":false}],"anonymous":false},{"type":"event","name":"Mint","inputs":[{"type":"address","name":"sender","internalType":"address","indexed":true},{"type":"uint256","name":"toVoter","internalType":"uint256","indexed":false},{"type":"uint256","name":"toTreasury","internalType":"uint256","indexed":false},{"type":"uint256","name":"emittedTotal","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"OwnershipTransferStarted","inputs":[{"type":"address","name":"previousOwner","internalType":"address","indexed":true},{"type":"address","name":"newOwner","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"OwnershipTransferred","inputs":[{"type":"address","name":"previousOwner","internalType":"address","indexed":true},{"type":"address","name":"newOwner","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"Upgraded","inputs":[{"type":"address","name":"implementation","internalType":"address","indexed":true}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"DURATION","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"MAX_TREASURY_RATE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"UPGRADE_INTERFACE_VERSION","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"acceptOwnership","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"baseRatePerSecond","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"emissionEnd","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"emissionStart","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"emitted","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"getCurrentPeriod","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"phase","internalType":"uint256"},{"type":"uint256","name":"phaseStart","internalType":"uint256"},{"type":"uint256","name":"phaseEnd","internalType":"uint256"},{"type":"uint256","name":"phaseRate","internalType":"uint256"}],"name":"getEmissionPhaseInfo","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"startTimestamp","internalType":"uint256"},{"type":"uint256","name":"endTimestamp","internalType":"uint256"},{"type":"uint256","name":"rate","internalType":"uint256"},{"type":"uint256","name":"currentPhase","internalType":"uint256"}],"name":"getEmissionSchedule","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"getRemainingBudget","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"initialize","inputs":[{"type":"address","name":"__voter","internalType":"address"},{"type":"address","name":"_veNFT","internalType":"address"},{"type":"address","name":"_treasury","internalType":"address"},{"type":"uint256","name":"_totalBudget","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"lastUpdate","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"owner","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"pendingOwner","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"proxiableUUID","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"renounceOwnership","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setTreasury","inputs":[{"type":"address","name":"_treasury","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setTreasuryRate","inputs":[{"type":"uint256","name":"_treasuryRate","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"start","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IMintable"}],"name":"token","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalBudget","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"transferOwnership","inputs":[{"type":"address","name":"newOwner","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"treasury","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"treasuryRate","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"updatePeriod","inputs":[]},{"type":"function","stateMutability":"payable","outputs":[],"name":"upgradeToAndCall","inputs":[{"type":"address","name":"newImplementation","internalType":"address"},{"type":"bytes","name":"data","internalType":"bytes"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IVotingEscrow"}],"name":"veNFT","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IVoter"}],"name":"voter","inputs":[]}]
Contract Creation Code
0x60a080604052346100ea57306080527ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005460ff8160401c166100d9576002600160401b03196001600160401b03821601610073575b604051611bea90816100f08239608051818181610cf70152610e0c0152f35b6001600160401b0319166001600160401b039081177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005581527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a13880610054565b63f92ee8a960e01b60005260046000fd5b600080fdfe608080604052600436101561001357600080fd5b60003560e01c908163086146d2146110b4575080631be052891461109657806346c96aac1461106f5780634f1ef28614610d8f578063513da94814610d7157806352d1902d14610cdc57806361d027b314610cb5578063715018a614610bce57806377a15b6114610ba457806379ba509714610b29578063809a948114610b0c5780638368909c14610aee5780638d90f9c214610ab05780638da5cb5b14610a6a57806396b096bf14610a43578063a83627de14610983578063ad3cb1cc146108ef578063af2aa63b1461085a578063bd153c641461083c578063be9a65551461078c578063c04637111461076e578063c78da39a14610750578063cf756fdf146103a7578063d0bf9c5414610353578063d90e026414610335578063e30c3978146102ef578063e4b72516146102d1578063f0f4426014610261578063f2fde38b146101955763fc0c546a1461016957600080fd5b346101905760003660031901126101905760206001600160a01b0360005416604051908152f35b600080fd5b34610190576020366003190112610190576001600160a01b036101b66110d2565b6101be6116a8565b16806001600160a01b03197f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c005416177f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00556001600160a01b037f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930054167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700600080a3005b34610190576020366003190112610190576001600160a01b036102826110d2565b61028a6116a8565b1680156102a7576001600160a01b03196003541617600355600080f35b7fd92e233d0000000000000000000000000000000000000000000000000000000060005260046000fd5b34610190576000366003190112610190576020600a54604051908152f35b346101905760003660031901126101905760206001600160a01b037f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c005416604051908152f35b34610190576000366003190112610190576020600754604051908152f35b346101905760203660031901126101905760043561036f6116a8565b6103e8811161037d57600a55005b7f3e6910cd0000000000000000000000000000000000000000000000000000000060005260046000fd5b34610190576080366003190112610190576103c06110d2565b6024356001600160a01b038116809103610190576044356001600160a01b03811680910361019057606435917ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00549360ff8560401c16159467ffffffffffffffff811680159081610748575b600114908161073e575b159081610735575b5061070b5767ffffffffffffffff1981166001177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0055856106cc575b50610483611af4565b61048b611af4565b610493611af4565b61049b611af4565b331561069d576001600160a01b03906104b3336116db565b6104bb611af4565b6104c3611af4565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00556103e8600a55169182158015610695575b801561068d575b6102a7576004916020916001600160a01b03196003541617600355806001600160a01b03196002541617600255604051928380927ffc0c546a0000000000000000000000000000000000000000000000000000000082525afa90811561068157600091610631575b506001600160a01b03166001600160a01b031960005416176000556001600160a01b0319600154161760015561059c81611938565b6008556000600455600060055560006006556105b457005b68ff0000000000000000197ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054167ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00557fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2602060405160018152a1005b6020813d602011610679575b8161064a602093836110e8565b810103126106755751906001600160a01b038216820361067257506001600160a01b03610567565b80fd5b5080fd5b3d915061063d565b6040513d6000823e3d90fd5b5080156104ff565b5081156104f8565b7f1e4fbdf700000000000000000000000000000000000000000000000000000000600052600060045260246000fd5b68ffffffffffffffffff191668010000000000000001177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00558561047a565b7ff92ee8a90000000000000000000000000000000000000000000000000000000060005260046000fd5b9050158761043e565b303b159150610436565b87915061042c565b34610190576000366003190112610190576020600854604051908152f35b34610190576000366003190112610190576020600654604051908152f35b34610190576000366003190112610190576001600160a01b0360015416330361081257600454156107b957005b426004556107c642611149565b62f099c081018091116107fc57600555426006556008548060031b90808204600814901517156107fc5763186f9d809004600755005b634e487b7160e01b600052601160045260246000fd5b7fc18384c10000000000000000000000000000000000000000000000000000000060005260046000fd5b34610190576000366003190112610190576020600954604051908152f35b34610190576000366003190112610190576004546005549060075481156000146108ad576108a9906000905b604051948594859094939260609260808301968352602083015260408201520152565b0390f35b6301e133808201908183116107fc576108a9914210156108cf57600090610886565b6108d883611149565b4210156108e757600190610886565b600290610886565b3461019057600036600319011261019057604080519061090f81836110e8565b600582527f352e302e300000000000000000000000000000000000000000000000000000006020830152805180926020825280519081602084015260005b82811061096c5750506000828201840152601f01601f19168101030190f35b60208282018101518783018701528694500161094d565b346101905760003660031901126101905760027f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005414610a195760027f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005560206109eb6111fd565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00556040519015158152f35b7f3ee5aeb50000000000000000000000000000000000000000000000000000000060005260046000fd5b346101905760003660031901126101905760206001600160a01b0360025416604051908152f35b346101905760003660031901126101905760206001600160a01b037f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c1993005416604051908152f35b34610190576000366003190112610190576108a9610acc61117a565b6040805194855260208501939093529183015260608201529081906080820190565b34610190576000366003190112610190576020600554604051908152f35b346101905760003660031901126101905760206040516103e88152f35b3461019057600036600319011261019057336001600160a01b037f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00541603610b7657610b74336116db565b005b7f118cdaa7000000000000000000000000000000000000000000000000000000006000523360045260246000fd5b34610190576000366003190112610190576020610bc66008546009549061113c565b604051908152f35b3461019057600036600319011261019057610be76116a8565b6001600160a01b03197f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c0054167f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c005560006001600160a01b037f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300546001600160a01b031981167f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930055167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b346101905760003660031901126101905760206001600160a01b0360035416604051908152f35b34610190576000366003190112610190576001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000163003610d475760206040517f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8152f35b7fe07c8dba0000000000000000000000000000000000000000000000000000000060005260046000fd5b34610190576000366003190112610190576020600454604051908152f35b604036600319011261019057610da36110d2565b6024359067ffffffffffffffff8211610190573660238301121561019057816004013590610dd082611120565b91610dde60405193846110e8565b8083526020830193366024838301011161019057816000926024602093018737840101526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001680301490811561103a575b50610d4757610e446116a8565b6001600160a01b038116926040517f52d1902d000000000000000000000000000000000000000000000000000000008152602081600481885afa60009181611006575b50610ea15784634c9c8ce360e01b60005260045260246000fd5b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc869203610fd95750823b15610fc557806001600160a01b03197f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416177f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b600080a2825115610f915760008091610b74945190845af43d15610f89573d91610f6c83611120565b92610f7a60405194856110e8565b83523d6000602085013e611b4d565b606091611b4d565b50505034610f9b57005b7fb398979f0000000000000000000000000000000000000000000000000000000060005260046000fd5b634c9c8ce360e01b60005260045260246000fd5b7faa1d49a40000000000000000000000000000000000000000000000000000000060005260045260246000fd5b9091506020813d602011611032575b81611022602093836110e8565b8101031261019057519086610e87565b3d9150611015565b90506001600160a01b037f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416141584610e37565b346101905760003660031901126101905760206001600160a01b0360015416604051908152f35b3461019057600036600319011261019057602060405162093a808152f35b346101905760003660031901126101905760209062093a8042048152f35b600435906001600160a01b038216820361019057565b90601f8019910116810190811067ffffffffffffffff82111761110a57604052565b634e487b7160e01b600052604160045260246000fd5b67ffffffffffffffff811161110a57601f01601f191660200190565b919082039182116107fc57565b906303c2670082018092116107fc57565b919082018092116107fc57565b818102929181159184041417156107fc57565b6004549081156111f1576301e1338082019081831191826107fc578042106000146111ae57600093926107fc579060075490565b9291506111ba82611149565b4210156111d6576111cd60019392611149565b90600754841c90565b9091506111e4600292611149565b9060055490600754841c90565b60009150819081908190565b600454600090156116a55760055480421060001461169f5742905b60065480831115611699578261122d916117ae565b90821480611683575b15611653575061124b6008546009549061113c565b801561164c57612710611260600a5483611167565b049061126c828261113c565b936001600160a01b038154166040517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152602081602481855afa90811561164157839161160f575b5083811061159b575b50508261153c575b84611322575b506112df9060095461115a565b9182600955600655604051928352602083015260408201527fb4c03061fb5b7fed76389d5af8f2e0ddb09f8c70d1333abbb62582835e10accb60603392a2600190565b6001600160a01b038154166001600160a01b0360015416906040519060208481840163095ea7b360e01b8152611384856113768d8960248401602090939291936001600160a01b0360408201951681520152565b03601f1981018752866110e8565b84519082855af184513d82611520575b5050156114e6575b5050506001600160a01b0360015416803b15610675578180916024604051809481937f3c6b16ab0000000000000000000000000000000000000000000000000000000083528b60048401525af180156114db576114c6575b5090816001600160a01b036112df935416906001600160a01b0360015416916040519160208181850163095ea7b360e01b8152866024870152816044870152604486526114426064876110e8565b85519082865af181513d826114aa575b505015611464575b50505050906112d2565b6114a19361149c916040519163095ea7b360e01b602084015260248301526044820152604481526114966064826110e8565b82611a83565b611a83565b3880808061145a565b9091506114be5750813b15155b3880611452565b6001146114b7565b6114d18280926110e8565b61067257386113f4565b6040513d84823e3d90fd5b61149c611518936040519063095ea7b360e01b60208301526024820152856044820152604481526114966064826110e8565b38808061139c565b9091506115345750803b15155b3880611394565b60011461152d565b80546003546040517fa9059cbb0000000000000000000000000000000000000000000000000000000060208201526001600160a01b039182166024820152604480820187905281526115969290911661149c6064836110e8565b6112cc565b6115a5908461113c565b813b1561160b576040517f40c10f1900000000000000000000000000000000000000000000000000000000815230600482015260248101919091529082908290604490829084905af180156114db578290156112c457611604916110e8565b38816112c4565b8280fd5b90506020813d602011611639575b8161162a602093836110e8565b8101031261160b5751386112bb565b3d915061161d565b6040513d85823e3d90fd5b5060065590565b600954611660828261115a565b600854809111611672575b505061124b565b61167c925061113c565b388061166b565b506116908160095461115a565b60085411611236565b50505090565b80611218565b90565b6001600160a01b037f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930054163303610b7657565b6001600160a01b03197f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c0054167f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00556001600160a01b03807f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930054921691826001600160a01b03198216177f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930055167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a3565b91906000928082111561193057600454916301e133808301918284116107fc576303c2670084018084116107fc57600554936007549580851180611927575b6118d8575b50808411806118cf575b61187d575b5080831180611874575b611817575b5050505050565b8082111561186c5750915b8082101561186557505b81811161183b575b8080611810565b9161184e6118539261185c95969461113c565b611167565b60021c9061115a565b90388080611834565b905061182c565b905091611822565b5083821061180b565b808311156118ca5750815b818410156118c457835b8181116118a0575b50611801565b8661184e6118bc949a936118b39361113c565b60011c9061115a565b95388061189a565b81611892565b611888565b508183106117fc565b808411156119225750825b8185101561191c57845b8181116118fb575b506117f2565b8761184e611914949b9361190e9361113c565b9061115a565b9638806118f5565b816118ed565b6118e3565b508184106117ed565b506000925050565b8015611a80576001600160a01b0360005416604051907f355274ea000000000000000000000000000000000000000000000000000000008252602082600481845afa60009281611a4c575b5061198d57505050565b8115611a47576020600491604051928380927f18160ddd0000000000000000000000000000000000000000000000000000000082525afa90811561068157600091611a15575b508082106119eb576119e49161113c565b106119eb57565b7fd71376560000000000000000000000000000000000000000000000000000000060005260046000fd5b906020823d602011611a3f575b81611a2f602093836110e8565b81010312610672575051386119d3565b3d9150611a22565b505050565b90926020823d602011611a78575b81611a67602093836110e8565b810103126106725750519138611983565b3d9150611a5a565b50565b906000602091828151910182855af115610681576000513d611aeb57506001600160a01b0381163b155b611ab45750565b6001600160a01b03907f5274afe7000000000000000000000000000000000000000000000000000000006000521660045260246000fd5b60011415611aad565b60ff7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005460401c1615611b2357565b7fd7e6bcf80000000000000000000000000000000000000000000000000000000060005260046000fd5b90611b8c5750805115611b6257602081519101fd5b7fd6bda2750000000000000000000000000000000000000000000000000000000060005260046000fd5b81511580611bd4575b611b9d575090565b6001600160a01b03907f9996b315000000000000000000000000000000000000000000000000000000006000521660045260246000fd5b50803b15611b9556fea164736f6c634300081c000a
Deployed ByteCode
0x608080604052600436101561001357600080fd5b60003560e01c908163086146d2146110b4575080631be052891461109657806346c96aac1461106f5780634f1ef28614610d8f578063513da94814610d7157806352d1902d14610cdc57806361d027b314610cb5578063715018a614610bce57806377a15b6114610ba457806379ba509714610b29578063809a948114610b0c5780638368909c14610aee5780638d90f9c214610ab05780638da5cb5b14610a6a57806396b096bf14610a43578063a83627de14610983578063ad3cb1cc146108ef578063af2aa63b1461085a578063bd153c641461083c578063be9a65551461078c578063c04637111461076e578063c78da39a14610750578063cf756fdf146103a7578063d0bf9c5414610353578063d90e026414610335578063e30c3978146102ef578063e4b72516146102d1578063f0f4426014610261578063f2fde38b146101955763fc0c546a1461016957600080fd5b346101905760003660031901126101905760206001600160a01b0360005416604051908152f35b600080fd5b34610190576020366003190112610190576001600160a01b036101b66110d2565b6101be6116a8565b16806001600160a01b03197f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c005416177f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00556001600160a01b037f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930054167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700600080a3005b34610190576020366003190112610190576001600160a01b036102826110d2565b61028a6116a8565b1680156102a7576001600160a01b03196003541617600355600080f35b7fd92e233d0000000000000000000000000000000000000000000000000000000060005260046000fd5b34610190576000366003190112610190576020600a54604051908152f35b346101905760003660031901126101905760206001600160a01b037f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c005416604051908152f35b34610190576000366003190112610190576020600754604051908152f35b346101905760203660031901126101905760043561036f6116a8565b6103e8811161037d57600a55005b7f3e6910cd0000000000000000000000000000000000000000000000000000000060005260046000fd5b34610190576080366003190112610190576103c06110d2565b6024356001600160a01b038116809103610190576044356001600160a01b03811680910361019057606435917ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00549360ff8560401c16159467ffffffffffffffff811680159081610748575b600114908161073e575b159081610735575b5061070b5767ffffffffffffffff1981166001177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0055856106cc575b50610483611af4565b61048b611af4565b610493611af4565b61049b611af4565b331561069d576001600160a01b03906104b3336116db565b6104bb611af4565b6104c3611af4565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00556103e8600a55169182158015610695575b801561068d575b6102a7576004916020916001600160a01b03196003541617600355806001600160a01b03196002541617600255604051928380927ffc0c546a0000000000000000000000000000000000000000000000000000000082525afa90811561068157600091610631575b506001600160a01b03166001600160a01b031960005416176000556001600160a01b0319600154161760015561059c81611938565b6008556000600455600060055560006006556105b457005b68ff0000000000000000197ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054167ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00557fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2602060405160018152a1005b6020813d602011610679575b8161064a602093836110e8565b810103126106755751906001600160a01b038216820361067257506001600160a01b03610567565b80fd5b5080fd5b3d915061063d565b6040513d6000823e3d90fd5b5080156104ff565b5081156104f8565b7f1e4fbdf700000000000000000000000000000000000000000000000000000000600052600060045260246000fd5b68ffffffffffffffffff191668010000000000000001177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00558561047a565b7ff92ee8a90000000000000000000000000000000000000000000000000000000060005260046000fd5b9050158761043e565b303b159150610436565b87915061042c565b34610190576000366003190112610190576020600854604051908152f35b34610190576000366003190112610190576020600654604051908152f35b34610190576000366003190112610190576001600160a01b0360015416330361081257600454156107b957005b426004556107c642611149565b62f099c081018091116107fc57600555426006556008548060031b90808204600814901517156107fc5763186f9d809004600755005b634e487b7160e01b600052601160045260246000fd5b7fc18384c10000000000000000000000000000000000000000000000000000000060005260046000fd5b34610190576000366003190112610190576020600954604051908152f35b34610190576000366003190112610190576004546005549060075481156000146108ad576108a9906000905b604051948594859094939260609260808301968352602083015260408201520152565b0390f35b6301e133808201908183116107fc576108a9914210156108cf57600090610886565b6108d883611149565b4210156108e757600190610886565b600290610886565b3461019057600036600319011261019057604080519061090f81836110e8565b600582527f352e302e300000000000000000000000000000000000000000000000000000006020830152805180926020825280519081602084015260005b82811061096c5750506000828201840152601f01601f19168101030190f35b60208282018101518783018701528694500161094d565b346101905760003660031901126101905760027f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005414610a195760027f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005560206109eb6111fd565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00556040519015158152f35b7f3ee5aeb50000000000000000000000000000000000000000000000000000000060005260046000fd5b346101905760003660031901126101905760206001600160a01b0360025416604051908152f35b346101905760003660031901126101905760206001600160a01b037f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c1993005416604051908152f35b34610190576000366003190112610190576108a9610acc61117a565b6040805194855260208501939093529183015260608201529081906080820190565b34610190576000366003190112610190576020600554604051908152f35b346101905760003660031901126101905760206040516103e88152f35b3461019057600036600319011261019057336001600160a01b037f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00541603610b7657610b74336116db565b005b7f118cdaa7000000000000000000000000000000000000000000000000000000006000523360045260246000fd5b34610190576000366003190112610190576020610bc66008546009549061113c565b604051908152f35b3461019057600036600319011261019057610be76116a8565b6001600160a01b03197f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c0054167f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c005560006001600160a01b037f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300546001600160a01b031981167f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930055167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b346101905760003660031901126101905760206001600160a01b0360035416604051908152f35b34610190576000366003190112610190576001600160a01b037f000000000000000000000000f0328299c36452e5e5ceaa550962032891760faf163003610d475760206040517f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8152f35b7fe07c8dba0000000000000000000000000000000000000000000000000000000060005260046000fd5b34610190576000366003190112610190576020600454604051908152f35b604036600319011261019057610da36110d2565b6024359067ffffffffffffffff8211610190573660238301121561019057816004013590610dd082611120565b91610dde60405193846110e8565b8083526020830193366024838301011161019057816000926024602093018737840101526001600160a01b037f000000000000000000000000f0328299c36452e5e5ceaa550962032891760faf1680301490811561103a575b50610d4757610e446116a8565b6001600160a01b038116926040517f52d1902d000000000000000000000000000000000000000000000000000000008152602081600481885afa60009181611006575b50610ea15784634c9c8ce360e01b60005260045260246000fd5b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc869203610fd95750823b15610fc557806001600160a01b03197f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416177f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b600080a2825115610f915760008091610b74945190845af43d15610f89573d91610f6c83611120565b92610f7a60405194856110e8565b83523d6000602085013e611b4d565b606091611b4d565b50505034610f9b57005b7fb398979f0000000000000000000000000000000000000000000000000000000060005260046000fd5b634c9c8ce360e01b60005260045260246000fd5b7faa1d49a40000000000000000000000000000000000000000000000000000000060005260045260246000fd5b9091506020813d602011611032575b81611022602093836110e8565b8101031261019057519086610e87565b3d9150611015565b90506001600160a01b037f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416141584610e37565b346101905760003660031901126101905760206001600160a01b0360015416604051908152f35b3461019057600036600319011261019057602060405162093a808152f35b346101905760003660031901126101905760209062093a8042048152f35b600435906001600160a01b038216820361019057565b90601f8019910116810190811067ffffffffffffffff82111761110a57604052565b634e487b7160e01b600052604160045260246000fd5b67ffffffffffffffff811161110a57601f01601f191660200190565b919082039182116107fc57565b906303c2670082018092116107fc57565b919082018092116107fc57565b818102929181159184041417156107fc57565b6004549081156111f1576301e1338082019081831191826107fc578042106000146111ae57600093926107fc579060075490565b9291506111ba82611149565b4210156111d6576111cd60019392611149565b90600754841c90565b9091506111e4600292611149565b9060055490600754841c90565b60009150819081908190565b600454600090156116a55760055480421060001461169f5742905b60065480831115611699578261122d916117ae565b90821480611683575b15611653575061124b6008546009549061113c565b801561164c57612710611260600a5483611167565b049061126c828261113c565b936001600160a01b038154166040517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152602081602481855afa90811561164157839161160f575b5083811061159b575b50508261153c575b84611322575b506112df9060095461115a565b9182600955600655604051928352602083015260408201527fb4c03061fb5b7fed76389d5af8f2e0ddb09f8c70d1333abbb62582835e10accb60603392a2600190565b6001600160a01b038154166001600160a01b0360015416906040519060208481840163095ea7b360e01b8152611384856113768d8960248401602090939291936001600160a01b0360408201951681520152565b03601f1981018752866110e8565b84519082855af184513d82611520575b5050156114e6575b5050506001600160a01b0360015416803b15610675578180916024604051809481937f3c6b16ab0000000000000000000000000000000000000000000000000000000083528b60048401525af180156114db576114c6575b5090816001600160a01b036112df935416906001600160a01b0360015416916040519160208181850163095ea7b360e01b8152866024870152816044870152604486526114426064876110e8565b85519082865af181513d826114aa575b505015611464575b50505050906112d2565b6114a19361149c916040519163095ea7b360e01b602084015260248301526044820152604481526114966064826110e8565b82611a83565b611a83565b3880808061145a565b9091506114be5750813b15155b3880611452565b6001146114b7565b6114d18280926110e8565b61067257386113f4565b6040513d84823e3d90fd5b61149c611518936040519063095ea7b360e01b60208301526024820152856044820152604481526114966064826110e8565b38808061139c565b9091506115345750803b15155b3880611394565b60011461152d565b80546003546040517fa9059cbb0000000000000000000000000000000000000000000000000000000060208201526001600160a01b039182166024820152604480820187905281526115969290911661149c6064836110e8565b6112cc565b6115a5908461113c565b813b1561160b576040517f40c10f1900000000000000000000000000000000000000000000000000000000815230600482015260248101919091529082908290604490829084905af180156114db578290156112c457611604916110e8565b38816112c4565b8280fd5b90506020813d602011611639575b8161162a602093836110e8565b8101031261160b5751386112bb565b3d915061161d565b6040513d85823e3d90fd5b5060065590565b600954611660828261115a565b600854809111611672575b505061124b565b61167c925061113c565b388061166b565b506116908160095461115a565b60085411611236565b50505090565b80611218565b90565b6001600160a01b037f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930054163303610b7657565b6001600160a01b03197f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c0054167f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00556001600160a01b03807f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930054921691826001600160a01b03198216177f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930055167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a3565b91906000928082111561193057600454916301e133808301918284116107fc576303c2670084018084116107fc57600554936007549580851180611927575b6118d8575b50808411806118cf575b61187d575b5080831180611874575b611817575b5050505050565b8082111561186c5750915b8082101561186557505b81811161183b575b8080611810565b9161184e6118539261185c95969461113c565b611167565b60021c9061115a565b90388080611834565b905061182c565b905091611822565b5083821061180b565b808311156118ca5750815b818410156118c457835b8181116118a0575b50611801565b8661184e6118bc949a936118b39361113c565b60011c9061115a565b95388061189a565b81611892565b611888565b508183106117fc565b808411156119225750825b8185101561191c57845b8181116118fb575b506117f2565b8761184e611914949b9361190e9361113c565b9061115a565b9638806118f5565b816118ed565b6118e3565b508184106117ed565b506000925050565b8015611a80576001600160a01b0360005416604051907f355274ea000000000000000000000000000000000000000000000000000000008252602082600481845afa60009281611a4c575b5061198d57505050565b8115611a47576020600491604051928380927f18160ddd0000000000000000000000000000000000000000000000000000000082525afa90811561068157600091611a15575b508082106119eb576119e49161113c565b106119eb57565b7fd71376560000000000000000000000000000000000000000000000000000000060005260046000fd5b906020823d602011611a3f575b81611a2f602093836110e8565b81010312610672575051386119d3565b3d9150611a22565b505050565b90926020823d602011611a78575b81611a67602093836110e8565b810103126106725750519138611983565b3d9150611a5a565b50565b906000602091828151910182855af115610681576000513d611aeb57506001600160a01b0381163b155b611ab45750565b6001600160a01b03907f5274afe7000000000000000000000000000000000000000000000000000000006000521660045260246000fd5b60011415611aad565b60ff7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005460401c1615611b2357565b7fd7e6bcf80000000000000000000000000000000000000000000000000000000060005260046000fd5b90611b8c5750805115611b6257602081519101fd5b7fd6bda2750000000000000000000000000000000000000000000000000000000060005260046000fd5b81511580611bd4575b611b9d575090565b6001600160a01b03907f9996b315000000000000000000000000000000000000000000000000000000006000521660045260246000fd5b50803b15611b9556fea164736f6c634300081c000a