Verified contractPartialMIT
Treasury
Address0xbf3cf484670dcf60f488e73bafb530348526eb9d
- Balance
0 ETH
- Transactions
6
- Compiler
solc 0.8.17
- Same code
1 more contract
Details
- Compiler
- solc 0.8.17+commit.8df45f5f
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- london
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 19,133,235
- Creation transaction
- 0x6e3d87fb4c…68dda08bee
- Main copy (most transactions)
- 0x3b91f74a…96902d68
56 files
- src/contracts/Treasury.solmain26.01 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol2.62 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1155.sol157 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC721.sol154 B
- lib/openzeppelin-contracts/contracts/proxy/Clones.sol4.03 KB
- lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol3.13 KB
- lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol4.03 KB
- lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol2.5 KB
- lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Holder.sol974 B
- lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Receiver.sol611 B
- lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol12.85 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.74 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Burnable.sol1.14 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Permit.sol3.32 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol2.25 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/draft-IERC20Permit.sol152 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol4.29 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol4.88 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol987 B
- lib/openzeppelin-contracts/contracts/utils/Address.sol9.37 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol844 B
- lib/openzeppelin-contracts/contracts/utils/Counters.sol1.4 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol2.78 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol8.4 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/EIP712.sol4.52 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol987 B
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol853 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol12.49 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol1.26 KB
- lib/solidity-utils/contracts/interfaces/IDaiLikePermit.sol316 B
- lib/solidity-utils/contracts/interfaces/IPermit2.sol1.4 KB
- lib/solidity-utils/contracts/libraries/RevertReasonForwarder.sol552 B
- lib/solidity-utils/contracts/libraries/SafeERC20.sol10.26 KB
- src/contracts/authorities/AuthorityControl.sol4.84 KB
- src/contracts/staking/VeFloorStaking.sol18.76 KB
- src/contracts/strategies/StrategyFactory.sol12.68 KB
- src/contracts/tokens/Floor.sol1.03 KB
- src/contracts/utils/EpochManaged.sol1.45 KB
- src/contracts/utils/Errors.sol1.34 KB
- src/interfaces/EpochManager.sol2.97 KB
- src/interfaces/Treasury.sol6.48 KB
- src/interfaces/actions/Action.sol150 B
- src/interfaces/actions/Sweeper.sol755 B
- src/interfaces/authorities/AuthorityControl.sol1.59 KB
- src/interfaces/authorities/AuthorityRegistry.sol2.48 KB
- src/interfaces/collections/CollectionRegistry.sol1.09 KB
- src/interfaces/staking/VeFloorStaking.sol1.68 KB
- src/interfaces/strategies/BaseStrategy.sol3.33 KB
- src/interfaces/strategies/StrategyFactory.sol5.44 KB
- src/interfaces/strategies/StrategyRegistry.sol1.29 KB
- src/interfaces/tokens/Floor.sol416 B
- src/interfaces/tokens/Votable.sol324 B
- src/interfaces/tokens/WETH.sol576 B
- src/interfaces/voting/NewCollectionWars.sol6.1 KB
- src/interfaces/voting/SweepWars.sol5.57 KB
src/contracts/Treasury.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20, SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {IERC721} from '@openzeppelin/contracts/interfaces/IERC721.sol';
import {IERC1155} from '@openzeppelin/contracts/interfaces/IERC1155.sol';
import {IERC721Receiver} from '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import {IERC1155Receiver} from '@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol';
import {ERC1155Holder} from '@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol';
import {ReentrancyGuard} from '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import {AuthorityControl} from '@floor/authorities/AuthorityControl.sol';
import {VeFloorStaking} from '@floor/staking/VeFloorStaking.sol';
import {StrategyFactory} from '@floor/strategies/StrategyFactory.sol';
import {FLOOR} from '@floor/tokens/Floor.sol';
import {EpochManaged} from '@floor/utils/EpochManaged.sol';
import {CannotSetNullAddress, InsufficientAmount, PercentageTooHigh, TransferFailed} from '@floor/utils/Errors.sol';
import {IAction} from '@floor-interfaces/actions/Action.sol';
import {IMercenarySweeper, ISweeper} from '@floor-interfaces/actions/Sweeper.sol';
import {IWETH} from '@floor-interfaces/tokens/WETH.sol';
import {ISweepWars} from '@floor-interfaces/voting/SweepWars.sol';
import {ITreasury, TreasuryEnums} from '@floor-interfaces/Treasury.sol';
/**
* The Treasury will hold all assets.
*/
contract Treasury is AuthorityControl, EpochManaged, IERC721Receiver, IERC1155Receiver, ITreasury, ReentrancyGuard {
using SafeERC20 for IERC20;
/// An array of sweeps that map against the epoch iteration.
mapping(uint => Sweep) public epochSweeps;
/// Holds our {FLOOR} and {WETH} contract references.
FLOOR public immutable floor;
IWETH public immutable weth;
/// Holds our {StrategyFactory} contract reference.
StrategyFactory public strategyFactory;
/// Holds our {VeFloorStaking} contract reference.
VeFloorStaking public veFloor;
/// Store a minimum sweep amount that can be implemented, or excluded, as desired by
/// the DAO.
uint public minSweepAmount;
/// Set a sweep power that is required for public sweep execution
uint public constant SWEEP_EXECUTE_TOKENS = 5_000 ether;
/// Stores our Mercenary sweeper contract address
IMercenarySweeper public mercSweeper;
/// Stores a list of approved sweeper contracts
mapping(address => bool) public approvedSweepers;
/**
* Set up our connection to the Treasury to ensure future calls only come from this
* trusted source.
*
* @param _authority {AuthorityRegistry} contract address
* @param _floor Address of our {FLOOR} contract
* @param _weth Address of {WETH} contract
*/
constructor(address _authority, address _floor, address _weth) AuthorityControl(_authority) {
if (_floor == address(0) || _weth == address(0)) revert CannotSetNullAddress();
floor = FLOOR(_floor);
weth = IWETH(_weth);
}
/**
* Allow FLOOR token to be minted. This should be called from the deposit method
* internally, but a public method will allow a {TreasuryManager} to bypass this
* and create additional FLOOR tokens if needed.
*
* @param amount The amount of {FLOOR} tokens to be minted
*/
function mint(uint amount) external onlyRole(TREASURY_MANAGER) {
if (amount == 0) {
revert InsufficientAmount();
}
_mint(address(this), amount);
}
/**
* Internal call to handle minting and event firing.
*
* @param recipient The recipient of the {FLOOR} tokens
* @param amount The number of tokens to be minted
*/
function _mint(address recipient, uint amount) internal {
floor.mint(recipient, amount);
emit FloorMinted(amount);
}
/**
* Allows an ERC20 token to be deposited.
*
* @param token ERC20 token address to be deposited
* @param amount The amount of the token to be deposited
*/
function depositERC20(address token, uint amount) external {
// Transfer ERC20 tokens into the {Treasury}. This call will revert if it fails.
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
emit DepositERC20(token, amount);
}
/**
* Allows an ERC721 token to be deposited.
*
* @param token ERC721 token address to be deposited
* @param tokenId The ID of the ERC721 being deposited
*/
function depositERC721(address token, uint tokenId) external {
IERC721(token).transferFrom(msg.sender, address(this), tokenId);
emit DepositERC721(token, tokenId);
}
/**
* Allows an ERC1155 token(s) to be deposited.
*
* @param token ERC1155 token address to be deposited
* @param tokenId The ID of the ERC1155 being deposited
* @param amount The amount of the token to be deposited
*/
function depositERC1155(address token, uint tokenId, uint amount) external {
IERC1155(token).safeTransferFrom(msg.sender, address(this), tokenId, amount, '');
emit DepositERC1155(token, tokenId, amount);
}
/**
* Allows an approved user to withdraw native token.
*
* @param recipient The user that will receive the native token
* @param amount The number of native tokens to withdraw
*/
function withdraw(address recipient, uint amount) external nonReentrant onlyRole(TREASURY_MANAGER) {
(bool success,) = recipient.call{value: amount}('');
if (!success) {
revert TransferFailed();
}
emit Withdraw(amount, recipient);
}
/**
* Allows an approved user to withdraw an ERC20 token from the Treasury.
*
* @param recipient The user that will receive the ERC20 tokens
* @param token ERC20 token address to be withdrawn
* @param amount The number of tokens to withdraw
*/
function withdrawERC20(address recipient, address token, uint amount) external nonReentrant onlyRole(TREASURY_MANAGER) {
// Transfer ERC20 tokens to the recipient. This call will revert if it fails.
IERC20(token).safeTransfer(recipient, amount);
emit WithdrawERC20(token, amount, recipient);
}
/**
* Allows an approved user to withdraw an ERC721 token from the Treasury.
*
* @param recipient The user that will receive the ERC721 tokens
* @param token ERC721 token address to be withdrawn
* @param tokenId The ID of the ERC721 being withdrawn
*/
function withdrawERC721(address recipient, address token, uint tokenId) external onlyRole(TREASURY_MANAGER) {
IERC721(token).transferFrom(address(this), recipient, tokenId);
emit WithdrawERC721(token, tokenId, recipient);
}
/**
* Allows an approved user to withdraw an ERC1155 token(s) from the Treasury.
*
* @param recipient The user that will receive the ERC1155 tokens
* @param token ERC1155 token address to be withdrawn
* @param tokenId The ID of the ERC1155 being withdrawn
* @param amount The number of tokens to withdraw
*/
function withdrawERC1155(address recipient, address token, uint tokenId, uint amount) external nonReentrant onlyRole(TREASURY_MANAGER) {
IERC1155(token).safeTransferFrom(address(this), recipient, tokenId, amount, '');
emit WithdrawERC1155(token, tokenId, amount, recipient);
}
/**
* Allows the {Treasury} to make a deposit directly into a {BaseStrategy} using
* the strategy ID. The function selector will need to be included in the `_data`
* parameter, along with the deposit related parameters.
*
* @param _strategyId The ID of the strategy to be depositted into
* @param _data Any bytes data that should be passed to the {IAction} execution function
* @param approvals Any tokens that need to be approved before actioning
*/
function strategyDeposit(
uint _strategyId,
bytes calldata _data,
ActionApproval[] calldata approvals
) external nonReentrant onlyRole(TREASURY_MANAGER) {
// Get our strategy address from the ID
address strategy = strategyFactory.strategy(_strategyId);
require(strategy != address(0), 'Invalid strategy');
uint ethValue;
uint approvalsLength = approvals.length;
for (uint i; i < approvalsLength;) {
if (approvals[i]._type == TreasuryEnums.ApprovalType.NATIVE) {
ethValue += approvals[i].amount;
} else if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC20) {
IERC20(approvals[i].assetContract).approve(approvals[i].target, approvals[i].amount);
} else if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC721) {
IERC1155(approvals[i].assetContract).setApprovalForAll(approvals[i].target, true);
} else if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC1155) {
IERC1155(approvals[i].assetContract).setApprovalForAll(approvals[i].target, true);
}
unchecked {
++i;
}
}
// Action our call against the target recipient
(bool success,) = strategy.call{value: ethValue}(_data);
require(success, 'Transaction failed');
// Remove approvals after execution
for (uint i; i < approvalsLength;) {
if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC20) {
IERC20(approvals[i].assetContract).approve(approvals[i].target, 0);
} else if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC721) {
IERC721(approvals[i].assetContract).setApprovalForAll(approvals[i].target, false);
} else if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC1155) {
IERC1155(approvals[i].assetContract).setApprovalForAll(approvals[i].target, false);
}
unchecked { ++i; }
}
}
/**
* Apply an action against the Treasury. If we need any tokens to be approved before the
* action is called, then these are approved before our call and approval is removed
* afterwards for 1155s.
*
* @param action Address of the action to apply
* @param approvals Any tokens that need to be approved before actioning
* @param data Any bytes data that should be passed to the {IAction} execution function
*/
function processAction(
address payable action,
ActionApproval[] calldata approvals,
bytes calldata data,
uint linkedSweepEpoch
)
external
nonReentrant
onlyRole(TREASURY_MANAGER)
{
uint ethValue;
uint approvalsLength = approvals.length;
for (uint i; i < approvalsLength;) {
if (approvals[i]._type == TreasuryEnums.ApprovalType.NATIVE) {
ethValue += approvals[i].amount;
} else if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC20) {
IERC20(approvals[i].assetContract).approve(approvals[i].target, approvals[i].amount);
} else if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC721) {
IERC1155(approvals[i].assetContract).setApprovalForAll(approvals[i].target, true);
} else if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC1155) {
IERC1155(approvals[i].assetContract).setApprovalForAll(approvals[i].target, true);
}
unchecked {
++i;
}
}
IAction(action).execute{value: ethValue}(data);
// Remove approvals after execution
for (uint i; i < approvalsLength;) {
if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC20) {
IERC20(approvals[i].assetContract).approve(approvals[i].target, 0);
} else if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC721) {
IERC721(approvals[i].assetContract).setApprovalForAll(approvals[i].target, false);
} else if (approvals[i]._type == TreasuryEnums.ApprovalType.ERC1155) {
IERC1155(approvals[i].assetContract).setApprovalForAll(approvals[i].target, false);
}
unchecked { ++i; }
}
emit ActionProcessed(action, data);
// If we have a sweep epoch index, then we can emit an event that will link the transaction
// to the epoch. This won't work for epoch 0, but we basically skip that one.
if (linkedSweepEpoch > 0) {
emit SweepAction(linkedSweepEpoch);
}
}
/**
* When an epoch ends, we have the ability to register a sweep against the {Treasury}
* via an approved contract. This will store a DAO sweep that will need to be actioned
* using the `sweepEpoch` function.
*
* @param epoch The current epoch that the sweep is generated from
* @param collections The collections that will be swept
* @param amounts The amount of ETH to sweep against each collection
*/
function registerSweep(uint epoch, address[] calldata collections, uint[] calldata amounts, TreasuryEnums.SweepType sweepType)
external
onlyRole(EPOCH_TRIGGER)
{
// Ensure that the epoch does not already have a completed sweep registered
require(!epochSweeps[epoch].completed, 'Epoch sweep already registered');
// Confirm that each collection has an amount
require(collections.length == amounts.length, 'Collections =/= amounts');
// Ensure that the sweep is not registered in the past
require(epoch >= currentEpoch(), 'Invalid sweep epoch');
// Register our sweep against the epoch. This value can be overwritten if another sweep
// is posted against the epoch, so this should be kept in mind during development.
epochSweeps[epoch] = Sweep({sweepType: sweepType, collections: collections, amounts: amounts, completed: false, message: ''});
emit SweepRegistered(epoch, sweepType, collections, amounts);
}
/**
* Actions a sweep to be used against a contract that implements {ISweeper}. This
* will fulfill the sweep and we then mark the sweep as completed.
*
* @param epochIndex The index of the `epochSweeps`
* @param sweeper The address of the sweeper contract to be used
* @param data Additional meta data to send to the sweeper
*/
function sweepEpoch(uint epochIndex, address sweeper, bytes calldata data, uint mercSweep) public nonReentrant {
// Load the stored sweep at our epoch index
Sweep memory epochSweep = epochSweeps[epochIndex];
// Ensure we have not already swept this epoch
require(!epochSweep.completed, 'Epoch sweep already completed');
/**
* Checks if the Epoch grace period has expired. This gives the DAO 1 epoch to action
* the sweep before allowing an external party to action on their behalf.
*
* Sweep Current
* 3 3 Not ended yet
* 3 4 Only DAO
* 3 5 DAO or 5,000 staked FLOOR power
*
* If the grace period has ended, then a user that holds 5,000 staked FLOOR power
* tokens can action the sweep to take place.
*/
uint _currentEpoch = currentEpoch();
// First we need to check that the epoch index has finished
require(epochIndex < _currentEpoch, 'Epoch has not finished');
// We can then assume that a `TreasuryManager` can always sweep the epoch
if (!hasRole(this.TREASURY_MANAGER(), msg.sender)) {
// If we are in the subsequent epoch, then we cannot allow a non-DAO sweep
if (address(veFloor) == address(0) || epochIndex + 1 == _currentEpoch) {
revert('Only DAO may currently execute');
}
// If we are beyond the subsequent epoch, then anyone with a locked voting
// power of 5000 tokens can execute.
require(veFloor.votingPowerOf(msg.sender) >= SWEEP_EXECUTE_TOKENS, 'Insufficient FLOOR holding');
}
return _sweepEpoch(epochIndex, sweeper, epochSweep, data, mercSweep);
}
/**
* Allows the DAO to resweep an already swept "Sweep" struct, using a contract that
* implements {ISweeper}. This will fulfill the sweep again and keep the sweep marked
* as completed.
*
* @dev This should only be used if there was an unexpected issue with the initial
* sweep that resulted in assets not being correctly acquired, but the epoch being
* marked as swept.
*
* @param epochIndex The index of the `epochSweeps`
* @param sweeper The address of the sweeper contract to be used
* @param data Additional meta data to send to the sweeper
*/
function resweepEpoch(uint epochIndex, address sweeper, bytes calldata data, uint mercSweep) public onlyRole(TREASURY_MANAGER) nonReentrant {
// Ensure that the epoch has already been swept. This ensures that we don't have to
// implement the same epoch constraints as these would have been present in the
// initial sweep.
require(epochSweeps[epochIndex].completed, 'Epoch not swept');
return _sweepEpoch(epochIndex, sweeper, epochSweeps[epochIndex], data, mercSweep);
}
/**
* Handles the logic to action a sweep.
*/
function _sweepEpoch(uint epochIndex, address sweeper, Sweep memory epochSweep, bytes calldata data, uint mercSweep) internal burnFloorTokens {
uint msgValue;
uint collectionsLength = epochSweep.collections.length;
// Ensure we have a valid sweep index
require(collectionsLength != 0, 'No collections to sweep');
// Confirm that our sweeper has been approved
require(approvedSweepers[sweeper], 'Sweeper contract not approved');
// Ensure that the caller has sufficient permissions
{
bytes32 sweeperPermissions = ISweeper(sweeper).permissions();
require(sweeperPermissions == '' || hasRole(sweeperPermissions, msg.sender), 'Invalid sweeper permissions');
}
// Add some additional logic around mercSweep specification and exit the process
// early to save wasted gas.
if (mercSweep != 0) {
require(epochSweep.sweepType == TreasuryEnums.SweepType.COLLECTION_ADDITION, 'Merc Sweep only available for collection additions');
require(address(mercSweeper) != address(0), 'Merc Sweeper not set');
msgValue = epochSweep.amounts[0];
require(mercSweep <= msgValue, 'Merc Sweep cannot be higher than msg.value');
} else {
// If this is COLLECTION_ADDITION, we will only ever a single collection, so
// no need for a loop.
if (epochSweep.sweepType == TreasuryEnums.SweepType.COLLECTION_ADDITION) {
msgValue = epochSweep.amounts[0];
} else {
// Find the total amount to send to the sweeper and transfer it before the call. We
// should always have at least one amount in the sweep, so we can save gas with a
// dowhile loop.
uint i;
do {
msgValue += epochSweep.amounts[i];
unchecked {
++i;
}
} while (i < collectionsLength);
}
}
// Check if we have sufficient ETH holdings and then withdraw the required
// remaining from WETH to power the upcoming sweep.
uint ethBalance = address(this).balance;
if (msgValue > ethBalance) {
weth.withdraw(msgValue - ethBalance);
}
// If we have specified mercenary staked NFTs to be swept then we need to
// action that sweep and remove the value swept from the future sweep amount.
if (mercSweep != 0) {
// Fire our request to our mercenary sweeper contract, which will return the
// amount actually spent on the sweep. We should only have a single value in
// the collections and amounts arrays, but the sweeper will handle this.
uint spend = mercSweeper.execute{value: msgValue}(epochManager.collectionEpochs(epochIndex), mercSweep);
// Reduce the remaining message value sent to the subsequent sweeper
unchecked { msgValue -= spend; }
epochSweep.amounts[0] = msgValue;
}
// Mark our sweep as completed
epochSweep.completed = true;
// Action our sweep. If we don't hold enough ETH to supply the message value then
// we expect this call to revert. This call may optionally return a message that
// will be stored against the struct.
epochSweep.message = ISweeper(sweeper).execute{value: msgValue}(epochSweep.collections, epochSweep.amounts, data);
// Write our sweep
epochSweeps[epochIndex] = epochSweep;
// Fire an event for anyone listening to sweeps
emit EpochSwept(epochIndex);
}
/**
* Allows the mercenary sweeper contract to be updated.
*
* @dev We allow for a zero-address as this will disable the functionality.
*
* @param _mercSweeper the new {IMercenarySweeper} contract
*/
function setMercenarySweeper(address _mercSweeper) external onlyRole(TREASURY_MANAGER) {
mercSweeper = IMercenarySweeper(_mercSweeper);
emit MercenarySweeperUpdated(_mercSweeper);
}
/**
* Allows a sweeper contract to be approved or uapproved. This must be done before
* a contract can be referenced in the `sweepEpoch` and `resweepEpoch` calls.
*
* @param _sweeper The address of the sweeper contract
* @param _approved True to approve, False to unapprove
*/
function approveSweeper(address _sweeper, bool _approved) external onlyRole(TREASURY_MANAGER) {
if (_sweeper == address(0)) revert CannotSetNullAddress();
approvedSweepers[_sweeper] = _approved;
}
/**
* Allows us to set a minimum amount of ETH to sweep with, so that if the yield
* allocated to the sweep is too low to be beneficial, then the DAO can stomache
* the additional cost.
*
* @param _minSweepAmount The minimum amount of ETH to sweep with
*/
function setMinSweepAmount(uint _minSweepAmount) external onlyRole(TREASURY_MANAGER) {
minSweepAmount = _minSweepAmount;
emit MinSweepAmountUpdated(_minSweepAmount);
}
/**
* Allows us to set a new VeFloorStaking contract that is used when sweeping epochs.
*
* @dev We allow this to be a zero-address to disable public sweeping
*
* @param _veFloorStaking New VeFloorStaking contract
*/
function setVeFloorStaking(address _veFloorStaking) external onlyRole(TREASURY_MANAGER) {
veFloor = VeFloorStaking(_veFloorStaking);
emit VeFloorStakingUpdated(_veFloorStaking);
}
/**
* Allows us to set a new {StrategyFactory} contract that is used when making strategy deposits.
*
* @param _strategyFactory New StrategyFactory contract address
*/
function setStrategyFactory(address _strategyFactory) external onlyRole(TREASURY_MANAGER) {
if (_strategyFactory == address(0)) revert CannotSetNullAddress();
strategyFactory = StrategyFactory(_strategyFactory);
emit StrategyFactoryUpdated(_strategyFactory);
}
/**
* Checks if any FLOOR tokens have been received during the transaction and then
* burns them afterwards.
*/
modifier burnFloorTokens() {
uint startBalance = floor.balanceOf(address(this));
_;
uint endBalance = floor.balanceOf(address(this));
if (endBalance > startBalance) {
unchecked {
floor.burn(endBalance - startBalance);
}
}
}
/**
* If we receive a direct ERC721 safeTransfer, then we additionally need to handle this
* and fire an event.
*/
function onERC721Received(address token, address, uint tokenId, bytes memory) public virtual returns (bytes4) {
emit DepositERC721(token, tokenId);
return this.onERC721Received.selector;
}
/**
* If we receive a direct ERC1155 safeTransfer, then we additionally need to handle this
* and fire an event.
*/
function onERC1155Received(address token, address, uint tokenId, uint amount, bytes memory) public virtual override returns (bytes4) {
emit DepositERC1155(token, tokenId, amount);
return this.onERC1155Received.selector;
}
/**
* If we receive a direct batch of ERC1155 safeTransfer, then we additionally need to
* handle this and fire an event for each token received.
*/
function onERC1155BatchReceived(address token, address, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory) public virtual override returns (bytes4) {
for (uint i; i < tokenIds.length;) {
emit DepositERC1155(token, tokenIds[i], amounts[i]);
unchecked { ++i; }
}
return this.onERC1155BatchReceived.selector;
}
/**
* Expose that we support interfaces for ERC721 and ERC1155 safeTramsfer.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return (
interfaceId == this.onERC721Received.selector ||
interfaceId == this.onERC1155Received.selector ||
interfaceId == this.onERC1155BatchReceived.selector
);
}
/**
* Allow our contract to receive native tokens.
*/
receive() external payable {
emit Deposit(msg.value);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../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.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155.sol)
pragma solidity ^0.8.0;
import "../token/ERC1155/IERC1155.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol)
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721.sol";
lib/openzeppelin-contracts/contracts/proxy/Clones.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/Clones.sol)
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create(0, 0x09, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create2(0, 0x09, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(add(ptr, 0x38), deployer)
mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
mstore(add(ptr, 0x14), implementation)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
mstore(add(ptr, 0x58), salt)
mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
predicted := keccak256(add(ptr, 0x43), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
}
lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
}
lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] calldata accounts,
uint256[] calldata ids
) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol)
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
*
* IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
* stuck.
*
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
lib/openzeppelin-contracts/contracts/token/ERC1155/utils/ERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* 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 ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these 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 override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override 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 override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override 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 `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` 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 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* 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 `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `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.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` 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.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Burnable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20.sol";
import "../../../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 `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` 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
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/cryptography/EIP712.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private constant _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
* However, to ensure consistency with the upgradeable transpiler, we will continue
* to reserve a slot.
* @custom:oz-renamed-from _PERMIT_TYPEHASH
*/
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;
/**
* @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 ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired 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);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
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);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
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].
*/
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);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// EIP-2612 is Final as of 2022-11-01. This file is deprecated.
import "./IERC20Permit.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
lib/openzeppelin-contracts/contracts/utils/Counters.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @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,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode 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 {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]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
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.
/// @solidity memory-safe-assembly
assembly {
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);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode 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 {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
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[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
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.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// 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);
}
// 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);
}
return (signer, RecoverError.NoError);
}
/**
* @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) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic 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 their contracts 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].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// 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 _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @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) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, 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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
lib/solidity-utils/contracts/interfaces/IDaiLikePermit.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v1;
interface IDaiLikePermit {
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
lib/solidity-utils/contracts/interfaces/IPermit2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPermit2 {
struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice The permit message signed for a single token allownce
struct PermitSingle {
// the permit data for a single token alownce
PermitDetails details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice Packed allowance
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
function transferFrom(address user, address spender, uint160 amount, address token) external;
function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
function allowance(address user, address token, address spender) external view returns (PackedAllowance memory);
}
lib/solidity-utils/contracts/libraries/RevertReasonForwarder.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v1;
/// @title Revert reason forwarder.
library RevertReasonForwarder {
/// @dev Forwards latest externall call revert.
function reRevert() internal pure {
// bubble up revert reason from latest external call
/// @solidity memory-safe-assembly
assembly { // solhint-disable-line no-inline-assembly
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
}
}
lib/solidity-utils/contracts/libraries/SafeERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v1;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "../interfaces/IDaiLikePermit.sol";
import "../interfaces/IPermit2.sol";
import "../libraries/RevertReasonForwarder.sol";
/// @title Implements efficient safe methods for ERC20 interface.
library SafeERC20 {
error SafeTransferFailed();
error SafeTransferFromFailed();
error ForceApproveFailed();
error SafeIncreaseAllowanceFailed();
error SafeDecreaseAllowanceFailed();
error SafePermitBadLength();
address private constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
bytes4 private constant _PERMIT_LENGHT_ERROR = 0x68275857; // SafePermitBadLength.selector
/// @dev Ensures method do not revert or return boolean `true`, admits call to non-smart-contract.
function safeTransferFromUniversal(
IERC20 token,
address from,
address to,
uint256 amount,
bool permit2
) internal {
if (permit2) {
safeTransferFromPermit2(token, from, to, amount);
} else {
safeTransferFrom(token, from, to, amount);
}
}
/// @dev Ensures method do not revert or return boolean `true`, admits call to non-smart-contract.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
bytes4 selector = token.transferFrom.selector;
bool success;
/// @solidity memory-safe-assembly
assembly { // solhint-disable-line no-inline-assembly
let data := mload(0x40)
mstore(data, selector)
mstore(add(data, 0x04), from)
mstore(add(data, 0x24), to)
mstore(add(data, 0x44), amount)
success := call(gas(), token, 0, data, 100, 0x0, 0x20)
if success {
switch returndatasize()
case 0 {
success := gt(extcodesize(token), 0)
}
default {
success := and(gt(returndatasize(), 31), eq(mload(0), 1))
}
}
}
if (!success) revert SafeTransferFromFailed();
}
/// @dev Permit2 version of safeTransferFrom above.
function safeTransferFromPermit2(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
bytes4 selector = IPermit2.transferFrom.selector;
bool success;
/// @solidity memory-safe-assembly
assembly { // solhint-disable-line no-inline-assembly
let data := mload(0x40)
mstore(data, selector)
mstore(add(data, 0x04), from)
mstore(add(data, 0x24), to)
mstore(add(data, 0x44), amount)
mstore(add(data, 0x64), token)
success := call(gas(), _PERMIT2, 0, data, 0x84, 0x0, 0x20)
if success {
switch returndatasize()
case 0 {
success := gt(extcodesize(token), 0)
}
default {
success := and(gt(returndatasize(), 31), eq(mload(0), 1))
}
}
}
if (!success) revert SafeTransferFromFailed();
}
/// @dev Ensures method do not revert or return boolean `true`, admits call to non-smart-contract.
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
if (!_makeCall(token, token.transfer.selector, to, value)) {
revert SafeTransferFailed();
}
}
/// @dev If `approve(from, to, amount)` fails, try to `approve(from, to, 0)` before retry.
function forceApprove(
IERC20 token,
address spender,
uint256 value
) internal {
if (!_makeCall(token, token.approve.selector, spender, value)) {
if (
!_makeCall(token, token.approve.selector, spender, 0) ||
!_makeCall(token, token.approve.selector, spender, value)
) {
revert ForceApproveFailed();
}
}
}
/// @dev Allowance increase with safe math check.
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 allowance = token.allowance(address(this), spender);
if (value > type(uint256).max - allowance) revert SafeIncreaseAllowanceFailed();
forceApprove(token, spender, allowance + value);
}
/// @dev Allowance decrease with safe math check.
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 allowance = token.allowance(address(this), spender);
if (value > allowance) revert SafeDecreaseAllowanceFailed();
forceApprove(token, spender, allowance - value);
}
function safePermit(IERC20 token, bytes calldata permit) internal {
if (!tryPermit(token, msg.sender, address(this), permit)) RevertReasonForwarder.reRevert();
}
function safePermit(IERC20 token, address owner, address spender, bytes calldata permit) internal {
if (!tryPermit(token, owner, spender, permit)) RevertReasonForwarder.reRevert();
}
function tryPermit(IERC20 token, bytes calldata permit) internal returns(bool success) {
return tryPermit(token, msg.sender, address(this), permit);
}
function tryPermit(IERC20 token, address owner, address spender, bytes calldata permit) internal returns(bool success) {
bytes4 permitSelector = IERC20Permit.permit.selector;
bytes4 daiPermitSelector = IDaiLikePermit.permit.selector;
bytes4 permit2Selector = IPermit2.permit.selector;
/// @solidity memory-safe-assembly
assembly { // solhint-disable-line no-inline-assembly
let ptr := mload(0x40)
switch permit.length
case 100 {
mstore(ptr, permitSelector)
mstore(add(ptr, 0x04), owner)
mstore(add(ptr, 0x24), spender)
// Compact IERC20Permit.permit(uint256 value, uint32 deadline, uint256 r, uint256 vs)
{ // stack too deep
let deadline := shr(224, calldataload(add(permit.offset, 0x20)))
let vs := calldataload(add(permit.offset, 0x44))
calldatacopy(add(ptr, 0x44), permit.offset, 0x20) // value
mstore(add(ptr, 0x64), sub(deadline, 1))
mstore(add(ptr, 0x84), add(27, shr(255, vs)))
calldatacopy(add(ptr, 0xa4), add(permit.offset, 0x24), 0x20) // r
mstore(add(ptr, 0xc4), shr(1, shl(1, vs)))
}
// IERC20Permit.permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s)
success := call(gas(), token, 0, ptr, 0xe4, 0, 0)
}
case 72 {
mstore(ptr, daiPermitSelector)
mstore(add(ptr, 0x04), owner)
mstore(add(ptr, 0x24), spender)
// Compact IDaiLikePermit.permit(uint32 nonce, uint32 expiry, uint256 r, uint256 vs)
{ // stack too deep
let nonce := shr(224, calldataload(permit.offset))
let expiry := shr(224, calldataload(add(permit.offset, 0x04)))
let vs := calldataload(add(permit.offset, 0x28))
mstore(add(ptr, 0x44), nonce)
mstore(add(ptr, 0x64), sub(expiry, 1))
mstore(add(ptr, 0x84), true)
mstore(add(ptr, 0xa4), add(27, shr(255, vs)))
calldatacopy(add(ptr, 0xc4), add(permit.offset, 0x08), 0x20) // r
mstore(add(ptr, 0xe4), shr(1, shl(1, vs)))
}
// IDaiLikePermit.permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s)
success := call(gas(), token, 0, ptr, 0x104, 0, 0)
}
case 224 {
mstore(ptr, permitSelector)
calldatacopy(add(ptr, 0x04), permit.offset, permit.length)
// IERC20Permit.permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s)
success := call(gas(), token, 0, ptr, add(4, permit.length), 0, 0)
}
case 256 {
mstore(ptr, daiPermitSelector)
calldatacopy(add(ptr, 0x04), permit.offset, permit.length)
// IDaiLikePermit.permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s)
success := call(gas(), token, 0, ptr, add(4, permit.length), 0, 0)
}
case 384 {
mstore(ptr, permit2Selector)
calldatacopy(add(ptr, 0x04), permit.offset, permit.length)
success := call(gas(), _PERMIT2, 0, ptr, add(4, permit.length), 0, 0)
}
// TODO: add case for compact permit2
default {
mstore(ptr, _PERMIT_LENGHT_ERROR)
revert(ptr, 4)
}
}
}
function _makeCall(
IERC20 token,
bytes4 selector,
address to,
uint256 amount
) private returns (bool success) {
/// @solidity memory-safe-assembly
assembly { // solhint-disable-line no-inline-assembly
let data := mload(0x40)
mstore(data, selector)
mstore(add(data, 0x04), to)
mstore(add(data, 0x24), amount)
success := call(gas(), token, 0, data, 0x44, 0x0, 0x20)
if success {
switch returndatasize()
case 0 {
success := gt(extcodesize(token), 0)
}
default {
success := and(gt(returndatasize(), 31), eq(mload(0), 1))
}
}
}
}
}
src/contracts/authorities/AuthorityControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Context} from '@openzeppelin/contracts/utils/Context.sol';
import {CannotSetNullAddress} from '@floor/utils/Errors.sol';
import {IAuthorityControl} from '@floor-interfaces/authorities/AuthorityControl.sol';
import {IAuthorityRegistry} from '@floor-interfaces/authorities/AuthorityRegistry.sol';
/// If the account does not have the required role for the call.
/// @param caller The address making the call
/// @param role The role that is required for the call
error AccountDoesNotHaveRole(address caller, bytes32 role);
/// If the account does not have the required admin role for the call.
/// @param caller The address making the call
error AccountDoesNotHaveAdminRole(address caller);
/**
* This contract is heavily based on the standardised OpenZeppelin `AccessControl` library.
* This allows for the creation of role based access levels that can be assigned to 1-n
* addresses.
*
* Contracts will be able to implement the AuthorityControl to provide access to the `onlyRole` modifier or the
* `hasRole` function. This will ensure that the `msg.sender` is allowed to perform an action.
*
* 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:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("TreasuryManager");
* ```
*/
contract AuthorityControl is Context, IAuthorityControl {
/// CollectionManager - Can approve token addresses to be allowed to be used in strategies
bytes32 public constant COLLECTION_MANAGER = keccak256('CollectionManager');
/// EpochTrigger - Can run epoch trigger contract specific logic
bytes32 public constant EPOCH_TRIGGER = keccak256('EpochTrigger');
/// FloorManager - Can mint and manage Floor and VeFloor tokens
bytes32 public constant FLOOR_MANAGER = keccak256('FloorManager');
/// Governor - A likely DAO owned vote address to allow for wide scale decisions to
/// be made and implemented.
bytes32 public constant GOVERNOR = keccak256('Governor');
/// Guardian - Wallet address that will allow for Governor based actions, except without
/// timeframe restrictions.
bytes32 public constant GUARDIAN = keccak256('Guardian');
/// TreasuryManager - Access to Treasury asset management
bytes32 public constant TREASURY_MANAGER = keccak256('TreasuryManager');
/// StrategyManager - Can create new strategies against approved strategies and collections
bytes32 public constant STRATEGY_MANAGER = keccak256('StrategyManager');
/// VoteManager - Can manage account votes
bytes32 public constant VOTE_MANAGER = keccak256('VoteManager');
/// Reference to the {AuthorityRegistry} contract that maintains role allocations
IAuthorityRegistry public immutable registry;
/**
* Modifier that checks that an account has a specific role. Reverts with a
* standardized message if user does not have specified role.
*
* @param role The keccak256 encoded role string
*/
modifier onlyRole(bytes32 role) {
if (!registry.hasRole(role, _msgSender())) {
revert AccountDoesNotHaveRole(_msgSender(), role);
}
_;
}
/**
* Modifier that checks that an account has a governor or guardian role.
* Reverts with a standardized message if sender does not have an admin role.
*/
modifier onlyAdminRole() {
if (!registry.hasAdminRole(_msgSender())) {
revert AccountDoesNotHaveAdminRole(_msgSender());
}
_;
}
/**
* The address that deploys the {AuthorityControl} becomes the default controller. This
* can only be overwritten by the existing.
*
* @param _registry The address of our deployed AuthorityRegistry contract
*/
constructor(address _registry) {
if (_registry == address(0)) revert CannotSetNullAddress();
registry = IAuthorityRegistry(_registry);
}
/**
* Returns `true` if `account` has been granted `role`.
*
* @param role The keccak256 encoded role string
* @param account Address to check ownership of role
*
* @return bool If the address has the specified user role
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return registry.hasRole(role, account);
}
/**
* Returns `true` if `account` has been granted either GOVERNOR or GUARDIAN role.
*
* @param account Address to check ownership of role
*
* @return bool If the address has the GOVERNOR or GUARDIAN role
*/
function hasAdminRole(address account) public view returns (bool) {
return registry.hasAdminRole(account);
}
}
src/contracts/staking/VeFloorStaking.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeERC20} from '@1inch/solidity-utils/contracts/libraries/SafeERC20.sol';
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import {Address} from '@openzeppelin/contracts/utils/Address.sol';
import {Math} from '@openzeppelin/contracts/utils/math/Math.sol';
import {CannotSetNullAddress, TransferFailed} from '@floor/utils/Errors.sol';
import {EpochManaged} from '@floor/utils/EpochManaged.sol';
import {IVeFloorStaking, Depositor} from '@floor-interfaces/staking/VeFloorStaking.sol';
import {IERC20, IVotable} from '@floor-interfaces/tokens/Votable.sol';
import {INewCollectionWars} from '@floor-interfaces/voting/NewCollectionWars.sol';
import {ISweepWars} from '@floor-interfaces/voting/SweepWars.sol';
import {ITreasury} from '@floor-interfaces/Treasury.sol';
/**
* @title FLOOR Staking
* @notice The contract provides the following features: staking, delegation, farming
* How lock period works:
* - balances and voting power
* - Lock min and max
* - Add lock
* - earlyWithdrawal
* - penalty math
*
* @dev Based on staked 1inch (St1inch :: 0x9A0C8Ff858d273f57072D714bca7411D717501D7)
*/
contract VeFloorStaking is EpochManaged, ERC20, IVeFloorStaking, IVotable {
using SafeERC20 for IERC20;
event EmergencyExitSet(bool status);
event MaxLossRatioSet(uint ratio);
event MinLockPeriodRatioSet(uint ratio);
event FeeReceiverSet(address receiver);
event EarlyWithdrawFeeExemptionSet(address account, bool exempt);
event Deposit(address account, uint amount);
event Withdraw(address sender, uint amount);
error ApproveDisabled();
error TransferDisabled();
error UnlockTimeHasNotCome();
error StakeUnlocked();
error MinLockPeriodRatioNotReached();
error MinReturnIsNotMet();
error MaxLossIsNotMet();
error MaxLossUnderflow();
error MaxLossOverflow();
error LossIsTooBig();
error RescueAmountIsTooLarge();
error ExpBaseTooBig();
error ExpBaseTooSmall();
error DepositsDisabled();
error ZeroAddress();
/// Set a list of locking periods that the user can lock for
uint8[] public LOCK_PERIODS = [uint8(2), 3, 4, 6];
/// Our FLOOR token
IERC20 public immutable floor;
/// Our internal contracts
ITreasury public immutable treasury;
INewCollectionWars public newCollectionWars;
ISweepWars public sweepWars;
/// Allow some addresses to be exempt from early withdraw fees
mapping(address => bool) public earlyWithdrawFeeExemptions;
/// Map our Depositor index against a user
mapping(address => Depositor) public depositors;
uint internal constant _ONE_E9 = 1e9;
uint public totalDeposits;
bool public emergencyExit;
uint public maxLossRatio;
uint public minLockPeriodRatio;
address public feeReceiver;
/**
* @notice Initializes the contract
* @param floor_ The token to be staked
* @param treasury_ The treasury contract address
*/
constructor(IERC20 floor_, address treasury_) ERC20('veFLOOR', 'veFLOOR') {
if (address(floor_) == address(0) || treasury_ == address(0)) revert CannotSetNullAddress();
floor = floor_;
treasury = ITreasury(treasury_);
setFeeReceiver(treasury_);
}
/**
* @notice Sets the new contract that would recieve early withdrawal fees
* @param feeReceiver_ The receiver contract address
*/
function setFeeReceiver(address feeReceiver_) public onlyOwner {
feeReceiver = feeReceiver_;
emit FeeReceiverSet(feeReceiver_);
}
/**
* @notice Sets the maximum allowed loss ratio for early withdrawal. If the ratio is not met, actual is more than allowed,
* then early withdrawal will revert.
* Example: maxLossRatio = 90% and 1000 staked floor tokens means that a user can execute early withdrawal only
* if his loss is less than or equals 90% of his stake, which is 900 tokens. Thus, if a user loses 900 tokens he is allowed
* to do early withdrawal and not if the loss is greater.
* @param maxLossRatio_ The maximum loss allowed (9 decimals).
*/
function setMaxLossRatio(uint maxLossRatio_) external onlyOwner {
if (maxLossRatio_ > _ONE_E9) revert MaxLossOverflow();
maxLossRatio = maxLossRatio_;
emit MaxLossRatioSet(maxLossRatio_);
}
/**
* @notice Sets the minimum allowed lock period ratio for early withdrawal. If the ratio is not met, actual is more than allowed,
* then early withdrawal will revert.
* @param minLockPeriodRatio_ The maximum loss allowed (9 decimals).
*/
function setMinLockPeriodRatio(uint minLockPeriodRatio_) external onlyOwner {
if (minLockPeriodRatio_ > _ONE_E9) revert MaxLossOverflow();
if ((minLockPeriodRatio_ * LOCK_PERIODS[0]) / _ONE_E9 == 0) revert MaxLossUnderflow();
minLockPeriodRatio = minLockPeriodRatio_;
emit MinLockPeriodRatioSet(minLockPeriodRatio_);
}
/**
* @notice Sets the emergency exit mode. In emergency mode any stake may withdraw its stake regardless of lock.
* The mode is intended to use only for migration to a new version of staking contract.
* @param emergencyExit_ set `true` to enter emergency exit mode and `false` to return to normal operations
*/
function setEmergencyExit(bool emergencyExit_) external onlyOwner {
emergencyExit = emergencyExit_;
emit EmergencyExitSet(emergencyExit_);
}
/**
* @notice Gets the voting power of the provided account
* @param account The address of an account to get voting power for
* @return votingPower The voting power available at the current epoch
*/
function votingPowerOf(address account) public view returns (uint) {
return (depositors[account].amount * depositors[account].epochCount) / LOCK_PERIODS[LOCK_PERIODS.length - 1];
}
/**
* @notice Stakes given amount and locks it for the given duration
*/
function deposit(uint amount, uint epochs) external {
_deposit(msg.sender, amount, epochs);
}
function _deposit(address account, uint amount, uint epochs) private {
// If emergency exit is enabled, then we don't accept deposits
if (emergencyExit) revert DepositsDisabled();
// Load our depositor with a single SLOAD
Depositor memory depositor = depositors[account];
// Validate our epoch index key
require(epochs < LOCK_PERIODS.length, 'Invalid epoch index');
// Ensure that the user is not trying to stake for less than the duration of epochs
// that are currently remaining on their stake.
uint _currentEpoch = currentEpoch();
require(_currentEpoch + LOCK_PERIODS[epochs] >= depositor.epochStart + depositor.epochCount, 'Cannot stake less epochs');
// Update the depositor lock to the current epoch
depositor.epochStart = uint160(_currentEpoch);
depositor.epochCount = LOCK_PERIODS[epochs];
// If we are staking additional tokens, then transfer the based FLOOR from the user
// and mint veFloor tokens to the recipient `account`.
if (amount > 0) {
// Take FLOOR tokens from the sender and mint them veFloor
floor.safeTransferFrom(msg.sender, address(this), amount);
_mint(account, amount);
// Increase our tracked amounts
depositor.amount += uint88(amount);
totalDeposits += amount;
}
// SSTORE our updated depositor data
depositors[account] = depositor;
emit Deposit(account, amount);
}
/**
* @notice Withdraw stake before lock period expires at the cost of losing part of a stake.
* The stake loss is proportional to the time passed from the maximum lock period to the lock expiration and voting power.
* The more time is passed the less would be the loss.
* Formula to calculate return amount = (deposit - voting power)) / 0.95
* @param minReturn The minumum amount of stake acceptable for return. If actual amount is less then the transaction is reverted
* @param maxLoss The maximum amount of loss acceptable. If actual loss is bigger then the transaction is reverted
*/
function earlyWithdraw(uint minReturn, uint maxLoss) external {
earlyWithdrawTo(msg.sender, minReturn, maxLoss);
}
/**
* @notice Withdraw stake before lock period expires at the cost of losing part of a stake to the specified account
* The stake loss is proportional to the time passed from the maximum lock period to the lock expiration and voting power.
* The more time is passed the less would be the loss.
* Formula to calculate return amount = (deposit - voting power)) / 0.95
* @param to The account to withdraw the stake to
* @param minReturn The minumum amount of stake acceptable for return. If actual amount is less then the transaction is reverted
* @param maxLoss The maximum amount of loss acceptable. If actual loss is bigger then the transaction is reverted
*/
function earlyWithdrawTo(address to, uint minReturn, uint maxLoss) public {
Depositor memory depositor = depositors[msg.sender]; // SLOAD
// Get the amount that has been deposited and ensure that there is an amount to
// be withdrawn at all.
uint amount = depositor.amount;
if (amount == 0) {
return;
}
// Check if stake is already fully unlocked, meaning that we don't need to early exit
uint _currentEpoch = currentEpoch();
if (emergencyExit || _currentEpoch >= depositor.epochStart + depositor.epochCount) revert StakeUnlocked();
// Determine when our earliest exit epoch is ensures that we have passed it. This is
// determined by the `minLockPeriodRatio` variable to calculate how much for the `epochCount`
// has passed from the `epochStart`.
uint allowedExitEpoch = depositor.epochStart + depositor.epochCount * minLockPeriodRatio / _ONE_E9;
if (_currentEpoch < allowedExitEpoch) revert MinLockPeriodRatioNotReached();
// Check if the called is exempt from being required to pay early withdrawal fees
if (isExemptFromEarlyWithdrawFees(msg.sender)) {
_withdraw(depositor, amount);
floor.safeTransfer(to, amount);
return;
}
(uint loss, uint ret) = _earlyWithdrawLoss(depositor, amount);
if (ret < minReturn) revert MinReturnIsNotMet();
if (loss > maxLoss) revert MaxLossIsNotMet();
if (loss > amount * maxLossRatio / _ONE_E9) revert LossIsTooBig();
_withdraw(depositor, amount);
floor.safeTransfer(to, ret);
if (!floor.transfer(feeReceiver, loss)) revert TransferFailed();
}
/**
* @notice Gets the loss amount if the staker do early withdrawal at the current block
* @param account The account to calculate early withdrawal loss for
* @return loss The loss amount
* @return ret The return amount
* @return canWithdraw True if the staker can withdraw without penalty, false otherwise
*/
function earlyWithdrawLoss(address account) external view returns (uint loss, uint ret, bool canWithdraw) {
Depositor memory depositor = depositors[account]; // SLOAD
(loss, ret) = _earlyWithdrawLoss(depositor, depositor.amount);
canWithdraw = loss <= depositor.amount * maxLossRatio / _ONE_E9;
}
function _earlyWithdrawLoss(Depositor memory depositor, uint depAmount) private view returns (uint loss, uint ret) {
// If the current epoch is after the end of the lock, then we can assume there is
// no early exit loss as their stake is now fully available.
uint _currentEpoch = currentEpoch();
if (_currentEpoch > depositor.epochStart + depositor.epochCount) {
return (0, depAmount);
}
// Determine the power that is actually applied to the user currently based on their
// staked amount and the comparative lock length.
uint power = (depAmount * depositor.epochCount) / LOCK_PERIODS[LOCK_PERIODS.length - 1];
// If we still have the full duration remaining then we don't need to do any
// further calculations.
if (depositor.epochStart == _currentEpoch) {
return (power, depAmount - power);
}
// Determine the number of epochs remaining in the stake. This is already overflow
// checked from the above conditional.
uint remaining = depositor.epochCount - (_currentEpoch - depositor.epochStart);
// Calculate the early withdrawal fee by determining the "per epoch" power generated
// and then charging a penalty for the number of remaining epochs. This determines the
// penalty based on the power, and not the total amount deposited.
loss = (power / depositor.epochCount) * remaining;
ret = depAmount - loss;
}
/**
* @notice Withdraws stake if lock period expired
*/
function withdraw() external {
withdrawTo(msg.sender);
}
/**
* @notice Withdraws stake if lock period expired to the given address
*/
function withdrawTo(address to) public {
Depositor memory depositor = depositors[msg.sender]; // SLOAD
if (!emergencyExit && currentEpoch() < depositor.epochStart + depositor.epochCount) revert UnlockTimeHasNotCome();
uint amount = depositor.amount;
if (amount > 0) {
_withdraw(depositor, balanceOf(msg.sender));
floor.safeTransfer(to, amount);
}
}
/**
* Handles our internal logic to process a withdrawal for a depositor.
*
* @param depositor The structure for the user making the withdrawal
* @param balance The amount that the user is trying to withdraw
*/
function _withdraw(Depositor memory depositor, uint balance) private {
totalDeposits -= depositor.amount;
depositor.amount = 0;
depositor.epochStart = 0;
depositor.epochCount = 0;
depositors[msg.sender] = depositor; // SSTORE
if (address(newCollectionWars) != address(0)) {
newCollectionWars.revokeVotes(msg.sender);
}
if (address(sweepWars) != address(0)) {
sweepWars.revokeAllUserVotes(msg.sender);
}
_burn(msg.sender, balance);
emit Withdraw(msg.sender, balance);
}
/**
* When a vote or action is cast in the system, then we need to reset the token lock
* period to ensure that the minimum locking threshold is met.
*/
function refreshLock(address account) external {
require(msg.sender == address(newCollectionWars) || msg.sender == address(sweepWars), 'Invalid caller');
// Load our depositor with a single SLOAD
Depositor memory depositor = depositors[account];
// Capture our current epoch to prevent multiple future reads
uint currentEpoch = currentEpoch();
// If we have implemented delayed staking, then this sense check will prevent
// unexpected revert errors.
if (depositor.epochStart > currentEpoch) {
return;
}
// Ensure that the user is within, or has gone past, the smallest lock window
if ((currentEpoch - depositor.epochStart) + LOCK_PERIODS[0] <= depositor.epochCount) {
return;
}
// Update the depositor lock to the current epoch
depositor.epochStart = uint160((currentEpoch + LOCK_PERIODS[0]) - depositor.epochCount);
// SSTORE our updated depositor data
depositors[account] = depositor;
emit Deposit(account, 0);
}
/**
* Allows our voting contract addresses to be updated.
*/
function setVotingContracts(address _newCollectionWars, address _sweepWars) external onlyOwner {
newCollectionWars = INewCollectionWars(_newCollectionWars);
sweepWars = ISweepWars(_sweepWars);
}
/**
* @notice Retrieves funds from the contract in emergency situations
* @param token The token to retrieve
* @param amount The amount of funds to transfer
*/
function rescueFunds(IERC20 token, uint amount) external onlyOwner {
if (address(token) == address(0)) {
Address.sendValue(payable(msg.sender), amount);
} else {
if (token == floor) {
if (amount > floor.balanceOf(address(this)) - totalDeposits) revert RescueAmountIsTooLarge();
}
token.safeTransfer(msg.sender, amount);
}
}
/**
* Checks if an address is exempt from having to pay early withdrawal fees.
*
* @param account Address of the account to check
*
* @return bool True if the user is exempt from early fees, false if not
*/
function isExemptFromEarlyWithdrawFees(address account) public view returns (bool) {
return earlyWithdrawFeeExemptions[account];
}
/**
* Allows an account to be exempted from paying early withdraw fees.
*
* @param account The account to update
* @param exempt If the account is to be exempt from fees
*/
function addEarlyWithdrawFeeExemption(address account, bool exempt) external onlyOwner {
earlyWithdrawFeeExemptions[account] = exempt;
emit EarlyWithdrawFeeExemptionSet(account, exempt);
}
// ERC20 methods disablers
function approve(address, uint) public pure override (IERC20, ERC20) returns (bool) {
revert ApproveDisabled();
}
function transfer(address, uint) public pure override (IERC20, ERC20) returns (bool) {
revert TransferDisabled();
}
function transferFrom(address, address, uint) public pure override (IERC20, ERC20) returns (bool) {
revert TransferDisabled();
}
function increaseAllowance(address, uint) public pure override returns (bool) {
revert ApproveDisabled();
}
function decreaseAllowance(address, uint) public pure override returns (bool) {
revert ApproveDisabled();
}
// The following functions are overrides required by Solidity.
function _afterTokenTransfer(address from, address to, uint amount) internal override (ERC20) {
super._afterTokenTransfer(from, to, amount);
}
function _mint(address to, uint amount) internal override (ERC20) {
super._mint(to, amount);
}
function _burn(address account, uint amount) internal override (ERC20) {
super._burn(account, amount);
}
}
src/contracts/strategies/StrategyFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {Clones} from '@openzeppelin/contracts/proxy/Clones.sol';
import {AuthorityControl} from '@floor/authorities/AuthorityControl.sol';
import {CannotSetNullAddress, CollectionNotApproved, StrategyNotApproved} from '@floor/utils/Errors.sol';
import {ICollectionRegistry} from '@floor-interfaces/collections/CollectionRegistry.sol';
import {IBaseStrategy} from '@floor-interfaces/strategies/BaseStrategy.sol';
import {IStrategyFactory} from '@floor-interfaces/strategies/StrategyFactory.sol';
import {IStrategyRegistry} from '@floor-interfaces/strategies/StrategyRegistry.sol';
import {ITreasury} from '@floor-interfaces/Treasury.sol';
// No empty names, that's just silly
error StrategyNameCannotBeEmpty();
/**
* Allows for strategies to be created, pairing them with an approved collection. The strategy
* creation script needs to be as highly optimised as possible to ensure that the gas
* costs are kept down.
*
* This factory will keep an index of created strategies and secondary information to ensure
* that external applications can display and maintain a list of available strategies.
*/
contract StrategyFactory is AuthorityControl, IStrategyFactory {
/// Maintains an array of all strategies created
address[] private _strategies;
/// Store our Treasury address
address public treasury;
/// Contract mappings to our approved collections
ICollectionRegistry public immutable collectionRegistry;
/// Contract mappings to our approved strategy implementations
IStrategyRegistry public immutable strategyRegistry;
/// Mappings to aide is discoverability
mapping(uint => address) private _strategyIds;
/// Mapping of collection to strategy addresses
mapping(address => address[]) private _collectionStrategies;
/// Stores a list of bypassed strategies
mapping(address => bool) private _bypassStrategy;
/**
* Store our registries, mapped to their interfaces.
*
* @param _authority {AuthorityRegistry} contract address
* @param _collectionRegistry Address of our {CollectionRegistry}
*/
constructor(address _authority, address _collectionRegistry, address _strategyRegistry) AuthorityControl(_authority) {
if (_collectionRegistry == address(0)) revert CannotSetNullAddress();
if (_strategyRegistry == address(0)) revert CannotSetNullAddress();
// Type-cast our interfaces and store our registry contracts
collectionRegistry = ICollectionRegistry(_collectionRegistry);
strategyRegistry = IStrategyRegistry(_strategyRegistry);
}
/**
* Provides a list of all strategies created.
*
* @return Array of all strategies created by the {StrategyFactory}
*/
function strategies() external view returns (address[] memory) {
return _strategies;
}
/**
* Returns an array of all strategies that belong to a specific collection.
*
* @param _collection The address of the collection to query
*
* @return address[] Array of strategy addresses
*/
function collectionStrategies(address _collection) external view returns (address[] memory) {
return _collectionStrategies[_collection];
}
/**
* Provides a strategy against the provided `strategyId` (index). If the index does not exist,
* then address(0) will be returned.
*
* @param _strategyId ID of the strategy to retrieve
*
* @return Address of the strategy
*/
function strategy(uint _strategyId) external view returns (address) {
return _strategyIds[_strategyId];
}
/**
* Creates a strategy with an approved collection.
*
* @dev The strategy is not created using Clones as there are complications when
* allocated roles and permissions.
*
* @param _name Human-readable name of the strategy
* @param _strategy The strategy implemented by the strategy
* @param _strategyInitData Bytes data required by the {Strategy} for initialization
* @param _collection The address of the collection attached to the strategy
*
* @return strategyId_ ID of the newly created strategy
* @return strategyAddr_ Address of the newly created strategy
*/
function deployStrategy(bytes32 _name, address _strategy, bytes calldata _strategyInitData, address _collection)
external
onlyRole(STRATEGY_MANAGER)
returns (uint strategyId_, address strategyAddr_)
{
// No empty names, that's just silly
if (_name == '') revert StrategyNameCannotBeEmpty();
// Make sure the strategy implementation is approved
if (!strategyRegistry.isApproved(_strategy)) revert StrategyNotApproved(_strategy);
// Make sure the collection is approved
if (!collectionRegistry.isApproved(_collection)) revert CollectionNotApproved(_collection);
// Capture our `strategyId`, before we increment the array length
strategyId_ = _strategies.length;
// Deploy a new {Strategy} instance using the clone mechanic
strategyAddr_ = Clones.cloneDeterministic(_strategy, bytes32(strategyId_));
// We then need to instantiate the strategy using our supplied `strategyInitData`
IBaseStrategy(strategyAddr_).initialize(_name, strategyId_, _strategyInitData);
// Add our strategies to our internal tracking
_strategies.push(strategyAddr_);
// Add our mappings for onchain discoverability
_strategyIds[strategyId_] = strategyAddr_;
_collectionStrategies[_collection].push(strategyAddr_);
// Finally we can emit our event to notify watchers of a new strategy
emit StrategyCreated(strategyId_, strategyAddr_, _collection);
}
/**
* Allows individual strategies to be paused, meaning that assets can no longer be deposited,
* although staked assets can always be withdrawn.
*
* @dev Events are fired within the strategy to allow listeners to update.
*
* @param _strategyId strategy ID to be updated
* @param _paused If the strategy should be paused or unpaused
*/
function pause(uint _strategyId, bool _paused) public onlyRole(STRATEGY_MANAGER) {
IBaseStrategy(_strategyIds[_strategyId]).pause(_paused);
}
/**
* Reads the yield generated by all strategies since the last time that this
* function was called.
*/
function snapshot(uint _epoch)
external
onlyRole(STRATEGY_MANAGER)
returns (address[] memory strategies_, uint[] memory amounts_, uint totalAmount_)
{
// Get our underlying WETH address
address weth = address(ITreasury(treasury).weth());
// Prefine some variables
address[] memory tokens;
uint[] memory amounts;
uint tokensLength;
// Get the number of strategies and define our returned array lengths
uint strategiesLength = _strategies.length;
strategies_ = new address[](strategiesLength);
amounts_ = new uint[](strategiesLength);
// Iterate over strategies to pull out yield
for (uint i; i < strategiesLength;) {
// Prevent a bypassed strategy from snapshotting
if (!_bypassStrategy[_strategies[i]]) {
// Snapshot our strategy
(tokens, amounts) = IBaseStrategy(_strategies[i]).snapshot();
// Capture the strategy address, even if we receive no WETH yield
strategies_[i] = _strategies[i];
// Iterate over tokens to just find WETH amounts
tokensLength = tokens.length;
for (uint l; l < tokensLength;) {
// Ensure that we only handle WETH tokens with amounts
if (tokens[l] == address(weth) && amounts[l] != 0) {
// Capture the WETH yield relative to the strategy
amounts_[i] = amounts[l];
// Keep a tally of the total amount of WETH earned
totalAmount_ += amounts[l];
}
unchecked { ++l; }
}
}
unchecked { ++i; }
}
emit StrategySnapshot(_epoch, strategies_, amounts_);
}
/**
* Harvest available reward yield from the strategy. This won't affect the amount
* depositted into the contract and should only harvest rewards directly into the
* {Treasury}.
*
* @param _strategyId Strategy ID to be harvested
*/
function harvest(uint _strategyId) external onlyRole(STRATEGY_MANAGER) {
if (_bypassStrategy[_strategyIds[_strategyId]]) return;
IBaseStrategy(_strategyIds[_strategyId]).harvest(treasury);
}
/**
* Makes a call to a strategy withdraw function by passing the strategy ID and
* `abi.encodeWithSelector` to build the bytes `_data` parameter. This will then
* pass the data on to the strategy function and inject the treasury recipient
* address within the call as the first function parameter.
*
* @dev It is required for the transaction to return a successful call, otherwise
* the transaction will be reverted. The error response will be standardised so
* debugging will require a trace, rather than just the end message.
*
* @param _strategyId Strategy ID to be withdrawn from
* @param _data Strategy withdraw function call, using `encodeWithSelector`
*/
function withdraw(uint _strategyId, bytes calldata _data) external onlyRole(STRATEGY_MANAGER) {
// If we are bypassing the strategy, then skip this call
if (_bypassStrategy[_strategyIds[_strategyId]]) return;
// Extract the selector from data
bytes4 _selector = bytes4(_data);
// Create a replication of the bytes data that removes the selector
bytes memory _newData = new bytes(_data.length - 4);
for (uint i; i < _data.length - 4; i++) {
_newData[i] = _data[i + 4];
}
// Make a call to our strategy that passes on our withdrawal data
(bool success,) = _strategyIds[_strategyId].call(
// Sandwich the selector against the recipient and remaining data
abi.encodePacked(abi.encodeWithSelector(_selector, treasury), _newData)
);
// If our call failed, return a standardised message rather than decoding
require(success, 'Unable to withdraw');
}
/**
* Makes a call to a strategy withdraw function.
*
* @param _strategy Strategy address to be updated
* @param _percentage The percentage of position to withdraw from
*/
function withdrawPercentage(address _strategy, uint _percentage)
external
onlyRole(STRATEGY_MANAGER)
returns (address[] memory tokens_, uint[] memory amounts_)
{
// Ensure our percentage is valid (less than 100% to 2 decimal places)
require(_percentage > 0, 'Invalid percentage');
require(_percentage <= 100_00, 'Invalid percentage');
// Prevent a bypassed strategy from parsing withdrawal calculations
if (_bypassStrategy[_strategy]) {
return (tokens_, amounts_);
}
// Calls our strategy to withdraw a percentage of the holdings
return IBaseStrategy(_strategy).withdrawPercentage(msg.sender, _percentage);
}
/**
* Allow a strategy to be skipped when being processing. This is beneficial if a
* strategy becomes corrupted at an external point and would otherwise prevent an
* epoch from ending.
*
* @dev This does not shutdown the strategy as it can be undone. If a strategy wants
* to wind down, then it should also be paused and a full withdraw made.
*/
function bypassStrategy(address _strategy, bool _bypass) external onlyRole(STRATEGY_MANAGER) {
_bypassStrategy[_strategy] = _bypass;
}
/**
* Allows the {Treasury} contract address to be updated. All withdrawals will
* be requested to be sent to this address when the `withdraw` is called.
*
* @dev This address is dynamically injected into the subsequent strategy
* withdraw call.
*
* @param _treasury The new {Treasury} contract address
*/
function setTreasury(address _treasury) public onlyRole(TREASURY_MANAGER) {
if (_treasury == address(0)) revert CannotSetNullAddress();
treasury = _treasury;
emit TreasuryUpdated(_treasury);
}
}
src/contracts/tokens/Floor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import {ERC20Burnable} from '@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol';
import {ERC20Permit} from '@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol';
import {AuthorityControl} from '@floor/authorities/AuthorityControl.sol';
import {IFLOOR} from '@floor-interfaces/tokens/Floor.sol';
/**
* Sets up our FLOOR ERC20 token.
*/
contract FLOOR is AuthorityControl, ERC20, ERC20Burnable, ERC20Permit, IFLOOR {
/**
* Sets up our ERC20 token.
*/
constructor(address _authority) ERC20('Floor', 'FLOOR') ERC20Permit('Floor') AuthorityControl(_authority) {}
/**
* Allows a `FLOOR_MANAGER` to mint additional FLOOR tokens.
*
* @param to Recipient of the tokens
* @param amount Amount of tokens to be minted
*/
function mint(address to, uint amount) public onlyRole(FLOOR_MANAGER) {
_mint(to, amount);
}
}
src/contracts/utils/EpochManaged.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {CannotSetNullAddress} from '@floor/utils/Errors.sol';
import {IEpochManager} from '@floor-interfaces/EpochManager.sol';
abstract contract EpochManaged is Ownable {
/// Emits when {EpochManager} is updated
event EpochManagerUpdated(address epochManager);
/// Stores the current {EpochManager} contract
IEpochManager public epochManager;
/**
* Allows an updated {EpochManager} address to be set.
*/
function setEpochManager(address _epochManager) external virtual onlyOwner {
_setEpochManager(_epochManager);
}
/**
* Allows an updated {EpochManager} address to be set by an inheriting contract.
*/
function _setEpochManager(address _epochManager) internal virtual {
if (_epochManager == address(0)) revert CannotSetNullAddress();
epochManager = IEpochManager(_epochManager);
emit EpochManagerUpdated(_epochManager);
}
/**
* Gets the current epoch from our {EpochManager}.
*/
function currentEpoch() internal view virtual returns (uint) {
return epochManager.currentEpoch();
}
/**
* Checks that the contract caller is the {EpochManager}.
*/
modifier onlyEpochManager() {
require(msg.sender == address(epochManager), 'Only EpochManager can call');
_;
}
}
src/contracts/utils/Errors.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
/**
* A collection of generic errors that can be referenced across multiple
* contracts. Contract-specific errors should still be stored in their
* individual Solidity files.
*/
/// If a NULL address tries to be stored which should not be accepted
error CannotSetNullAddress();
/// If the caller has entered an insufficient amount to process the action. This
/// will likely be a zero amount.
error InsufficientAmount();
/// If the caller enters a percentage value that is too high for the requirements
error PercentageTooHigh(uint amount);
/// If a required ETH or token `transfer` call fails
error TransferFailed();
/// If a user calls a deposit related function with a zero amount
error CannotDepositZeroAmount();
/// If a user calls a withdrawal related function with a zero amount
error CannotWithdrawZeroAmount();
/// If there are no rewards available to be claimed
error NoRewardsAvailableToClaim();
/// If the requested collection is not approved
/// @param collection Address of the collection requested
error CollectionNotApproved(address collection);
/// If the requested strategy implementation is not approved
/// @param strategyImplementation Address of the strategy implementation requested
error StrategyNotApproved(address strategyImplementation);
src/interfaces/EpochManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* Handles epoch management for all other contracts.
*/
interface IEpochManager {
/// Emitted when an epoch is ended
event EpochEnded(uint epoch, uint timestamp);
/// Emitted when a new collection war is scheduled
event CollectionAdditionWarScheduled(uint epoch, uint index);
/// Emitted when required contracts are updated
event EpochManagerContractsUpdated(address newCollectionWars, address voteMarket);
/**
* The current epoch that is running across the codebase.
*
* @return The current epoch
*/
function currentEpoch() external view returns (uint);
/**
* Stores a mapping of an epoch to a collection addition war index.
*
* @param _epoch Epoch to check
*
* @return Index of the collection addition war. Will return 0 if none found
*/
function collectionEpochs(uint _epoch) external view returns (uint);
/**
* Will return if the current epoch is a collection addition vote.
*
* @return If the current epoch is a collection addition
*/
function isCollectionAdditionEpoch() external view returns (bool);
/**
* Will return if the specified epoch is a collection addition vote.
*
* @param epoch The epoch to check
*
* @return If the specified epoch is a collection addition
*/
function isCollectionAdditionEpoch(uint epoch) external view returns (bool);
/**
* Allows an epoch to be scheduled to be a collection addition vote. An index will
* be specified to show which collection addition will be used. The index will not
* be a zero value.
*
* @param epoch The epoch that the Collection Addition will take place in
* @param index The Collection Addition array index
*/
function scheduleCollectionAdditionEpoch(uint epoch, uint index) external;
/**
* Triggers an epoch to end.
*
* @dev More information about this function can be found in the actual contract
*/
function endEpoch() external;
/**
* Provides an estimated timestamp of when an epoch started, and also the earliest
* that an epoch in the future could start.
*
* @param _epoch The epoch to find the estimated timestamp of
*
* @return The estimated timestamp of when the specified epoch started
*/
function epochIterationTimestamp(uint _epoch) external returns (uint);
/**
* The length of an epoch in seconds.
*
* @return The length of the epoch in seconds
*/
function EPOCH_LENGTH() external returns (uint);
/**
* Sets contracts that the epoch manager relies on. This doesn't have to include
* all of the contracts that are {EpochManaged}, but only needs to set ones that the
* {EpochManager} needs to interact with.
*/
function setContracts(address _newCollectionWars, address _voteMarket) external;
}
src/interfaces/Treasury.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IWETH} from '@floor-interfaces/tokens/WETH.sol';
library TreasuryEnums {
/// Different sweep types that can be specified.
enum SweepType {
COLLECTION_ADDITION,
SWEEP
}
/// Different approval types that can be specified.
enum ApprovalType {
NATIVE,
ERC20,
ERC721,
ERC1155
}
}
/**
* @dev The Treasury will hold all assets.
*/
interface ITreasury {
/// Stores data that allows the Treasury to action a sweep.
struct Sweep {
TreasuryEnums.SweepType sweepType;
address[] collections;
uint[] amounts;
bool completed;
string message;
}
/// The data structure format that will be mapped against to define a token
/// approval request.
struct ActionApproval {
TreasuryEnums.ApprovalType _type; // Token type
address assetContract; // Used by 20, 721 and 1155
address target; // Used by 20, 721 and 1155
uint amount; // Used by native and 20 tokens
}
/// @dev When native network token is withdrawn from the Treasury
event Deposit(uint amount);
/// @dev When an ERC20 is depositted into the Treasury
event DepositERC20(address token, uint amount);
/// @dev When an ERC721 is depositted into the Treasury
event DepositERC721(address token, uint tokenId);
/// @dev When an ERC1155 is depositted into the Treasury
event DepositERC1155(address token, uint tokenId, uint amount);
/// @dev When native network token is withdrawn from the Treasury
event Withdraw(uint amount, address recipient);
/// @dev When an ERC20 token is withdrawn from the Treasury
event WithdrawERC20(address token, uint amount, address recipient);
/// @dev When an ERC721 token is withdrawn from the Treasury
event WithdrawERC721(address token, uint tokenId, address recipient);
/// @dev When an ERC1155 is withdrawn from the Treasury
event WithdrawERC1155(address token, uint tokenId, uint amount, address recipient);
/// @dev When FLOOR is minted
event FloorMinted(uint amount);
/// @dev When a {Treasury} action is processed
event ActionProcessed(address action, bytes data);
/// @dev When a sweep is registered against an epoch
event SweepRegistered(uint sweepEpoch, TreasuryEnums.SweepType sweepType, address[] collections, uint[] amounts);
/// @dev When an action is assigned to a sweep epoch
event SweepAction(uint sweepEpoch);
/// @dev When an epoch is swept
event EpochSwept(uint epochIndex);
/// Emitted when the {MercenarySweeper} contract address is updated
event MercenarySweeperUpdated(address mercSweeper);
/// Emitted when the minimum sweep amount is updated
event MinSweepAmountUpdated(uint minSweepAmount);
/// Emitted when the {VeFloorStaking} contract is updated
event VeFloorStakingUpdated(address veFloorStaking);
/// Emitted when the {StrategyFactory} contract is updated
event StrategyFactoryUpdated(address strategyFactory);
/**
* Our stored WETH address for the {Treasury}
*/
function weth() external returns (IWETH);
/**
* Allow FLOOR token to be minted. This should be called from the deposit method
* internally, but a public method will allow a {TreasuryManager} to bypass this
* and create additional FLOOR tokens if needed.
*
* @dev We only want to do this on creation and for inflation. Have a think on how
* we can implement this!
*/
function mint(uint amount) external;
/**
* Allows an ERC20 token to be deposited and generates FLOOR tokens based on
* the current determined value of FLOOR and the token.
*/
function depositERC20(address token, uint amount) external;
/**
* Allows an ERC721 token to be deposited and generates FLOOR tokens based on
* the current determined value of FLOOR and the token.
*/
function depositERC721(address token, uint tokenId) external;
/**
* Allows an ERC1155 token(s) to be deposited and generates FLOOR tokens based on
* the current determined value of FLOOR and the token.
*/
function depositERC1155(address token, uint tokenId, uint amount) external;
/**
* Allows an approved user to withdraw native token.
*/
function withdraw(address recipient, uint amount) external;
/**
* Allows an approved user to withdraw and ERC20 token from the Treasury.
*/
function withdrawERC20(address recipient, address token, uint amount) external;
/**
* Allows an approved user to withdraw and ERC721 token from the Treasury.
*/
function withdrawERC721(address recipient, address token, uint tokenId) external;
/**
* Allows an approved user to withdraw an ERC1155 token(s) from the Treasury.
*/
function withdrawERC1155(address recipient, address token, uint tokenId, uint amount) external;
/**
* Actions a sweep to be used against a contract that implements {ISweeper}. This
* will fulfill the sweep and we then mark the sweep as completed.
*/
function sweepEpoch(uint epochIndex, address sweeper, bytes calldata data, uint mercSweep) external;
/**
* Allows the DAO to resweep an already swept "Sweep" struct, using a contract that
* implements {ISweeper}. This will fulfill the sweep again and keep the sweep marked
* as completed.
*/
function resweepEpoch(uint epochIndex, address sweeper, bytes calldata data, uint mercSweep) external;
/**
* When an epoch ends, we have the ability to register a sweep against the {Treasury}
* via an approved contract. This will store a DAO sweep that will need to be actioned
* using the `sweepEpoch` function.
*/
function registerSweep(uint epoch, address[] calldata collections, uint[] calldata amounts, TreasuryEnums.SweepType sweepType)
external;
/**
* The minimum sweep amount that can be implemented, or excluded, as desired by the DAO.
*/
function minSweepAmount() external returns (uint);
/**
* Allows the mercenary sweeper contract to be updated.
*/
function setMercenarySweeper(address _mercSweeper) external;
/**
* Allows us to set a new VeFloorStaking contract that is used when sweeping epochs.
*/
function setVeFloorStaking(address _veFloorStaking) external;
}
src/interfaces/actions/Action.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAction {
function execute(bytes calldata) external payable returns (uint);
}
src/interfaces/actions/Sweeper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* Used by sweepers.
*/
abstract contract ISweeper {
function execute(address[] calldata collections, uint[] calldata amounts, bytes calldata data)
external
payable
virtual
returns (string memory);
/**
* Specify the {AuthorityControl} permissions, if any, that are required to
* run the sweeper. If no permissions are set, then anyone can run the sweeper
* in their allocated sweep window.
*/
function permissions() public view virtual returns (bytes32);
}
/**
* Used by mercenary sweepers.
*/
abstract contract IMercenarySweeper {
function execute(uint warIndex, uint amount) external payable virtual returns (uint);
}
src/interfaces/authorities/AuthorityControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAuthorityControl {
/// CollectionManager - Can approve token addresses to be allowed to be used in strategies
function COLLECTION_MANAGER() external returns (bytes32);
/// EpochTrigger - Can run epoch trigger contract specific logic
function EPOCH_TRIGGER() external returns (bytes32);
/// FloorManager - Can mint and manage Floor and VeFloor tokens
function FLOOR_MANAGER() external returns (bytes32);
/// Governor - A likely DAO owned vote address to allow for wide scale decisions to
/// be made and implemented.
function GOVERNOR() external returns (bytes32);
/// Guardian - Wallet address that will allow for Governor based actions, except without
/// timeframe restrictions.
function GUARDIAN() external returns (bytes32);
/// TreasuryManager - Access to Treasury asset management
function TREASURY_MANAGER() external returns (bytes32);
/// StrategyManager - Can create new strategies against approved strategies and collections
function STRATEGY_MANAGER() external returns (bytes32);
/// VoteManager - Can manage account votes
function VOTE_MANAGER() external returns (bytes32);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns `true` if `account` has been granted either the GOVERNOR or
* GUARDIAN `role`.
*/
function hasAdminRole(address account) external view returns (bool);
}
src/interfaces/authorities/AuthorityRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* This interface expands upon the OpenZeppelin `IAccessControl` interface:
* https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/access/IAccessControl.sol
*/
interface IAuthorityRegistry {
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns `true` if `account` has been granted either the GOVERNOR or
* GUARDIAN `role`.
*/
function hasAdminRole(address account) external view returns (bool);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role) external;
}
src/interfaces/collections/CollectionRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* Allows collection contracts to be approved and revoked by addresses holding the
* {CollectionManager} role. Only once approved can these collections be applied to
* new or existing strategies. They will only need to be stored as a mapping of address
* to boolean.
*/
interface ICollectionRegistry {
/// Emitted when a collection is successfully approved
event CollectionApproved(address contractAddr);
/// Emitted when a collection has been successfully revoked
event CollectionRevoked(address contractAddr);
/**
* Returns `true` if the contract address is an approved collection, otherwise
* returns `false`.
*/
function isApproved(address contractAddr) external view returns (bool);
/**
* Returns an array of all approved collections.
*/
function approvedCollections() external view returns (address[] memory);
/**
* Approves a collection contract to be used for strategies.
*/
function approveCollection(address contractAddr) external;
}
src/interfaces/staking/VeFloorStaking.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct Depositor {
uint160 epochStart;
uint8 epochCount;
uint88 amount;
}
interface IVeFloorStaking {
/// Set a list of locking periods that the user can lock for
function LOCK_PERIODS(uint) external returns (uint8);
// function floor() external returns (IERC20);
function earlyWithdrawFeeExemptions(address) external returns (bool);
function depositors(address) external returns (uint160, uint8, uint88);
function totalDeposits() external returns (uint);
function emergencyExit() external returns (bool);
function maxLossRatio() external returns (uint);
function minLockPeriodRatio() external returns (uint);
function feeReceiver() external returns (address);
function setFeeReceiver(address feeReceiver_) external;
function setMaxLossRatio(uint maxLossRatio_) external;
function setMinLockPeriodRatio(uint minLockPeriodRatio_) external;
function setEmergencyExit(bool emergencyExit_) external;
function deposit(uint amount, uint epochs) external;
function earlyWithdraw(uint minReturn, uint maxLoss) external;
function earlyWithdrawTo(address to, uint minReturn, uint maxLoss) external;
function earlyWithdrawLoss(address account) external view returns (uint loss, uint ret, bool canWithdraw);
function withdraw() external;
function withdrawTo(address to) external;
// function rescueFunds(IERC20 token, uint256 amount) external;
function isExemptFromEarlyWithdrawFees(address account) external view returns (bool);
function addEarlyWithdrawFeeExemption(address account, bool exempt) external;
}
src/interfaces/strategies/BaseStrategy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* Strategies will hold the logic for interacting with external platforms to stake
* and harvest reward yield. Each strategy will require its own strategy implementation
* to allow for different immutable variables to be defined during construct.
*
* This will follow a similar approach to how NFTX offer their eligibility module
* logic, with a lot of the power coming from inheritence.
*
* When constructed, we want to give the {Treasury} a max uint approval of the yield
* and underlying tokens.
*/
interface IBaseStrategy {
/// @dev When strategy receives a deposit
event Deposit(address token, uint amount, address caller);
/// @dev When strategy is harvested
event Harvest(address token, uint amount);
/// @dev When a staked user exits their position
event Withdraw(address token, uint amount, address recipient);
/**
* Allows the strategy to be initialised.
*/
function initialize(bytes32 name, uint strategyId, bytes calldata initData) external;
/**
* Name of the strategy.
*/
function name() external view returns (bytes32);
/**
* The numerical ID of the strategy that acts as an index for the {StrategyFactory}.
*/
function strategyId() external view returns (uint);
/**
* Total rewards generated by the strategy in all time. This is pure bragging rights.
*/
function lifetimeRewards(address token) external returns (uint amount_);
/**
* The amount of rewards claimed in the last claim call.
*/
function lastEpochRewards(address token) external returns (uint amount_);
/**
* Gets rewards that are available to harvest.
*/
function available() external returns (address[] memory, uint[] memory);
/**
* Extracts all rewards from third party and moves it to a recipient. This should
* only be called by a specific action.
*
* @dev This _should_ always be imposed to be the {Treasury} by the {StrategyFactory}.
*/
function harvest(address /* _recipient */ ) external;
/**
* Returns an array of tokens that the strategy supports.
*
* @return address[] The address of valid tokens
*/
function validTokens() external view returns (address[] memory);
/**
* Makes a call to a strategy to withdraw a percentage of the deposited holdings.
*
* @param recipient Strategy address to be updated
* @param percentage The 2 decimal accuracy of the percentage to withdraw (e.g. 100% = 10000)
*
* @return address[] Array of tokens withdrawn
* @return uint[] Amounts of respective tokens withdrawn
*/
function withdrawPercentage(address recipient, uint percentage) external returns (address[] memory, uint[] memory);
/**
* Pauses deposits from being made into the strategy. This should only be called by
* a guardian or governor.
*
* @param _p Boolean value for if the strategy should be paused
*/
function pause(bool _p) external;
/**
* Gets a read of new yield since the last call. This is what can be called when
* the epoch ends to determine the amount generated within the epoch.
*/
function snapshot() external returns (address[] memory, uint[] memory);
}
src/interfaces/strategies/StrategyFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* Allows for strategies to be created, pairing them with a {Strategy} and an approved
* collection. The strategy creation script needs to be as highly optimised as possible
* to ensure that the gas costs are kept down.
*
* This factory will keep an index of created strategies and secondary information to ensure
* that external applications can display and maintain a list of available strategies.
*
* The contract can be paused to prevent the creation of new strategies.
*/
interface IStrategyFactory {
/// @dev Sent when a strategy is created successfully
event StrategyCreated(uint indexed strategyId, address strategyAddress, address assetAddress);
/// @dev Sent when a snapshot is taken
event StrategySnapshot(uint epoch, address[] tokens, uint[] amounts);
/// @dev Sent when the Treasury address is updated
event TreasuryUpdated(address treasury);
/**
* Our stored {Treasury} address.
*/
function treasury() external view returns (address);
/**
* Provides a list of all strategies created.
*
* @return Array of all strategies created by the {StrategyFactory}
*/
function strategies() external view returns (address[] memory);
/**
* Returns an array of all strategies that belong to a specific collection.
*/
function collectionStrategies(address _collection) external view returns (address[] memory);
/**
* Provides a strategy against the provided `strategyId` (index). If the index does not exist,
* then address(0) will be returned.
*
* @param _strategyId ID of the strategy to retrieve
*
* @return Address of the strategy
*/
function strategy(uint _strategyId) external view returns (address);
/**
* Creates a strategy with an approved collection.
*
* @dev The strategy is not created using Clones as there are complications when allocated
* roles and permissions.
*
* @param _name Human-readable name of the strategy
* @param _strategy The strategy implemented by the strategy
* @param _strategyInitData Bytes data required by the {Strategy} for initialization
* @param _collection The address of the collection attached to the strategy
*
* @return strategyId_ ID of the newly created strategy
* @return strategyAddr_ Address of the newly created strategy
*/
function deployStrategy(bytes32 _name, address _strategy, bytes calldata _strategyInitData, address _collection)
external
returns (uint strategyId_, address strategyAddr_);
/**
* Allows individual strategies to be paused, meaning that assets can no longer be deposited,
* although staked assets can always be withdrawn.
*
* @dev Events are fired within the strategy to allow listeners to update.
*
* @param _strategyId Strategy ID to be paused
* @param _paused If the strategy should be paused or unpaused
*/
function pause(uint _strategyId, bool _paused) external;
/**
* Reads the yield generated by a strategy since the last time that this function was called.
*
* @param _epoch The current epoch being snapshotted
*
* @return tokens Tokens that have been generated as yield
* @return amounts The amount of yield generated for the corresponding token
*/
function snapshot(uint _epoch) external returns (address[] memory tokens, uint[] memory amounts, uint totalAmount);
/**
* Harvest available reward yield from the strategy. This won't affect the amount
* depositted into the contract and should only harvest rewards directly into the
* {Treasury}.
*
* @param _strategyId Strategy ID to be harvested
*/
function harvest(uint _strategyId) external;
/**
* Makes a call to a strategy withdraw function by passing the strategy ID and
* `abi.encodeWithSelector` to build the bytes `_data` parameter. This will then
* pass the data on to the strategy function and inject the treasury recipient
* address within the call as the first function parameter.
*
* @dev It is required for the transaction to return a successful call, otherwise
* the transaction will be reverted. The error response will be standardised so
* debugging will require a trace, rather than just the end message.
*
* @param _strategyId Strategy ID to be withdrawn from
* @param _data Strategy withdraw function call, using `encodeWithSelector`
*/
function withdraw(uint _strategyId, bytes calldata _data) external;
/**
* Makes a call to a strategy to withdraw a percentage of the deposited holdings.
*
* @param _strategy Strategy address to be updated
* @param _percentage The 2 decimal accuracy of the percentage to withdraw (e.g. 100% = 10000)
*/
function withdrawPercentage(address _strategy, uint _percentage) external returns (address[] memory, uint[] memory);
/**
* Allows the {Treasury} contract address to be updated. All withdrawals will
* be requested to be sent to this address when the `withdraw` is called.
*
* @dev This address is dynamically injected into the subsequent strategy
* withdraw call.
*
* @param _treasury The new {Treasury} contract address
*/
function setTreasury(address _treasury) external;
}
src/interfaces/strategies/StrategyRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* Allows strategy contracts to be approved and revoked by addresses holding the
* {TREASURY_MANAGER} role. Only once approved can these strategy implementations be deployed
* to new or existing strategies.
*/
interface IStrategyRegistry {
/// Emitted when a strategy is approved or unapproved
event ApprovedStrategyUpdated(address contractAddr, bool approved);
/**
* Checks if a strategy has previously been approved.
*
* @param contractAddr The strategy implementation address to be checked
*
* @return Returns `true` if the contract address is an approved strategy, otherwise
* returns `false`.
*/
function isApproved(address contractAddr) external view returns (bool);
/**
* Changes the approval state of a strategy implementation contract.
*
* The strategy address cannot be null, and if it is already the new state, then
* no changes will be made.
*
* The caller must have the `TREASURY_MANAGER` role.
*
* @param contractAddr Address of unapproved strategy to approve
* @param approved The new approval state for the implementation
*/
function approveStrategy(address contractAddr, bool approved) external;
}
src/interfaces/tokens/Floor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol';
interface IFLOOR is IERC20 {
/**
* Creates `_amount` token to `_to`. Must only be called by the owner.
*
* @param _to The address that will receive the mint
* @param _amount The amount to be minted
*/
function mint(address _to, uint _amount) external;
}
src/interfaces/tokens/Votable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IVotable is IERC20 {
/// @dev we assume that voting power is a function of balance that preserves order
function votingPowerOf(address account) external view returns (uint);
}
src/interfaces/tokens/WETH.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IWETH is IERC20 {
function allowance(address, address) external view returns (uint);
function balanceOf(address) external view returns (uint);
function approve(address, uint) external returns (bool);
function transfer(address, uint) external returns (bool);
function transferFrom(address, address, uint) external returns (bool);
function deposit() external payable;
function withdraw(uint) external;
}
src/interfaces/voting/NewCollectionWars.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface INewCollectionWars {
/**
* For each FloorWar that is created, this structure will be created. When
* the epoch ends, the FloorWar will remain and will be updated with information
* on the winning collection and the votes attributed to each collection.
*/
struct FloorWar {
uint index;
uint startEpoch;
address[] collections;
}
/// Sent when a user casts a vote
event VoteCast(address sender, address collection, uint userVotes, uint collectionVotes);
/// Sent when a collection vote is revoked
event VoteRevoked(address sender, address collection, uint collectionVotes);
/// Sent when a collection NFT is staked to vote
event NftVoteCast(address sender, uint war, address collection, uint collectionVotes, uint collectionNftVotes);
/// Sent when a Collection Addition War is created
event CollectionAdditionWarCreated(uint epoch, address[] collections, uint[] floorPrices);
/// Sent when a Collection Addition War is started
event CollectionAdditionWarStarted(uint warIndex);
/// Sent when a Collection Addition War ends
event CollectionAdditionWarEnded(uint warIndex, address collection);
/// Sent when Collection Addition War NFTs are exercised
event CollectionExercised(uint warIndex, address collection, uint value);
/// Sent when the {NewCollectionWarOptions} contract address is updated
event NewCollectionWarOptionsUpdated(address newCollectionWarOptions);
/// Stores the number of votes a user has placed against a war collection
function userVotes(bytes32) external view returns (uint);
/// Stores the floor spot price of a collection token against a war collection
function collectionSpotPrice(bytes32) external view returns (uint);
/// Stores the total number of votes against a war collection
function collectionVotes(bytes32) external view returns (uint);
function collectionNftVotes(bytes32) external view returns (uint);
/// Stores which collection the user has cast their votes towards to allow for
/// reallocation on subsequent votes if needed.
function userCollectionVote(bytes32) external view returns (address);
/// Stores the address of the collection that won a Floor War
function floorWarWinner(uint _epoch) external view returns (address);
/// Stores if a collection has been flagged as ERC1155
function is1155(address) external returns (bool);
/// Stores the unlock epoch of a collection in a floor war
function collectionEpochLock(bytes32) external returns (uint);
/**
* The total voting power of a user, regardless of if they have cast votes
* or not.
*
* @param _user User address being checked
*/
function userVotingPower(address _user) external view returns (uint);
/**
* The total number of votes that a user has available.
*
* @param _user User address being checked
*
* @return uint Number of votes available to the user
*/
function userVotesAvailable(uint _war, address _user) external view returns (uint);
/**
* Allows the user to cast 100% of their voting power against an individual
* collection. If the user has already voted on the FloorWar then this will
* additionally reallocate their votes.
*/
function vote(address collection) external;
/**
* Allows an approved contract to submit option-related votes against a collection
* in the current war.
*
* @param sender The address of the user that staked the token
* @param collection The collection to cast the vote against
* @param votingPower The voting power added from the option creation
*/
function optionVote(address sender, uint war, address collection, uint votingPower) external;
/**
* Revokes a user's current votes in the current war.
*
* @dev This is used when a user unstakes their floor
*
* @param account The address of the account that is having their vote revoked
*/
function revokeVotes(address account) external;
/**
* Allow an authorised user to create a new floor war to start with a range of
* collections from a specific epoch.
*/
function createFloorWar(uint epoch, address[] calldata collections, bool[] calldata isErc1155, uint[] calldata floorPrices)
external
returns (uint);
/**
* Sets a scheduled {FloorWar} to be active.
*
* @dev This function is called by the {EpochManager} when a new epoch starts
*
* @param index The index of the {FloorWar} being started
*/
function startFloorWar(uint index) external;
/**
* When the epoch has come to an end, this function will be called to finalise
* the votes and decide which collection has won. This collection will then need
* to be added to the {CollectionRegistry}.
*
* Any NFTs that have been staked will be timelocked for an additional epoch to
* give the DAO time to exercise or reject any options.
*
* @dev We can't action this in one single call as we will need information about
* the underlying NFTX token as well.
*/
function endFloorWar() external returns (address highestVoteCollection);
/**
* Allows us to update our collection floor prices if we have seen a noticable difference
* since the start of the epoch. This will need to be called for this reason as the floor
* price of the collection heavily determines the amount of voting power awarded when
* creating an option.
*/
function updateCollectionFloorPrice(address collection, uint floorPrice) external;
/**
* Allows our options contract to be updated.
*
* @param _contract The new contract to use
*/
function setOptionsContract(address _contract) external;
/**
* Check if a collection is in a FloorWar.
*/
function isCollectionInWar(bytes32 warCollection) external view returns (bool);
}
src/interfaces/voting/SweepWars.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* The GWV will allow users to assign their veFloor position to a strategy, or
* optionally case it to a veFloor, which will use a constant value. As the
* strategies will be rendered as an address, the veFloor vote will take a NULL
* address value.
*
* At point of development this can take influence from:
* https://github.com/saddle-finance/saddle-contract/blob/master/contracts/tokenomics/gauges/GaugeController.vy
*/
interface ISweepWars {
/// Sent when a user casts or revokes their vote
event VoteCast(address sender, address collection, int amount);
/// Sent when a user has revoked their vote, or it is revoked on their behalf
event VotesRevoked(address account, address collection, uint forVotesRevoked, uint againstVotesRevoked);
/// Sent when the Sample Size is updated
event SampleSizeUpdated(uint size);
/// Sent when the {NftStaking} contract address is updated
event NftStakingUpdated(address nftStaking);
/**
* Gets the number of votes for a collection at the current epoch.
*/
function votes(address) external view returns (int);
/**
* The total voting power of a user, regardless of if they have cast votes
* or not.
*/
function userVotingPower(address _user) external view returns (uint);
/**
* The total number of votes that a user has available, calculated by:
*
* ```
* votesAvailable_ = balanceOf(_user) - SUM(userVotes.votes_)
* ```
*/
function userVotesAvailable(address _user) external view returns (uint votesAvailable_);
/**
* Provides a list of collection addresses that can be voted on.
*/
function voteOptions() external view returns (address[] memory collections_);
/**
* Allows a user to cast a vote using their veFloor allocation. We don't
* need to monitor transfers as veFloor can only be minted or burned, and
* we check the voters balance during the `snapshot` call.
*
* A user can vote with a partial amount of their veFloor holdings, and when
* it comes to calculating their voting power this will need to be taken into
* consideration that it will be:
*
* ```
* staked balance + (gains from staking * (total balance - staked balance)%)
* ```
*
* The {Treasury} cannot vote with it's holdings, as it shouldn't be holding
* any staked Floor.
*/
function vote(address _collection, int _amount) external;
/**
* Allows a user to revoke their votes from strategies. This will free up the
* user's available votes that can subsequently be voted again with.
*/
function revokeVotes(address[] memory _collection) external;
/**
* Allows an authorised contract or wallet to revoke all user votes. This
* can be called when the veFLOOR balance is reduced.
*/
function revokeAllUserVotes(address _account) external;
/**
* The snapshot function will need to iterate over all strategies that have
* more than 0 votes against them. With that we will need to find each
* strategy percentage share in relation to other strategies.
*
* This percentage share will instruct the {Treasury} on how much additional
* FLOOR to allocate to the users staked in the strategies. These rewards will
* become available in the {RewardLedger}.
*
* +----------------+-----------------+-------------------+-------------------+
* | Voter | veFloor | Vote Weight | Strategy |
* +----------------+-----------------+-------------------+-------------------+
* | Alice | 30 | 40 | 1 |
* | Bob | 20 | 30 | 2 |
* | Carol | 40 | 55 | 3 |
* | Dave | 20 | 40 | 2 |
* | Emily | 25 | 35 | 0 |
* +----------------+-----------------+-------------------+-------------------+
*
* With the above information, and assuming that the {Treasury} has allocated
* 1000 FLOOR tokens to be additionally distributed in this snapshot, we would
* have the following allocations going to the strategies.
*
* +----------------+-----------------+-------------------+-------------------+
* | Strategy | Votes Total | Vote Percent | veFloor Rewards |
* +----------------+-----------------+-------------------+-------------------+
* | 0 (veFloor) | 35 | 17.5% | 175 |
* | 1 | 40 | 20% | 200 |
* | 2 | 70 | 35% | 350 |
* | 3 | 55 | 27.5% | 275 |
* | 4 | 0 | 0% | 0 |
* +----------------+-----------------+-------------------+-------------------+
*
* This would distribute the strategies allocated rewards against the staked
* percentage in the strategy. Any Treasury holdings that would be given in rewards
* are just deposited into the {Treasury} as FLOOR, bypassing the {RewardsLedger}.
*/
function snapshot(uint tokens) external returns (address[] memory collections, uint[] memory amounts);
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "none"
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "london",
"remappings": [
":@1inch/=lib/",
":@ERC721A/=lib/ERC721A/contracts/",
":@chainlink/=lib/chainlink/",
":@charmfi/=lib/charmfi-contracts-0.8.0-support/",
":@floor-interfaces/=src/interfaces/",
":@floor-scripts/=script/",
":@floor/=src/contracts/",
":@manifoldxyz/=lib/lssvm2/lib/",
":@mocks/=lib/nftx-protocol-v3/src/mocks/",
":@murky/=lib/murky/src/",
":@nftx-protocol-v3/=lib/nftx-protocol-v3/src/",
":@openzeppelin-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
":@permit2/=lib/nftx-protocol-v3/lib/permit2/src/",
":@prb/math/=lib/lssvm2/lib/prb-math/src/",
":@prb/test/=lib/foundry-random/lib/prb-test/src/",
":@solidity-math-utils/=lib/solidity-math-utils/project/contracts/",
":@solidity-trigonometry/=lib/solidity-trigonometry/src/",
":@src/=lib/nftx-protocol-v3/src/",
":@sudoswap/=lib/lssvm/src/",
":@test/=lib/nftx-protocol-v3/test/",
":@uni-core/=lib/nftx-protocol-v3/src/uniswap/v3-core/",
":@uni-periphery/=lib/nftx-protocol-v3/src/uniswap/v3-periphery/",
":@uniswap-v3/=lib/",
":@uniswap/lib/=lib/nftx-protocol-v3/lib/solidity-lib/",
":@uniswap/v2-core/=lib/nftx-protocol-v3/lib/v2-core/",
":@uniswap/v3-core/contracts/=lib/nftx-protocol-v3/src/uniswap/v3-core/",
":@uniswap/v3-periphery/=lib/v3-periphery/",
":CramBit/=lib/foundry-random/lib/CramBit/",
":ERC721A/=lib/ERC721A/contracts/",
":base64-sol/=lib/nftx-protocol-v3/src/uniswap/v3-periphery/libraries/",
":chainlink/=lib/chainlink/",
":charmfi-contracts-0.8.0-support/=lib/charmfi-contracts-0.8.0-support/",
":clones-with-immutable-args/=lib/lssvm2/lib/clones-with-immutable-args/src/",
":crambit/=lib/foundry-random/lib/CramBit/src/",
":create2-helpers/=lib/lssvm2/lib/royalty-registry-solidity/lib/create2-helpers/",
":create3-factory/=lib/lssvm2/lib/create3-factory/",
":ds-test/=lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":foundry-huff/=lib/lssvm2/lib/foundry-huff/src/",
":foundry-random/=lib/foundry-random/src/",
":huffmate/=lib/lssvm2/lib/huffmate/src/",
":libraries-solidity/=lib/lssvm2/lib/libraries-solidity/contracts/",
":lssvm/=lib/lssvm/src/",
":lssvm2/=lib/lssvm2/src/",
":manifoldxyz/=lib/lssvm2/lib/royalty-registry-solidity/contracts/",
":murky/=lib/murky/src/",
":nftx-protocol-v3/=lib/nftx-protocol-v3/src/",
":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/",
":prb-math/=lib/solidity-trigonometry/lib/prb-math/contracts/",
":prb-test/=lib/foundry-random/lib/prb-test/src/",
":royalty-registry-solidity.git/=lib/lssvm/lib/royalty-registry-solidity.git/contracts/",
":royalty-registry-solidity/=lib/lssvm2/lib/royalty-registry-solidity/",
":solidity-bytes-utils/=lib/foundry-random/lib/solidity-bytes-utils/contracts/",
":solidity-math-utils/=lib/solidity-math-utils/",
":solidity-stringutils/=lib/lssvm2/lib/foundry-huff/lib/solidity-stringutils/",
":solidity-trigonometry/=lib/solidity-trigonometry/src/",
":solidity-utils/=lib/solidity-utils/contracts/",
":solmate/=lib/lssvm2/lib/solmate/src/",
":src/=lib/foundry-random/src/",
":stringutils/=lib/lssvm2/lib/foundry-huff/lib/solidity-stringutils/",
":v3-core/=lib/v3-core/contracts/",
":v3-periphery/=lib/v3-periphery/contracts/",
":weird-erc20/=lib/lssvm/lib/solmate/lib/weird-erc20/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.