file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/80001/0xC42DCF0FBc12A4A3D204000d4f560d49e88307A2/sources/contracts/Marketplace.sol | Closes an auction for an auction creator; distributes winning bid amount to auction creator. | function _closeAuctionForAuctionCreator(Listing memory _targetListing, Offer memory _winningBid) internal {
uint256 payoutAmount = _winningBid.pricePerToken * _targetListing.quantity;
_targetListing.quantity = 0;
_targetListing.endTime = block.timestamp;
listings[_targetListing.listingId] = _targetListing;
_winningBid.pricePerToken = 0;
winningBid[_targetListing.listingId] = _winningBid;
payout(address(this), _targetListing.tokenOwner, _targetListing.currency, payoutAmount);
emit AuctionClosed(
_targetListing.listingId,
_msgSender(),
false,
_targetListing.tokenOwner,
_winningBid.offeror
);
}
| 5,599,689 |
./full_match/1/0x9C1dC986D786534c13Ec32eFA6C7A1631898d102/sources/inari1.sol | Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`. | function unstakeSushiFromAaveTo(address to, uint256 amount) external {
}
β β ββ β β βββ β β β
β β β ββββ ββ β β β β
β ββ ββ ββ β β β β βββββ
βββ βββββ β β β β
β ββ */
| 3,116,974 |
pragma solidity ^0.4.24;
/**
* @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 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.
*/
constructor() 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));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**************************************************************
* @title Scale Token Contract
* @file Scale.sol
* @author Jared Downing and Kane Thomas of the Scale Network
* @version 1.0
*
* @section DESCRIPTION
*
* This is an ERC20-based token with staking and inflationary functionality.
*
*************************************************************/
//////////////////////////////////
/// OpenZeppelin library imports
//////////////////////////////////
/**
* @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 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);
emit 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 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);
emit 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;
emit 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) {
return allowed[_owner][_spender];
}
/**
* @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
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
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
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
* Modified to allow minting for non-owner addresses
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
/**
* @dev 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(address _to, uint256 _amount) internal returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
}
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2Ο.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this ether.
* @notice Ether can still be send to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
assert(owner.send(address(this).balance));
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
//////////////////////////////////
/// Scale Token
//////////////////////////////////
contract Scale is MintableToken, HasNoEther, BurnableToken {
// Libraries
using SafeMath for uint;
//////////////////////
// Token Information
//////////////////////
string public constant name = "SCALE";
string public constant symbol = "SCALE";
uint8 public constant decimals = 18;
///////////////////////////////////////////////////////////
// Variables For Staking and Pooling
///////////////////////////////////////////////////////////
// -- Pool Minting Rates and Percentages -- //
// Pool for Scale distribution to rewards pool
// Set to 0 to prohibit issuing to the pool before it is assigned
address public pool = address(0);
// Pool and Owner minted tokens per second
uint public poolMintRate;
uint public ownerMintRate;
// Amount of Scale to be staked to the pool, staking, and owner, as calculated through their percentages
uint public poolMintAmount;
uint public stakingMintAmount;
uint public ownerMintAmount;
// Scale distribution percentages
uint public poolPercentage = 70;
uint public ownerPercentage = 5;
uint public stakingPercentage = 25;
// Last time minted for owner and pool
uint public ownerTimeLastMinted;
uint public poolTimeLastMinted;
// -- Staking -- //
// Minted tokens per second
uint public stakingMintRate;
// Total Scale currently staked
uint public totalScaleStaked;
// Mapping of the timestamp => totalStaking that is created each time an address stakes or unstakes
mapping (uint => uint) totalStakingHistory;
// Variable for staking accuracy. Set to 86400 for seconds in a day so that staking gains are based on the day an account begins staking.
uint timingVariable = 86400;
// Address staking information
struct AddressStakeData {
uint stakeBalance;
uint initialStakeTime;
uint unstakeTime;
mapping (uint => uint) stakePerDay;
}
// Track all tokens staked
mapping (address => AddressStakeData) public stakeBalances;
// -- Inflation -- //
// Inflation rate begins at 100% per year and decreases by 30% per year until it reaches 10% where it decreases by 0.5% per year
uint256 inflationRate = 1000;
// Used to manage when to inflate. Allowed to inflate once per year until the rate reaches 1%.
uint256 public lastInflationUpdate;
// -- Events -- //
// Fired when tokens are staked
event Stake(address indexed staker, uint256 value);
// Fired when tokens are unstaked
event Unstake(address indexed unstaker, uint256 stakedAmount);
// Fired when a user claims their stake
event ClaimStake(address indexed claimer, uint256 stakedAmount, uint256 stakingGains);
//////////////////////////////////////////////////
/// Scale Token Functionality
//////////////////////////////////////////////////
/// @dev Scale token constructor
constructor() public {
// Assign owner
owner = msg.sender;
// Assign initial owner supply
uint _initOwnerSupply = 10000000 ether;
// Mint given to owner only one-time
bool _success = mint(msg.sender, _initOwnerSupply);
// Require minting success
require(_success);
// Set pool and owner last minted to ensure extra coins are not minted by either
ownerTimeLastMinted = now;
poolTimeLastMinted = now;
// Set minting amount for pool, staking, and owner over the course of 1 year
poolMintAmount = _initOwnerSupply.mul(poolPercentage).div(100);
ownerMintAmount = _initOwnerSupply.mul(ownerPercentage).div(100);
stakingMintAmount = _initOwnerSupply.mul(stakingPercentage).div(100);
// One year in seconds
uint _oneYearInSeconds = 31536000 ether;
// Set the rate of coins minted per second for the pool, owner, and global staking
poolMintRate = calculateFraction(poolMintAmount, _oneYearInSeconds, decimals);
ownerMintRate = calculateFraction(ownerMintAmount, _oneYearInSeconds, decimals);
stakingMintRate = calculateFraction(stakingMintAmount, _oneYearInSeconds, decimals);
// Set the last time inflation was updated to now so that the next time it can be updated is 1 year from now
lastInflationUpdate = now;
}
/////////////
// Inflation
/////////////
/// @dev the inflation rate begins at 100% and decreases by 30% every year until it reaches 10%
/// at 10% the rate begins to decrease by 0.5% until it reaches 1%
function adjustInflationRate() private {
// Make sure adjustInflationRate cannot be called for at least another year
lastInflationUpdate = now;
// Decrease inflation rate by 30% each year
if (inflationRate > 100) {
inflationRate = inflationRate.sub(300);
}
// Inflation rate reaches 10%. Decrease inflation rate by 0.5% from here on out until it reaches 1%.
else if (inflationRate > 10) {
inflationRate = inflationRate.sub(5);
}
adjustMintRates();
}
/// @dev adjusts the mint rate when the yearly inflation update is called
function adjustMintRates() internal {
// Calculate new mint amount of Scale that should be created per year.
poolMintAmount = totalSupply.mul(inflationRate).div(1000).mul(poolPercentage).div(100);
ownerMintAmount = totalSupply.mul(inflationRate).div(1000).mul(ownerPercentage).div(100);
stakingMintAmount = totalSupply.mul(inflationRate).div(1000).mul(stakingPercentage).div(100);
// Adjust Scale created per-second for each rate
poolMintRate = calculateFraction(poolMintAmount, 31536000 ether, decimals);
ownerMintRate = calculateFraction(ownerMintAmount, 31536000 ether, decimals);
stakingMintRate = calculateFraction(stakingMintAmount, 31536000 ether, decimals);
}
/// @dev anyone can call this function to update the inflation rate yearly
function updateInflationRate() public {
// Require 1 year to have passed for every inflation adjustment
require(now.sub(lastInflationUpdate) >= 31536000);
adjustInflationRate();
}
/////////////
// Staking
/////////////
/// @dev staking function which allows users to stake an amount of tokens to gain interest for up to 1 year
function stake(uint _stakeAmount) external {
// Require that tokens are staked successfully
require(stakeScale(msg.sender, _stakeAmount));
}
/// @dev staking function which allows users to stake an amount of tokens for another user
function stakeFor(address _user, uint _amount) external {
// Stake for the user
require(stakeScale(_user, _amount));
}
/// @dev Transfer tokens from the contract to the user when unstaking
/// @param _value uint256 the amount of tokens to be transferred
function transferFromContract(uint _value) internal {
// Sanity check to make sure we are not transferring more than the contract has
require(_value <= balances[address(this)]);
// Add to the msg.sender balance
balances[msg.sender] = balances[msg.sender].add(_value);
// Subtract from the contract's balance
balances[address(this)] = balances[address(this)].sub(_value);
// Fire an event for transfer
emit Transfer(address(this), msg.sender, _value);
}
/// @dev stake function reduces the user's total available balance and adds it to their staking balance
/// @param _value how many tokens a user wants to stake
function stakeScale(address _user, uint256 _value) private returns (bool success) {
// You can only stake / stakeFor as many tokens as you have
require(_value <= balances[msg.sender]);
// Require the user is not in power down period
require(stakeBalances[_user].unstakeTime == 0);
// Transfer tokens to contract address
transfer(address(this), _value);
// Now as a day
uint _nowAsDay = now.div(timingVariable);
// Adjust the new staking balance
uint _newStakeBalance = stakeBalances[_user].stakeBalance.add(_value);
// If this is the initial stake time, save
if (stakeBalances[_user].stakeBalance == 0) {
// Save the time that the stake started
stakeBalances[_user].initialStakeTime = _nowAsDay;
}
// Add stake amount to staked balance
stakeBalances[_user].stakeBalance = _newStakeBalance;
// Assign the total amount staked at this day
stakeBalances[_user].stakePerDay[_nowAsDay] = _newStakeBalance;
// Increment the total staked tokens
totalScaleStaked = totalScaleStaked.add(_value);
// Set the new staking history
setTotalStakingHistory();
// Fire an event for newly staked tokens
emit Stake(_user, _value);
return true;
}
/// @dev deposit a user's initial stake plus earnings if the user unstaked at least 14 days ago
function claimStake() external returns (bool) {
// Require that at least 14 days have passed (days)
require(now.div(timingVariable).sub(stakeBalances[msg.sender].unstakeTime) >= 14);
// Get the user's stake balance
uint _userStakeBalance = stakeBalances[msg.sender].stakeBalance;
// Calculate tokens to mint using unstakeTime, rewards are not received during power-down period
uint _tokensToMint = calculateStakeGains(stakeBalances[msg.sender].unstakeTime);
// Clear out stored data from mapping
stakeBalances[msg.sender].stakeBalance = 0;
stakeBalances[msg.sender].initialStakeTime = 0;
stakeBalances[msg.sender].unstakeTime = 0;
// Return the stake balance to the staker
transferFromContract(_userStakeBalance);
// Mint the new tokens to the sender
mint(msg.sender, _tokensToMint);
// Scale unstaked event
emit ClaimStake(msg.sender, _userStakeBalance, _tokensToMint);
return true;
}
/// @dev allows users to start the reclaim process for staked tokens and stake rewards
/// @return bool on success
function initUnstake() external returns (bool) {
// Require that the user has not already started the unstaked process
require(stakeBalances[msg.sender].unstakeTime == 0);
// Require that there was some amount staked
require(stakeBalances[msg.sender].stakeBalance > 0);
// Log time that user started unstaking
stakeBalances[msg.sender].unstakeTime = now.div(timingVariable);
// Subtract stake balance from totalScaleStaked
totalScaleStaked = totalScaleStaked.sub(stakeBalances[msg.sender].stakeBalance);
// Set this every time someone adjusts the totalScaleStaked amount
setTotalStakingHistory();
// Scale unstaked event
emit Unstake(msg.sender, stakeBalances[msg.sender].stakeBalance);
return true;
}
/// @dev function to let the user know how much time they have until they can claim their tokens from unstaking
/// @param _user to check the time until claimable of
/// @return uint time in seconds until they may claim
function timeUntilClaimAvaliable(address _user) view external returns (uint) {
return stakeBalances[_user].unstakeTime.add(14).mul(86400);
}
/// @dev function to check the staking balance of a user
/// @param _user to check the balance of
/// @return uint of the stake balance
function stakeBalanceOf(address _user) view external returns (uint) {
return stakeBalances[_user].stakeBalance;
}
/// @dev returns how much Scale a user has earned so far
/// @param _now is passed in to allow for a gas-free analysis
/// @return staking gains based on the amount of time passed since staking began
function getStakingGains(uint _now) view public returns (uint) {
if (stakeBalances[msg.sender].stakeBalance == 0) {
return 0;
}
return calculateStakeGains(_now.div(timingVariable));
}
/// @dev Calculates staking gains
/// @param _unstakeTime when the user stopped staking.
/// @return uint for total coins to be minted
function calculateStakeGains(uint _unstakeTime) view private returns (uint mintTotal) {
uint _initialStakeTimeInVariable = stakeBalances[msg.sender].initialStakeTime; // When the user started staking as a unique day in unix time
uint _timePassedSinceStakeInVariable = _unstakeTime.sub(_initialStakeTimeInVariable); // How much time has passed, in days, since the user started staking.
uint _stakePercentages = 0; // Keeps an additive track of the user's staking percentages over time
uint _tokensToMint = 0; // How many new Scale tokens to create
uint _lastDayStakeWasUpdated; // Last day the totalScaleStaked was updated
uint _lastStakeDay; // Last day that the user staked
// If user staked and init unstaked on the same day, gains are 0
if (_timePassedSinceStakeInVariable == 0) {
return 0;
}
// If user has been staking longer than 365 days, staked days after 365 days do not earn interest
else if (_timePassedSinceStakeInVariable >= 365) {
_unstakeTime = _initialStakeTimeInVariable.add(365);
_timePassedSinceStakeInVariable = 365;
}
// Average this msg.sender's relative percentage ownership of totalScaleStaked throughout each day since they started staking
for (uint i = _initialStakeTimeInVariable; i < _unstakeTime; i++) {
// Total amount user has staked on i day
uint _stakeForDay = stakeBalances[msg.sender].stakePerDay[i];
// If this was a day that the user staked or added stake
if (_stakeForDay != 0) {
// If the day exists add it to the percentages
if (totalStakingHistory[i] != 0) {
// If the day does exist add it to the number to be later averaged as a total average percentage of total staking
_stakePercentages = _stakePercentages.add(calculateFraction(_stakeForDay, totalStakingHistory[i], decimals));
// Set the last day someone staked
_lastDayStakeWasUpdated = totalStakingHistory[i];
}
else {
// Use the last day found in the totalStakingHistory mapping
_stakePercentages = _stakePercentages.add(calculateFraction(_stakeForDay, _lastDayStakeWasUpdated, decimals));
}
_lastStakeDay = _stakeForDay;
}
else {
// If the day exists add it to the percentages
if (totalStakingHistory[i] != 0) {
// If the day does exist add it to the number to be later averaged as a total average percentage of total staking
_stakePercentages = _stakePercentages.add(calculateFraction(_lastStakeDay, totalStakingHistory[i], decimals));
// Set the last day someone staked
_lastDayStakeWasUpdated = totalStakingHistory[i];
}
else {
// Use the last day found in the totalStakingHistory mapping
_stakePercentages = _stakePercentages.add(calculateFraction(_lastStakeDay, _lastDayStakeWasUpdated, decimals));
}
}
}
// Get the account's average percentage staked of the total stake over the course of all days they have been staking
uint _stakePercentageAverage = calculateFraction(_stakePercentages, _timePassedSinceStakeInVariable, 0);
// Calculate this account's mint rate per second while staking
uint _finalMintRate = stakingMintRate.mul(_stakePercentageAverage);
// Account for 18 decimals when calculating the amount of tokens to mint
_finalMintRate = _finalMintRate.div(1 ether);
// Calculate total tokens to be minted. Multiply by timingVariable to convert back to seconds.
_tokensToMint = calculateMintTotal(_timePassedSinceStakeInVariable.mul(timingVariable), _finalMintRate);
return _tokensToMint;
}
/// @dev set the new totalStakingHistory mapping to the current timestamp and totalScaleStaked
function setTotalStakingHistory() private {
// Get now in terms of the variable staking accuracy (days in Scale's case)
uint _nowAsTimingVariable = now.div(timingVariable);
// Set the totalStakingHistory as a timestamp of the totalScaleStaked today
totalStakingHistory[_nowAsTimingVariable] = totalScaleStaked;
}
/////////////
// Scale Owner Claiming
/////////////
/// @dev allows contract owner to claim their allocated mint
function ownerClaim() external onlyOwner {
require(now > ownerTimeLastMinted);
uint _timePassedSinceLastMint; // The amount of time passed since the owner claimed in seconds
uint _tokenMintCount; // The amount of new tokens to mint
bool _mintingSuccess; // The success of minting the new Scale tokens
// Calculate the number of seconds that have passed since the owner last took a claim
_timePassedSinceLastMint = now.sub(ownerTimeLastMinted);
assert(_timePassedSinceLastMint > 0);
// Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate
_tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, ownerMintRate);
// Mint the owner's tokens; this also increases totalSupply
_mintingSuccess = mint(msg.sender, _tokenMintCount);
require(_mintingSuccess);
// New minting was a success. Set last time minted to current block.timestamp (now)
ownerTimeLastMinted = now;
}
////////////////////////////////
// Scale Pool Distribution
////////////////////////////////
// @dev anyone can call this function that mints Scale to the pool dedicated to Scale distribution to rewards pool
function poolIssue() public {
// Do not allow tokens to be minted to the pool until the pool is set
require(pool != address(0));
// Make sure time has passed since last minted to pool
require(now > poolTimeLastMinted);
require(pool != address(0));
uint _timePassedSinceLastMint; // The amount of time passed since the pool claimed in seconds
uint _tokenMintCount; // The amount of new tokens to mint
bool _mintingSuccess; // The success of minting the new Scale tokens
// Calculate the number of seconds that have passed since the owner last took a claim
_timePassedSinceLastMint = now.sub(poolTimeLastMinted);
assert(_timePassedSinceLastMint > 0);
// Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate
_tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, poolMintRate);
// Mint the owner's tokens; this also increases totalSupply
_mintingSuccess = mint(pool, _tokenMintCount);
require(_mintingSuccess);
// New minting was a success! Set last time minted to current block.timestamp (now)
poolTimeLastMinted = now;
}
/// @dev sets the address for the rewards pool
/// @param _newAddress pool Address
function setPool(address _newAddress) public onlyOwner {
pool = _newAddress;
}
////////////////////////////////
// Helper Functions
////////////////////////////////
/// @dev calculateFraction allows us to better handle the Solidity ugliness of not having decimals as a native type
/// @param _numerator is the top part of the fraction we are calculating
/// @param _denominator is the bottom part of the fraction we are calculating
/// @param _precision tells the function how many significant digits to calculate out to
/// @return quotient returns the result of our fraction calculation
function calculateFraction(uint _numerator, uint _denominator, uint _precision) pure private returns(uint quotient) {
// Take passed value and expand it to the required precision
_numerator = _numerator.mul(10 ** (_precision + 1));
// Handle last-digit rounding
uint _quotient = ((_numerator.div(_denominator)) + 5) / 10;
return (_quotient);
}
/// @dev Determines the amount of Scale to create based on the number of seconds that have passed
/// @param _timeInSeconds is the time passed in seconds to mint for
/// @return uint with the calculated number of new tokens to mint
function calculateMintTotal(uint _timeInSeconds, uint _mintRate) pure private returns(uint mintAmount) {
// Calculates the amount of tokens to mint based upon the number of seconds passed
return(_timeInSeconds.mul(_mintRate));
}
} | function to check the staking balance of a user _user to check the balance of return uint of the stake balance | function stakeBalanceOf(address _user) view external returns (uint) {
return stakeBalances[_user].stakeBalance;
}
| 12,235,982 |
./full_match/5/0x5911a979e00C4847B2BE34F733e59cF6885fC48A/sources/contracts/claim/factory/MerkleSet.sol | Tests membership in the merkle set/ | function _testMembership(
bytes32 leaf,
bytes32[] memory merkleProof
) internal view returns (bool) {
return MerkleProof.verify(merkleProof, merkleRoot, leaf);
}
| 1,891,659 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
// File: @openzeppelin/contracts/GSN/Context.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 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
/**
* @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: contracts/uniswapv2/interfaces/IUniswapV2Pair.sol
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;
}
// File: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol
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;
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @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: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @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/utils/Address.sol
/**
* @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");
}
/**
* @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/ERC20.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;
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 { }
}
// File: contracts/strategies/IStrategy.sol
// Assume the strategy generates `TOKEN`.
interface IStrategy {
function approve(IERC20 _token) external;
function getValuePerShare(address _vault) external view returns(uint256);
function pendingValuePerShare(address _vault) external view returns (uint256);
// Deposit tokens to a farm to yield more tokens.
function deposit(address _vault, uint256 _amount) external;
// Claim the profit from a farm.
function claim(address _vault) external;
// Withdraw the principal from a farm.
function withdraw(address _vault, uint256 _amount) external;
// Target farming token of this strategy.
function getTargetToken() external view returns(address);
}
// File: contracts/SodaMaster.sol
/*
Here we have a list of constants. In order to get access to an address
managed by SodaMaster, the calling contract should copy and define
some of these constants and use them as keys.
Keys themselves are immutable. Addresses can be immutable or mutable.
a) Vault addresses are immutable once set, and the list may grow:
K_VAULT_WETH = 0;
K_VAULT_USDT_ETH_SUSHI_LP = 1;
K_VAULT_SOETH_ETH_UNI_V2_LP = 2;
K_VAULT_SODA_ETH_UNI_V2_LP = 3;
K_VAULT_GT = 4;
K_VAULT_GT_ETH_UNI_V2_LP = 5;
b) SodaMade token addresses are immutable once set, and the list may grow:
K_MADE_SOETH = 0;
c) Strategy addresses are mutable:
K_STRATEGY_CREATE_SODA = 0;
K_STRATEGY_EAT_SUSHI = 1;
K_STRATEGY_SHARE_REVENUE = 2;
d) Calculator addresses are mutable:
K_CALCULATOR_WETH = 0;
Solidity doesn't allow me to define global constants, so please
always make sure the key name and key value are copied as the same
in different contracts.
*/
// SodaMaster manages the addresses all the other contracts of the system.
// This contract is owned by Timelock.
contract SodaMaster is Ownable {
address public pool;
address public bank;
address public revenue;
address public dev;
address public soda;
address public wETH;
address public usdt;
address public uniswapV2Factory;
mapping(address => bool) public isVault;
mapping(uint256 => address) public vaultByKey;
mapping(address => bool) public isSodaMade;
mapping(uint256 => address) public sodaMadeByKey;
mapping(address => bool) public isStrategy;
mapping(uint256 => address) public strategyByKey;
mapping(address => bool) public isCalculator;
mapping(uint256 => address) public calculatorByKey;
// Immutable once set.
function setPool(address _pool) external onlyOwner {
require(pool == address(0));
pool = _pool;
}
// Immutable once set.
// Bank owns all the SodaMade tokens.
function setBank(address _bank) external onlyOwner {
require(bank == address(0));
bank = _bank;
}
// Mutable in case we want to upgrade this module.
function setRevenue(address _revenue) external onlyOwner {
revenue = _revenue;
}
// Mutable in case we want to upgrade this module.
function setDev(address _dev) external onlyOwner {
dev = _dev;
}
// Mutable, in case Uniswap has changed or we want to switch to sushi.
// The core systems, Pool and Bank, don't rely on Uniswap, so there is no risk.
function setUniswapV2Factory(address _uniswapV2Factory) external onlyOwner {
uniswapV2Factory = _uniswapV2Factory;
}
// Immutable once set.
function setWETH(address _wETH) external onlyOwner {
require(wETH == address(0));
wETH = _wETH;
}
// Immutable once set. Hopefully Tether is reliable.
// Even if it fails, not a big deal, we only used USDT to estimate APY.
function setUSDT(address _usdt) external onlyOwner {
require(usdt == address(0));
usdt = _usdt;
}
// Immutable once set.
function setSoda(address _soda) external onlyOwner {
require(soda == address(0));
soda = _soda;
}
// Immutable once added, and you can always add more.
function addVault(uint256 _key, address _vault) external onlyOwner {
require(vaultByKey[_key] == address(0), "vault: key is taken");
isVault[_vault] = true;
vaultByKey[_key] = _vault;
}
// Immutable once added, and you can always add more.
function addSodaMade(uint256 _key, address _sodaMade) external onlyOwner {
require(sodaMadeByKey[_key] == address(0), "sodaMade: key is taken");
isSodaMade[_sodaMade] = true;
sodaMadeByKey[_key] = _sodaMade;
}
// Mutable and removable.
function addStrategy(uint256 _key, address _strategy) external onlyOwner {
isStrategy[_strategy] = true;
strategyByKey[_key] = _strategy;
}
function removeStrategy(uint256 _key) external onlyOwner {
isStrategy[strategyByKey[_key]] = false;
delete strategyByKey[_key];
}
// Mutable and removable.
function addCalculator(uint256 _key, address _calculator) external onlyOwner {
isCalculator[_calculator] = true;
calculatorByKey[_key] = _calculator;
}
function removeCalculator(uint256 _key) external onlyOwner {
isCalculator[calculatorByKey[_key]] = false;
delete calculatorByKey[_key];
}
}
// File: contracts/tokens/SodaVault.sol
// SodaVault is owned by Timelock
contract SodaVault is ERC20, Ownable {
using SafeMath for uint256;
uint256 constant PER_SHARE_SIZE = 1e12;
mapping (address => uint256) public lockedAmount;
mapping (address => mapping(uint256 => uint256)) public rewards;
mapping (address => mapping(uint256 => uint256)) public debts;
IStrategy[] public strategies;
SodaMaster public sodaMaster;
constructor (SodaMaster _sodaMaster, string memory _name, string memory _symbol) ERC20(_name, _symbol) public {
sodaMaster = _sodaMaster;
}
function setStrategies(IStrategy[] memory _strategies) public onlyOwner {
delete strategies;
for (uint256 i = 0; i < _strategies.length; ++i) {
strategies.push(_strategies[i]);
}
}
function getStrategyCount() view public returns(uint count) {
return strategies.length;
}
/// @notice Creates `_amount` token to `_to`. Must only be called by SodaPool.
function mintByPool(address _to, uint256 _amount) public {
require(_msgSender() == sodaMaster.pool(), "not pool");
_deposit(_amount);
_updateReward(_to);
if (_amount > 0) {
_mint(_to, _amount);
}
_updateDebt(_to);
}
// Must only be called by SodaPool.
function burnByPool(address _account, uint256 _amount) public {
require(_msgSender() == sodaMaster.pool(), "not pool");
uint256 balance = balanceOf(_account);
require(lockedAmount[_account] + _amount <= balance, "Vault: burn too much");
_withdraw(_amount);
_updateReward(_account);
_burn(_account, _amount);
_updateDebt(_account);
}
// Must only be called by SodaBank.
function transferByBank(address _from, address _to, uint256 _amount) public {
require(_msgSender() == sodaMaster.bank(), "not bank");
uint256 balance = balanceOf(_from);
require(lockedAmount[_from] + _amount <= balance);
_claim();
_updateReward(_from);
_updateReward(_to);
_transfer(_from, _to, _amount);
_updateDebt(_to);
_updateDebt(_from);
}
// Any user can transfer to another user.
function transfer(address _to, uint256 _amount) public override returns (bool) {
uint256 balance = balanceOf(_msgSender());
require(lockedAmount[_msgSender()] + _amount <= balance, "transfer: <= balance");
_updateReward(_msgSender());
_updateReward(_to);
_transfer(_msgSender(), _to, _amount);
_updateDebt(_to);
_updateDebt(_msgSender());
return true;
}
// Must only be called by SodaBank.
function lockByBank(address _account, uint256 _amount) public {
require(_msgSender() == sodaMaster.bank(), "not bank");
uint256 balance = balanceOf(_account);
require(lockedAmount[_account] + _amount <= balance, "Vault: lock too much");
lockedAmount[_account] += _amount;
}
// Must only be called by SodaBank.
function unlockByBank(address _account, uint256 _amount) public {
require(_msgSender() == sodaMaster.bank(), "not bank");
require(_amount <= lockedAmount[_account], "Vault: unlock too much");
lockedAmount[_account] -= _amount;
}
// Must only be called by SodaPool.
function clearRewardByPool(address _who) public {
require(_msgSender() == sodaMaster.pool(), "not pool");
for (uint256 i = 0; i < strategies.length; ++i) {
rewards[_who][i] = 0;
}
}
function getPendingReward(address _who, uint256 _index) public view returns (uint256) {
uint256 total = totalSupply();
if (total == 0 || _index >= strategies.length) {
return 0;
}
uint256 value = strategies[_index].getValuePerShare(address(this));
uint256 pending = strategies[_index].pendingValuePerShare(address(this));
uint256 balance = balanceOf(_who);
return balance.mul(value.add(pending)).div(PER_SHARE_SIZE).sub(debts[_who][_index]);
}
function _deposit(uint256 _amount) internal {
for (uint256 i = 0; i < strategies.length; ++i) {
strategies[i].deposit(address(this), _amount);
}
}
function _withdraw(uint256 _amount) internal {
for (uint256 i = 0; i < strategies.length; ++i) {
strategies[i].withdraw(address(this), _amount);
}
}
function _claim() internal {
for (uint256 i = 0; i < strategies.length; ++i) {
strategies[i].claim(address(this));
}
}
function _updateReward(address _who) internal {
uint256 balance = balanceOf(_who);
if (balance > 0) {
for (uint256 i = 0; i < strategies.length; ++i) {
uint256 value = strategies[i].getValuePerShare(address(this));
rewards[_who][i] = rewards[_who][i].add(balance.mul(
value).div(PER_SHARE_SIZE).sub(debts[_who][i]));
}
}
}
function _updateDebt(address _who) internal {
uint256 balance = balanceOf(_who);
for (uint256 i = 0; i < strategies.length; ++i) {
uint256 value = strategies[i].getValuePerShare(address(this));
debts[_who][i] = balance.mul(value).div(PER_SHARE_SIZE);
}
}
}
// File: contracts/calculators/ICalculator.sol
// `TOKEN` can be any ERC20 token. The first one is WETH.
abstract contract ICalculator {
function rate() external view virtual returns(uint256);
function minimumLTV() external view virtual returns(uint256);
function maximumLTV() external view virtual returns(uint256);
// Get next loan Id.
function getNextLoanId() external view virtual returns(uint256);
// Get loan creator address.
function getLoanCreator(uint256 _loanId) external view virtual returns (address);
// Get the locked `TOKEN` amount by the loan.
function getLoanLockedAmount(uint256 _loanId) external view virtual returns (uint256);
// Get the time by the loan.
function getLoanTime(uint256 _loanId) external view virtual returns (uint256);
// Get the rate by the loan.
function getLoanRate(uint256 _loanId) external view virtual returns (uint256);
// Get the minimumLTV by the loan.
function getLoanMinimumLTV(uint256 _loanId) external view virtual returns (uint256);
// Get the maximumLTV by the loan.
function getLoanMaximumLTV(uint256 _loanId) external view virtual returns (uint256);
// Get the SoMade amount of the loan principal.
function getLoanPrincipal(uint256 _loanId) external view virtual returns (uint256);
// Get the SoMade amount of the loan interest.
function getLoanInterest(uint256 _loanId) external view virtual returns (uint256);
// Get the SoMade amount that the user needs to pay back in full.
function getLoanTotal(uint256 _loanId) external view virtual returns (uint256);
// Get the extra fee for collection in SoMade.
function getLoanExtra(uint256 _loanId) external view virtual returns (uint256);
// Lend SoMade to create a new loan.
//
// Only SodaPool can call this contract, and SodaPool should make sure the
// user has enough `TOKEN` deposited.
function borrow(address _who, uint256 _amount) external virtual;
// Pay back to a loan fully.
//
// Only SodaPool can call this contract.
function payBackInFull(uint256 _loanId) external virtual;
// Collect debt if someone defaults.
//
// Only SodaPool can call this contract, and SodaPool should send `TOKEN` to
// the debt collector.
function collectDebt(uint256 _loanId) external virtual;
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.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");
}
}
}
// File: contracts/components/SodaPool.sol
// This contract is owned by Timelock.
contract SodaPool is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
SodaVault vault; // Address of vault contract.
uint256 startTime;
}
// Info of each pool.
mapping (uint256 => PoolInfo) public poolMap; // By poolId
event Deposit(address indexed user, uint256 indexed poolId, uint256 amount);
event Withdraw(address indexed user, uint256 indexed poolId, uint256 amount);
event Claim(address indexed user, uint256 indexed poolId);
constructor() public {
}
function setPoolInfo(uint256 _poolId, IERC20 _token, SodaVault _vault, uint256 _startTime) public onlyOwner {
poolMap[_poolId].token = _token;
poolMap[_poolId].vault = _vault;
poolMap[_poolId].startTime = _startTime;
}
function _handleDeposit(SodaVault _vault, IERC20 _token, uint256 _amount) internal {
uint256 count = _vault.getStrategyCount();
require(count == 1 || count == 2, "_handleDeposit: count");
// NOTE: strategy0 is always the main strategy.
address strategy0 = address(_vault.strategies(0));
_token.safeTransferFrom(address(msg.sender), strategy0, _amount);
}
function _handleWithdraw(SodaVault _vault, IERC20 _token, uint256 _amount) internal {
uint256 count = _vault.getStrategyCount();
require(count == 1 || count == 2, "_handleWithdraw: count");
address strategy0 = address(_vault.strategies(0));
_token.safeTransferFrom(strategy0, address(msg.sender), _amount);
}
function _handleRewards(SodaVault _vault) internal {
uint256 count = _vault.getStrategyCount();
for (uint256 i = 0; i < count; ++i) {
uint256 rewardPending = _vault.rewards(msg.sender, i);
if (rewardPending > 0) {
IERC20(_vault.strategies(i).getTargetToken()).safeTransferFrom(
address(_vault.strategies(i)), msg.sender, rewardPending);
}
}
_vault.clearRewardByPool(msg.sender);
}
// Deposit tokens to SodaPool for SODA allocation.
// If we have a strategy, then tokens will be moved there.
function deposit(uint256 _poolId, uint256 _amount) public {
PoolInfo storage pool = poolMap[_poolId];
require(now >= pool.startTime, "deposit: after startTime");
_handleDeposit(pool.vault, pool.token, _amount);
pool.vault.mintByPool(msg.sender, _amount);
emit Deposit(msg.sender, _poolId, _amount);
}
// Claim SODA (and potentially other tokens depends on strategy).
function claim(uint256 _poolId) public {
PoolInfo storage pool = poolMap[_poolId];
require(now >= pool.startTime, "claim: after startTime");
pool.vault.mintByPool(msg.sender, 0);
_handleRewards(pool.vault);
emit Claim(msg.sender, _poolId);
}
// Withdraw tokens from SodaPool (from a strategy first if there is one).
function withdraw(uint256 _poolId, uint256 _amount) public {
PoolInfo storage pool = poolMap[_poolId];
require(now >= pool.startTime, "withdraw: after startTime");
pool.vault.burnByPool(msg.sender, _amount);
_handleWithdraw(pool.vault, pool.token, _amount);
_handleRewards(pool.vault);
emit Withdraw(msg.sender, _poolId, _amount);
}
}
// File: contracts/tokens/SodaMade.sol
// All SodaMade tokens should be owned by SodaBank.
contract SodaMade is ERC20, Ownable {
constructor (string memory _name, string memory _symbol) ERC20(_name, _symbol) public {
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (SodaBank).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/// @notice Burns `_amount` token in `account`. Must only be called by the owner (SodaBank).
function burnFrom(address account, uint256 amount) public onlyOwner {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// File: contracts/components/SodaBank.sol
// SodaBank produces SoETH (and other SodaMade assets) by locking user's vault assets.
// This contract is owned by Timelock.
contract SodaBank is Ownable {
using SafeMath for uint256;
// Info of each pool.
struct PoolInfo {
SodaMade made;
SodaVault vault; // Address of vault contract.
ICalculator calculator;
}
// PoolInfo by poolId.
mapping(uint256 => PoolInfo) public poolMap;
// Info of each loan.
struct LoanInfo {
uint256 poolId; // Corresponding asset of the loan.
uint256 loanId; // LoanId of the loan.
}
// Loans of each user.
mapping (address => LoanInfo[]) public loanList;
SodaMaster public sodaMaster;
event Borrow(address indexed user, uint256 indexed index, uint256 indexed poolId, uint256 amount);
event PayBackInFull(address indexed user, uint256 indexed index);
event CollectDebt(address indexed user, uint256 indexed poolId, uint256 loanId);
constructor(
SodaMaster _sodaMaster
) public {
sodaMaster = _sodaMaster;
}
// Set pool info.
function setPoolInfo(uint256 _poolId, SodaMade _made, SodaVault _vault, ICalculator _calculator) public onlyOwner {
poolMap[_poolId].made = _made;
poolMap[_poolId].vault = _vault;
poolMap[_poolId].calculator = _calculator;
}
// Return length of address loan
function getLoanListLength(address _who) external view returns (uint256) {
return loanList[_who].length;
}
// Lend SoETH to create a new loan by locking vault.
function borrow(uint256 _poodId, uint256 _amount) external {
PoolInfo storage pool = poolMap[_poodId];
require(address(pool.calculator) != address(0), "no calculator");
uint256 loanId = pool.calculator.getNextLoanId();
pool.calculator.borrow(msg.sender, _amount);
uint256 lockedAmount = pool.calculator.getLoanLockedAmount(loanId);
// Locks in vault.
pool.vault.lockByBank(msg.sender, lockedAmount);
// Give user SoETH or other SodaMade tokens.
pool.made.mint(msg.sender, _amount);
// Records the loan.
LoanInfo memory loanInfo;
loanInfo.poolId = _poodId;
loanInfo.loanId = loanId;
loanList[msg.sender].push(loanInfo);
emit Borrow(msg.sender, loanList[msg.sender].length - 1, _poodId, _amount);
}
// Pay back to a loan fully.
function payBackInFull(uint256 _index) external {
require(_index < loanList[msg.sender].length, "getTotalLoan: index out of range");
PoolInfo storage pool = poolMap[loanList[msg.sender][_index].poolId];
require(address(pool.calculator) != address(0), "no calculator");
uint256 loanId = loanList[msg.sender][_index].loanId;
uint256 lockedAmount = pool.calculator.getLoanLockedAmount(loanId);
uint256 principal = pool.calculator.getLoanPrincipal(loanId);
uint256 interest = pool.calculator.getLoanInterest(loanId);
// Burn principal.
pool.made.burnFrom(msg.sender, principal);
// Transfer interest to sodaRevenue.
pool.made.transferFrom(msg.sender, sodaMaster.revenue(), interest);
pool.calculator.payBackInFull(loanId);
// Unlocks in vault.
pool.vault.unlockByBank(msg.sender, lockedAmount);
emit PayBackInFull(msg.sender, _index);
}
// Collect debt if someone defaults. Collector keeps half of the profit.
function collectDebt(uint256 _poolId, uint256 _loanId) external {
PoolInfo storage pool = poolMap[_poolId];
require(address(pool.calculator) != address(0), "no calculator");
address loanCreator = pool.calculator.getLoanCreator(_loanId);
uint256 principal = pool.calculator.getLoanPrincipal(_loanId);
uint256 interest = pool.calculator.getLoanInterest(_loanId);
uint256 extra = pool.calculator.getLoanExtra(_loanId);
uint256 lockedAmount = pool.calculator.getLoanLockedAmount(_loanId);
// Pay principal + interest + extra.
// Burn principal.
pool.made.burnFrom(msg.sender, principal);
// Transfer interest and extra to sodaRevenue.
pool.made.transferFrom(msg.sender, sodaMaster.revenue(), interest + extra);
// Clear the loan.
pool.calculator.collectDebt(_loanId);
// Unlocks in vault.
pool.vault.unlockByBank(loanCreator, lockedAmount);
pool.vault.transferByBank(loanCreator, msg.sender, lockedAmount);
emit CollectDebt(msg.sender, _poolId, _loanId);
}
}
// File: contracts/tokens/SodaToken.sol
// This token is owned by ../strategies/CreateSoda.sol
contract SodaToken is ERC20("SodaToken", "SODA"), Ownable {
/// @notice Creates `_amount` token to `_to`.
/// Must only be called by the owner (CreateSoda).
/// CreateSoda gurantees the maximum supply of SODA is 330,000,000
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// transfers delegate authority when sending a token.
// https://medium.com/bulldax-finance/sushiswap-delegation-double-spending-bug-5adcc7b3830f
function _transfer(address sender, address recipient, uint256 amount) internal override virtual {
super._transfer(sender, recipient, amount);
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
}
/// @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), "SODA::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SODA::delegateBySig: invalid nonce");
require(now <= expiry, "SODA::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, "SODA::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 SODAs (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, "SODA::_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/strategies/CreateSoda.sol
// This contract has the power to change SODA allocation among
// different pools, but can't mint more than 100,000 SODA tokens.
// With ALL_BLOCKS_AMOUNT and SODA_PER_BLOCK,
// we have 100,000 * 1 = 100,000
//
// For the remaining 900,000 SODA, we will need to deploy a new contract called
// CreateMoreSoda after the community can make a decision by voting.
//
// Currently this contract is the only owner of SodaToken and is itself owned by
// Timelock, and it has a function transferToCreateMoreSoda to transfer the
// ownership to CreateMoreSoda once all the 100,000 tokens are out.
contract CreateSoda is IStrategy, Ownable {
using SafeMath for uint256;
uint256 public constant ALL_BLOCKS_AMOUNT = 100000;
uint256 public constant SODA_PER_BLOCK = 1 * 1e18;
uint256 constant PER_SHARE_SIZE = 1e12;
// Info of each pool.
struct PoolInfo {
uint256 allocPoint; // How many allocation points assigned to this pool. SODAs to distribute per block.
uint256 lastRewardBlock; // Last block number that SODAs distribution occurs.
}
// Info of each pool.
mapping (address => PoolInfo) public poolMap; // By vault address.
// pool length
mapping (uint256 => address) public vaultMap;
uint256 public poolLength;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The first block.
uint256 public startBlock;
// startBlock + ALL_BLOCKS_AMOUNT
uint256 public endBlock;
// The SODA Pool.
SodaMaster public sodaMaster;
mapping(address => uint256) private valuePerShare; // By vault.
constructor(
SodaMaster _sodaMaster
) public {
sodaMaster = _sodaMaster;
// Approve all.
IERC20(sodaMaster.soda()).approve(sodaMaster.pool(), type(uint256).max);
}
// Admin calls this function.
function setPoolInfo(
uint256 _poolId,
address _vault,
IERC20 _token,
uint256 _allocPoint,
bool _withUpdate
) external onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
if (_poolId >= poolLength) {
poolLength = _poolId + 1;
}
vaultMap[_poolId] = _vault;
totalAllocPoint = totalAllocPoint.sub(poolMap[_vault].allocPoint).add(_allocPoint);
poolMap[_vault].allocPoint = _allocPoint;
_token.approve(sodaMaster.pool(), type(uint256).max);
}
// Admin calls this function.
function approve(IERC20 _token) external override onlyOwner {
_token.approve(sodaMaster.pool(), type(uint256).max);
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to > endBlock) {
_to = endBlock;
}
if (_from >= _to) {
return 0;
}
return _to.sub(_from);
}
function getValuePerShare(address _vault) external view override returns(uint256) {
return valuePerShare[_vault];
}
function pendingValuePerShare(address _vault) external view override returns (uint256) {
PoolInfo storage pool = poolMap[_vault];
uint256 amountInVault = IERC20(_vault).totalSupply();
if (block.number > pool.lastRewardBlock && amountInVault > 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sodaReward = multiplier.mul(SODA_PER_BLOCK).mul(pool.allocPoint).div(totalAllocPoint);
sodaReward = sodaReward.sub(sodaReward.div(20));
return sodaReward.mul(PER_SHARE_SIZE).div(amountInVault);
} else {
return 0;
}
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
for (uint256 i = 0; i < poolLength; ++i) {
_update(vaultMap[i]);
}
}
// Update reward variables of the given pool to be up-to-date.
function _update(address _vault) public {
PoolInfo storage pool = poolMap[_vault];
if (pool.allocPoint <= 0) {
return;
}
if (pool.lastRewardBlock == 0) {
// This is the first time that we start counting blocks.
pool.lastRewardBlock = block.number;
}
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 shareAmount = IERC20(_vault).totalSupply();
if (shareAmount == 0) {
// Only after now >= pool.startTime in SodaPool, shareAmount can be larger than 0.
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 allReward = multiplier.mul(SODA_PER_BLOCK).mul(pool.allocPoint).div(totalAllocPoint);
SodaToken(sodaMaster.soda()).mint(sodaMaster.dev(), allReward.div(20)); // 5% goes to dev.
uint256 farmerReward = allReward.sub(allReward.div(20));
SodaToken(sodaMaster.soda()).mint(address(this), farmerReward); // 95% goes to farmers.
valuePerShare[_vault] = valuePerShare[_vault].add(farmerReward.mul(PER_SHARE_SIZE).div(shareAmount));
pool.lastRewardBlock = block.number;
}
/**
* @dev See {IStrategy-deposit}.
*/
function deposit(address _vault, uint256 _amount) external override {
require(sodaMaster.isVault(msg.sender), "sender not vault");
if (startBlock == 0) {
startBlock = block.number;
endBlock = startBlock + ALL_BLOCKS_AMOUNT;
}
_update(_vault);
}
/**
* @dev See {IStrategy-claim}.
*/
function claim(address _vault) external override {
require(sodaMaster.isVault(msg.sender), "sender not vault");
_update(_vault);
}
/**
* @dev See {IStrategy-withdraw}.
*/
function withdraw(address _vault, uint256 _amount) external override {
require(sodaMaster.isVault(msg.sender), "sender not vault");
_update(_vault);
}
/**
* @dev See {IStrategy-getTargetToken}.
*/
function getTargetToken() external view override returns(address) {
return sodaMaster.soda();
}
// This only happens after all the 100,000 tokens are minted, and should
// be after the community can vote (I promise by then Timelock will
// be administrated by GovernorAlpha).
//
// Community (of the future), please make sure _createMoreSoda contract is
// safe enough to pull the trigger.
function transferToCreateMoreSoda(address _createMoreSoda) external onlyOwner {
require(block.number > endBlock);
SodaToken(sodaMaster.soda()).transferOwnership(_createMoreSoda);
}
}
// File: contracts/SodaDataBoard.sol
// Query data related to soda.
// This contract is owned by Timelock.
contract SodaDataBoard is Ownable {
SodaMaster public sodaMaster;
constructor(SodaMaster _sodaMaster) public {
sodaMaster = _sodaMaster;
}
function getCalculatorStat(uint256 _poolId) public view returns(uint256, uint256, uint256) {
ICalculator calculator;
(,, calculator) = SodaBank(sodaMaster.bank()).poolMap(_poolId);
uint256 rate = calculator.rate();
uint256 minimumLTV = calculator.minimumLTV();
uint256 maximumLTV = calculator.maximumLTV();
return (rate, minimumLTV, maximumLTV);
}
function getPendingReward(uint256 _poolId, uint256 _index) public view returns(uint256) {
SodaVault vault;
(, vault,) = SodaPool(sodaMaster.pool()).poolMap(_poolId);
return vault.getPendingReward(msg.sender, _index);
}
// get APY * 100
function getAPY(uint256 _poolId, address _token, bool _isLPToken) public view returns(uint256) {
(, SodaVault vault,) = SodaPool(sodaMaster.pool()).poolMap(_poolId);
uint256 MK_STRATEGY_CREATE_SODA = 0;
CreateSoda createSoda = CreateSoda(sodaMaster.strategyByKey(MK_STRATEGY_CREATE_SODA));
(uint256 allocPoint,) = createSoda.poolMap(address(vault));
uint256 totalAlloc = createSoda.totalAllocPoint();
if (totalAlloc == 0) {
return 0;
}
uint256 vaultSupply = vault.totalSupply();
uint256 factor = 1; // 1 SODA per block
if (vaultSupply == 0) {
// Assume $1 is put in.
return getSodaPrice() * factor * 5760 * 100 * allocPoint / totalAlloc / 1e6;
}
// 2250000 is the estimated yearly block number of ethereum.
// 1e18 comes from vaultSupply.
if (_isLPToken) {
uint256 lpPrice = getEthLpPrice(_token);
if (lpPrice == 0) {
return 0;
}
return getSodaPrice() * factor * 2250000 * 100 * allocPoint * 1e18 / totalAlloc / lpPrice / vaultSupply;
} else {
uint256 tokenPrice = getTokenPrice(_token);
if (tokenPrice == 0) {
return 0;
}
return getSodaPrice() * factor * 2250000 * 100 * allocPoint * 1e18 / totalAlloc / tokenPrice / vaultSupply;
}
}
// return user loan record size.
function getUserLoanLength(address _who) public view returns (uint256) {
return SodaBank(sodaMaster.bank()).getLoanListLength(_who);
}
// return loan info (loanId,principal, interest, lockedAmount, time, rate, maximumLTV)
function getUserLoan(address _who, uint256 _index) public view returns (uint256,uint256,uint256,uint256,uint256,uint256,uint256) {
uint256 poolId;
uint256 loanId;
(poolId, loanId) = SodaBank(sodaMaster.bank()).loanList(_who, _index);
ICalculator calculator;
(,, calculator) = SodaBank(sodaMaster.bank()).poolMap(poolId);
uint256 lockedAmount = calculator.getLoanLockedAmount(loanId);
uint256 principal = calculator.getLoanPrincipal(loanId);
uint256 interest = calculator.getLoanInterest(loanId);
uint256 time = calculator.getLoanTime(loanId);
uint256 rate = calculator.getLoanRate(loanId);
uint256 maximumLTV = calculator.getLoanMaximumLTV(loanId);
return (loanId, principal, interest, lockedAmount, time, rate, maximumLTV);
}
function getEthLpPrice(address _token) public view returns (uint256) {
IUniswapV2Factory factory = IUniswapV2Factory(sodaMaster.uniswapV2Factory());
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(_token, sodaMaster.wETH()));
(uint256 reserve0, uint256 reserve1,) = pair.getReserves();
if (pair.token0() == _token) {
return reserve1 * getEthPrice() * 2 / pair.totalSupply();
} else {
return reserve0 * getEthPrice() * 2 / pair.totalSupply();
}
}
// Return the 6 digit price of eth on uniswap.
function getEthPrice() public view returns (uint256) {
IUniswapV2Factory factory = IUniswapV2Factory(sodaMaster.uniswapV2Factory());
IUniswapV2Pair ethUSDTPair = IUniswapV2Pair(factory.getPair(sodaMaster.wETH(), sodaMaster.usdt()));
require(address(ethUSDTPair) != address(0), "ethUSDTPair need set by owner");
(uint reserve0, uint reserve1,) = ethUSDTPair.getReserves();
// USDT has 6 digits and WETH has 18 digits.
// To get 6 digits after floating point, we need 1e18.
if (ethUSDTPair.token0() == sodaMaster.wETH()) {
return reserve1 * 1e18 / reserve0;
} else {
return reserve0 * 1e18 / reserve1;
}
}
// Return the 6 digit price of soda on uniswap.
function getSodaPrice() public view returns (uint256) {
return getTokenPrice(sodaMaster.soda());
}
// Return the 6 digit price of any token on uniswap.
function getTokenPrice(address _token) public view returns (uint256) {
if (_token == sodaMaster.wETH()) {
return getEthPrice();
}
IUniswapV2Factory factory = IUniswapV2Factory(sodaMaster.uniswapV2Factory());
IUniswapV2Pair tokenETHPair = IUniswapV2Pair(factory.getPair(_token, sodaMaster.wETH()));
require(address(tokenETHPair) != address(0), "tokenETHPair need set by owner");
(uint reserve0, uint reserve1,) = tokenETHPair.getReserves();
if (reserve0 == 0 || reserve1 == 0) {
return 0;
}
// For 18 digits tokens, we will return 6 digits price.
if (tokenETHPair.token0() == _token) {
return getEthPrice() * reserve1 / reserve0;
} else {
return getEthPrice() * reserve0 / reserve1;
}
}
} | Return the 6 digit price of soda on uniswap. | function getSodaPrice() public view returns (uint256) {
return getTokenPrice(sodaMaster.soda());
}
| 6,835,731 |
./full_match/4/0x05F5230b57E7D1d96B7ECC3975e447955a690b85/sources/BondingCurveFactory_flat.sol | return address: The address of the uniswap router./ | function getRouterAddress() public view returns(address) {
return address(routerInstance);
}
| 651,453 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract VolcanoCoin is ERC20{
//set variables
uint totalSupply = 10000;
address owner;
event totalSupplyInc(uint);
// event Transfer(address indexed sender, address indexed receiver, uint256 amount);
struct usersBalances {
address user;
uint balance;
}
mapping(address => usersBalances) balances; //(Q1b)
address[] public userList; //this has an automatic getter
uint numUsers;
constructor() ERC20("TOKEN", "TKN") {
//Set owner statically, once.
owner = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;
// add the owner to the array, and set the owner balance = total supply
userList.push(owner);
balances[msg.sender].balance = totalSupply;
//initialise number of users to 0
// numUsers = 0;
}
//Only owner permissions
modifier onlyOwner {
if (msg.sender == owner){ //if condition () is true...
_; //...then execute the rest of the function
}
}
//Only your OWN permissions
modifier onlyMsgSender(address _address) {
if (_address == msg.sender){ //if condition () is true...
_; //...then execute the rest of the function
}
}
//require that the msg.sender isnt in the list of users already
//Get user balance from balances mapping (Q2b)
function getUserBalance() public view returns(uint){
return balances[msg.sender].balance;
}
function newUser() public {
// push msg.sender to the array
userList.push(msg.sender);
// set new user balance to 0 in mapping!
balances[msg.sender].balance = 0;
// increment number of users
// numUsers++;
}
function numberOfUsers() public view returns (uint) {
// return length of dynamic array
return userList.length;
}
//Get total supply
function getTotalSupply() public view returns(uint){
return totalSupply;
}
// Increment total supply by 1000 tokens - owner only
function incTotalSupply() public onlyOwner {
totalSupply = totalSupply + 1000;
//Should increment the balance of the owner with 1000 here?
emit totalSupplyInc(totalSupply);
}
function transferTokens(address _recipient, uint256 _amount) public payable {
require(_recipient != address(0));
require(balances[msg.sender].balance >= _amount);
require(_recipient != msg.sender);
balances[msg.sender].balance = balances[msg.sender].balance - _amount;
balances[_recipient].balance = balances[_recipient].balance + _amount; //SafeMath???
emit Transfer(msg.sender, _recipient, _amount);
}
} | Increment total supply by 1000 tokens - owner onlyShould increment the balance of the owner with 1000 here? | function incTotalSupply() public onlyOwner {
totalSupply = totalSupply + 1000;
emit totalSupplyInc(totalSupply);
}
| 15,861,018 |
pragma solidity ^0.5.7;
library MyEtherFundControl {
using MyEtherFundControl for data;
struct data {
uint min;
uint max;
uint startAt;
uint maxAmountPerDay;
mapping(uint => uint) investmentsPerDay;
}
function addInvestment(data storage control, uint amount) internal{
control.investmentsPerDay[getCurrentDay()] += amount;
}
function getMaxInvestmentToday(data storage control) internal view returns (uint){
if (control.startAt == 0) {
return 10000 ether;
}
if (control.startAt > now) {
return 10000 ether;
}
return control.maxAmountPerDay - control.getTodayInvestment();
}
function getCurrentDay() internal view returns (uint){
return now / 24 hours;
}
function getTodayInvestment(data storage control) internal view returns (uint){
return control.investmentsPerDay[getCurrentDay()];
}
}
contract MyEtherFund {
using MyEtherFundControl for MyEtherFundControl.data;
address public owner;
uint constant public MIN_INVEST = 10000000000000000 wei;
uint public currentInterest = 3;
uint public depositAmount;
uint public paidAmount;
uint public round = 1;
uint public lastPaymentDate;
uint public advertisingCommission = 10;
uint public devCommission = 5;
uint public profitThreshold = 2;
address payable public devAddress;
address payable public advertiserAddress;
// investors addresses
address[] public addresses;
// mapping address to Investor
mapping(address => Investor) public investors;
// currently on restart phase or not?
bool public pause;
struct TopInvestor {
address payable addr;
uint deposit;
uint from;
}
struct Investor{
uint id;
uint deposit;
uint deposits;
uint paidOut;
uint date;
address payable referrer;
}
event Invest(address indexed addr, uint amount, address referrer);
event Payout(address indexed addr, uint amount, string eventType, address from);
event NextRoundStarted(uint indexed round, uint date, uint deposit);
event PerseusUpdate(address addr, string eventType);
TopInvestor public top_investor;
MyEtherFundControl.data private myEtherFundControl;
// only contract creator access
modifier onlyOwner {if (msg.sender == owner) _;}
constructor() public {
owner = msg.sender;
devAddress = msg.sender;
advertiserAddress = msg.sender;
addresses.length = 1;
myEtherFundControl.min = 30 ether;
myEtherFundControl.max = 500 ether;
}
// change advertiser address
function setAdvertiserAddr(address payable addr) onlyOwner public {
advertiserAddress = addr;
}
// change owner
function transferOwnership(address payable addr) onlyOwner public {
owner = addr;
}
function setMyEtherFundControlStartAt(uint startAt) onlyOwner public {
myEtherFundControl.startAt = startAt;
}
function getMyEtherFundControlStartAt() public view returns (uint) {
return myEtherFundControl.startAt;
}
// set max of investments per day. Only devAddress have access to this function
function setGrowingMaxPerDay(uint maxAmountPerDay) public {
require(maxAmountPerDay >= myEtherFundControl.min && maxAmountPerDay <= myEtherFundControl.max, "incorrect amount");
require(msg.sender == devAddress, "Only dev team have access to this function");
myEtherFundControl.maxAmountPerDay = maxAmountPerDay;
}
// main function, which accept new investments and do dividends payouts
// if you send 0 ETH to this function, you will receive your dividends
function() payable external { //inject DOS BY COMPLEX FALLBACK
// ensure that payment not from contract
if (isContract()) {
revert();
}
// if contract is on restarting phase - do some work before restart
if (pause) {
doRestart();
msg.sender.call.gas(2301).value(msg.value)(""); // return all money to sender
return;
}
if (0 == msg.value) {
payoutDividends(); // do pay out
return;
}
require(msg.value >= MIN_INVEST, "Too small amount, minimum 0.01 ether");
Investor storage user = investors[msg.sender];
if (user.id == 0) { // if no saved address, save it
user.id = addresses.push(msg.sender);
user.date = now;
// check referrer
address payable referrer = bytesToAddress(msg.data);
if (investors[referrer].deposit > 0 && referrer != msg.sender) {
user.referrer = referrer;
}
} else {
payoutDividends(); // else pay dividends before reinvest
}
uint investment = min(myEtherFundControl.getMaxInvestmentToday(), msg.value);
require(investment > 0, "Too much investments today");
// update investor
user.deposit += investment;
user.deposits += 1;
emit Invest(msg.sender, investment, user.referrer);
depositAmount += investment;
lastPaymentDate = now;
if (devAddress.send(investment / 100 * devCommission)) {
// project fee
}
if (advertiserAddress.send(investment / 100 * advertisingCommission)) {
// advert fee
}
// referrer commission for all deposits
uint bonusAmount = investment / 100 * currentInterest;
// user have referrer
if (user.referrer != address(0)) {
if (user.referrer.send(bonusAmount)) { // pay referrer commission
emit Payout(user.referrer, bonusAmount, "referral", msg.sender);
}
if (user.deposits == 1) { // only the first deposit cashback
if (msg.sender.send(bonusAmount)) {
emit Payout(msg.sender, bonusAmount, "cash-back", address(0));
}
}
} else if (top_investor.addr != address(0) && top_investor.from + 24 hours > now) {
if (top_investor.addr.send(bonusAmount)) { // pay bonus to current Perseus
emit Payout(top_investor.addr, bonusAmount, "perseus", msg.sender);
}
}
// check and maybe update current interest rate
considerCurrentInterest();
// add investment to the myEtherFundControl service
myEtherFundControl.addInvestment(investment);
// Perseus has changed? do some checks
considerTopInvestor(investment);
// return excess eth (if myEtherFundControl is active)
if (msg.value > investment) {
msg.sender.call.gas(2301).value(msg.value - investment)("");
}
}
function getTodayInvestment() view public returns (uint){
return myEtherFundControl.getTodayInvestment();
}
function getMaximumInvestmentPerDay() view public returns (uint){
return myEtherFundControl.maxAmountPerDay;
}
function payoutDividends() private {
require(investors[msg.sender].id > 0, "Investor not found");
uint amount = getInvestorDividendsAmount(msg.sender);
if (amount == 0) {
return;
}
// save last paid out date
investors[msg.sender].date = now;
// save total paid out for investor
investors[msg.sender].paidOut += amount;
// save total paid out for contract
paidAmount += amount;
uint balance = address(this).balance;
// check contract balance, if not enough - do restart
if (balance < amount) {
pause = true;
amount = balance;
}
msg.sender.transfer(amount);
emit Payout(msg.sender, amount, "payout", address(0));
// if investor has reached the limit (x2 profit) - delete him
if (investors[msg.sender].paidOut >= investors[msg.sender].deposit * profitThreshold) {
delete investors[msg.sender];
}
}
// remove all investors and prepare data for the new round!
function doRestart() private {
uint txs;
for (uint i = addresses.length - 1; i > 0; i--) {
delete investors[addresses[i]]; // remove investor
addresses.length -= 1; // decrease addr length
if (txs++ == 150) { // 150 to prevent gas over use
return;
}
}
emit NextRoundStarted(round, now, depositAmount);
pause = false; // stop pause, play
round += 1; // increase round number
depositAmount = 0;
paidAmount = 0;
lastPaymentDate = now;
}
function getInvestorCount() public view returns (uint) {
return addresses.length - 1;
}
function considerCurrentInterest() internal{
uint interest;
// if 4000 ETH - set interest rate for 1%
if (depositAmount >= 4000 ether) {
interest = 1;
} else if (depositAmount >= 1000 ether) { // if 1000 ETH - set interest rate for 2%
interest = 2;
} else {
interest = 3; // base = 3%
}
// if interest has not changed, return
if (interest >= currentInterest) {
return;
}
currentInterest = interest;
}
// top investor in 24 hours
function considerTopInvestor(uint amount) internal {
// if current dead, delete him
if (top_investor.addr != address(0) && top_investor.from + 24 hours < now) {
top_investor.addr = address(0);
top_investor.deposit = 0;
emit PerseusUpdate(msg.sender, "expired");
}
// if the investment bigger than current made - change top investor
if (amount > top_investor.deposit) {
top_investor = TopInvestor(msg.sender, amount, now);
emit PerseusUpdate(msg.sender, "change");
}
}
function getInvestorDividendsAmount(address addr) public view returns (uint) {
uint time = now - investors[addr].date;
return investors[addr].deposit / 100 * currentInterest * time / 1 days;
}
function bytesToAddress(bytes memory bys) private pure returns (address payable addr) {
assembly {
addr := mload(add(bys, 20))
}
}
// check that there is no contract in the middle
function isContract() internal view returns (bool) {
return msg.sender != tx.origin;
}
// get min value from a and b
function min(uint a, uint b) public pure returns (uint) {
if (a < b) return a;
else return b;
}
} | top investor in 24 hours if current dead, delete him | function considerTopInvestor(uint amount) internal {
if (top_investor.addr != address(0) && top_investor.from + 24 hours < now) {
top_investor.addr = address(0);
top_investor.deposit = 0;
emit PerseusUpdate(msg.sender, "expired");
}
if (amount > top_investor.deposit) {
top_investor = TopInvestor(msg.sender, amount, now);
emit PerseusUpdate(msg.sender, "change");
}
}
| 14,027,770 |
./partial_match/1313161554/0x548A76388D5A11C37a34f24be3560eFFf7289267/sources/_contracts/abstract/ReaperBaseStrategyv2.sol | This function must be overriden simply for access control purposes. Only DEFAULT_ADMIN_ROLE can upgrade the implementation once the timelock has passed./ | function _authorizeUpgrade(address) internal override {
_atLeastRole(DEFAULT_ADMIN_ROLE);
require(upgradeProposalTime + UPGRADE_TIMELOCK < block.timestamp);
clearUpgradeCooldown();
}
| 16,915,265 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// 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 "../../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;
/**
* @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 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 "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureChecker {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// 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.9;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
abstract contract ERC721Base is IERC165, IERC721 {
using Address for address;
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
bytes4 internal constant ERC165ID = 0x01ffc9a7;
uint256 internal constant OPERATOR_FLAG = 0x8000000000000000000000000000000000000000000000000000000000000000;
uint256 internal constant NOT_OPERATOR_FLAG = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
mapping(uint256 => uint256) internal _owners;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => bool)) internal _operatorsForAll;
mapping(uint256 => address) internal _operators;
function name() public pure virtual returns (string memory) {
revert("NOT_IMPLEMENTED");
}
/// @notice Approve an operator to transfer a specific token on the senders behalf.
/// @param operator The address receiving the approval.
/// @param id The id of the token.
function approve(address operator, uint256 id) external override {
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
require(msg.sender == owner || _operatorsForAll[owner][msg.sender], "UNAUTHORIZED_APPROVAL");
_approveFor(owner, blockNumber, operator, id);
}
/// @notice Transfer a token between 2 addresses.
/// @param from The sender of the token.
/// @param to The recipient of the token.
/// @param id The id of the token.
function transferFrom(
address from,
address to,
uint256 id
) external override {
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
require(owner == from, "NOT_OWNER");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
if (msg.sender != from) {
require(
(operatorEnabled && _operators[id] == msg.sender) || _operatorsForAll[from][msg.sender],
"UNAUTHORIZED_TRANSFER"
);
}
_transferFrom(from, to, id);
}
/// @notice Transfer a token between 2 addresses letting the receiver know of the transfer.
/// @param from The send of the token.
/// @param to The recipient of the token.
/// @param id The id of the token.
function safeTransferFrom(
address from,
address to,
uint256 id
) external override {
safeTransferFrom(from, to, id, "");
}
/// @notice Set the approval for an operator to manage all the tokens of the sender.
/// @param operator The address receiving the approval.
/// @param approved The determination of the approval.
function setApprovalForAll(address operator, bool approved) external override {
_setApprovalForAll(msg.sender, operator, approved);
}
/// @notice Get the number of tokens owned by an address.
/// @param owner The address to look for.
/// @return balance The number of tokens owned by the address.
function balanceOf(address owner) public view override returns (uint256 balance) {
require(owner != address(0), "ZERO_ADDRESS_OWNER");
balance = _balances[owner];
}
/// @notice Get the owner of a token.
/// @param id The id of the token.
/// @return owner The address of the token owner.
function ownerOf(uint256 id) external view override returns (address owner) {
owner = _ownerOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
}
/// @notice Get the owner of a token and the blockNumber of the last transfer, useful to voting mechanism.
/// @param id The id of the token.
/// @return owner The address of the token owner.
/// @return blockNumber The blocknumber at which the last transfer of that id happened.
function ownerAndLastTransferBlockNumberOf(uint256 id) internal view returns (address owner, uint256 blockNumber) {
return _ownerAndBlockNumberOf(id);
}
struct OwnerData {
address owner;
uint256 lastTransferBlockNumber;
}
/// @notice Get the list of owner of a token and the blockNumber of its last transfer, useful to voting mechanism.
/// @param ids The list of token ids to check.
/// @return ownersData The list of (owner, lastTransferBlockNumber) for each ids given as input.
function ownerAndLastTransferBlockNumberList(uint256[] calldata ids)
external
view
returns (OwnerData[] memory ownersData)
{
ownersData = new OwnerData[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 data = _owners[ids[i]];
ownersData[i].owner = address(uint160(data));
ownersData[i].lastTransferBlockNumber = (data >> 160) & 0xFFFFFFFFFFFFFFFFFFFFFF;
}
}
/// @notice Get the approved operator for a specific token.
/// @param id The id of the token.
/// @return The address of the operator.
function getApproved(uint256 id) external view override returns (address) {
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
if (operatorEnabled) {
return _operators[id];
} else {
return address(0);
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool isOperator) {
return _operatorsForAll[owner][operator];
}
/// @notice Transfer a token between 2 addresses letting the receiver knows of the transfer.
/// @param from The sender of the token.
/// @param to The recipient of the token.
/// @param id The id of the token.
/// @param data Additional data.
function safeTransferFrom(
address from,
address to,
uint256 id,
bytes memory data
) public override {
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
require(owner == from, "NOT_OWNER");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
if (msg.sender != from) {
require(
(operatorEnabled && _operators[id] == msg.sender) || _operatorsForAll[from][msg.sender],
"UNAUTHORIZED_TRANSFER"
);
}
_safeTransferFrom(from, to, id, data);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override returns (bool) {
/// 0x01ffc9a7 is ERC165.
/// 0x80ac58cd is ERC721
/// 0x5b5e139f is for ERC721 metadata
return id == 0x01ffc9a7 || id == 0x80ac58cd || id == 0x5b5e139f;
}
function _safeTransferFrom(
address from,
address to,
uint256 id,
bytes memory data
) internal {
_transferFrom(from, to, id);
if (to.isContract()) {
require(_checkOnERC721Received(msg.sender, from, to, id, data), "ERC721_TRANSFER_REJECTED");
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 id
) internal virtual {}
function _transferFrom(
address from,
address to,
uint256 id
) internal {
_beforeTokenTransfer(from, to, id);
unchecked {
_balances[to]++;
if (from != address(0)) {
_balances[from]--;
}
}
_owners[id] = (block.number << 160) | uint256(uint160(to));
emit Transfer(from, to, id);
}
/// @dev See approve.
function _approveFor(
address owner,
uint256 blockNumber,
address operator,
uint256 id
) internal {
if (operator == address(0)) {
_owners[id] = (blockNumber << 160) | uint256(uint160(owner));
} else {
_owners[id] = OPERATOR_FLAG | (blockNumber << 160) | uint256(uint160(owner));
_operators[id] = operator;
}
emit Approval(owner, operator, id);
}
/// @dev See setApprovalForAll.
function _setApprovalForAll(
address sender,
address operator,
bool approved
) internal {
_operatorsForAll[sender][operator] = approved;
emit ApprovalForAll(sender, operator, approved);
}
/// @dev Check if receiving contract accepts erc721 transfers.
/// @param operator The address of the operator.
/// @param from The from address, may be different from msg.sender.
/// @param to The adddress we want to transfer to.
/// @param id The id of the token we would like to transfer.
/// @param _data Any additional data to send with the transfer.
/// @return Whether the expected value of 0x150b7a02 is returned.
function _checkOnERC721Received(
address operator,
address from,
address to,
uint256 id,
bytes memory _data
) internal returns (bool) {
bytes4 retval = IERC721Receiver(to).onERC721Received(operator, from, id, _data);
return (retval == ERC721_RECEIVED);
}
/// @dev See ownerOf
function _ownerOf(uint256 id) internal view returns (address owner) {
return address(uint160(_owners[id]));
}
/// @dev Get the owner and operatorEnabled status of a token.
/// @param id The token to query.
/// @return owner The owner of the token.
/// @return operatorEnabled Whether or not operators are enabled for this token.
function _ownerAndOperatorEnabledOf(uint256 id) internal view returns (address owner, bool operatorEnabled) {
uint256 data = _owners[id];
owner = address(uint160(data));
operatorEnabled = (data & OPERATOR_FLAG) == OPERATOR_FLAG;
}
// @dev Get the owner and operatorEnabled status of a token.
/// @param id The token to query.
/// @return owner The owner of the token.
/// @return blockNumber the blockNumber at which the owner became the owner (last transfer).
function _ownerAndBlockNumberOf(uint256 id) internal view returns (address owner, uint256 blockNumber) {
uint256 data = _owners[id];
owner = address(uint160(data));
blockNumber = (data >> 160) & 0xFFFFFFFFFFFFFFFFFFFFFF;
}
// from https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/Multicall.sol
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed.
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract.
/// @return results The results from each of the calls passed in via data.
function multicall(bytes[] calldata data) public payable 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: MIT
pragma solidity 0.8.9;
import "./ERC721Base.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "./IERC4494.sol";
abstract contract ERC721BaseWithERC4494Permit is ERC721Base {
using Address for address;
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_FOR_ALL_TYPEHASH =
keccak256("PermitForAll(address spender,uint256 nonce,uint256 deadline)");
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
uint256 private immutable _deploymentChainId;
bytes32 private immutable _deploymentDomainSeparator;
mapping(address => uint256) internal _userNonces;
constructor() {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
_deploymentChainId = chainId;
_deploymentDomainSeparator = _calculateDomainSeparator(chainId);
}
/// @dev Return the DOMAIN_SEPARATOR.
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _DOMAIN_SEPARATOR();
}
function nonces(address account) external view virtual returns (uint256 nonce) {
return accountNonces(account);
}
function nonces(uint256 id) external view virtual returns (uint256 nonce) {
return tokenNonces(id);
}
function tokenNonces(uint256 id) public view returns (uint256 nonce) {
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
return blockNumber;
}
function accountNonces(address owner) public view returns (uint256 nonce) {
return _userNonces[owner];
}
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(tokenId);
require(owner != address(0), "NONEXISTENT_TOKEN");
// We use blockNumber as nonce as we already store it per tokens. It can thus act as an increasing transfer counter.
// while technically multiple transfer could happen in the same block, the signed message would be using a previous block.
// And the transfer would use then a more recent blockNumber, invalidating that message when transfer is executed.
_requireValidPermit(owner, spender, tokenId, deadline, blockNumber, sig);
_approveFor(owner, blockNumber, spender, tokenId);
}
function permitForAll(
address signer,
address spender,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
_requireValidPermitForAll(signer, spender, deadline, _userNonces[signer]++, sig);
_setApprovalForAll(signer, spender, true);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override returns (bool) {
return
super.supportsInterface(id) ||
id == type(IERC4494).interfaceId ||
id == type(IERC4494Alternative).interfaceId;
}
// -------------------------------------------------------- INTERNAL --------------------------------------------------------------------
function _requireValidPermit(
address signer,
address spender,
uint256 id,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, spender, id, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
function _requireValidPermitForAll(
address signer,
address spender,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_FOR_ALL_TYPEHASH, spender, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
/// @dev Return the DOMAIN_SEPARATOR.
function _DOMAIN_SEPARATOR() internal view returns (bytes32) {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
// in case a fork happen, to support the chain that had to change its chainId,, we compute the domain operator
return chainId == _deploymentChainId ? _deploymentDomainSeparator : _calculateDomainSeparator(chainId);
}
/// @dev Calculate the DOMAIN_SEPARATOR.
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), chainId, address(this)));
}
}
// SPDX-License-Identifier: BSD-3-Clause
/// @title Vote checkpointing for an ERC-721 token
/*********************************
* βββββββββββββββββββββββββββββ *
* βββββββββββββββββββββββββββββ *
* βββββββββββββββββββββββββββββ *
* βββββββββββββββββββββββββββββ *
* βββββββββββββββββββββββββββββ *
* βββββββββββββββββββββββββββββ *
* βββββββββββββββββββββββββββββ *
* βββββββββββββββββββββββββββββ *
* βββββββββββββββββββββββββββββ *
* βββββββββββββββββββββββββββββ *
*********************************/
// LICENSE
// ERC721Checkpointable.sol uses and modifies part of Compound Lab's Comp.sol:
// https://github.com/compound-finance/compound-protocol/blob/ae4388e780a8d596d97619d9704a931a2752c2bc/contracts/Governance/Comp.sol
//
// Comp.sol source code Copyright 2020 Compound Labs, Inc. licensed under the BSD-3-Clause license.
// With modifications by Nounders DAO.
//
// Additional conditions of BSD-3-Clause can be found here: https://opensource.org/licenses/BSD-3-Clause
//
// MODIFICATIONS
// Checkpointing logic from Comp.sol has been used with the following modifications:
// - `delegates` is renamed to `_delegates` and is set to private
// - `delegates` is a public function that uses the `_delegates` mapping look-up, but unlike
// Comp.sol, returns the delegator's own address if there is no delegate.
// This avoids the delegator needing to "delegate to self" with an additional transaction
// - `_transferTokens()` is renamed `_beforeTokenTransfer()` and adapted to hook into OpenZeppelin's ERC721 hooks.
pragma solidity 0.8.9;
import "./ERC721BaseWithERC4494Permit.sol";
abstract contract ERC721Checkpointable is ERC721BaseWithERC4494Permit {
bool internal _useCheckpoints = true; // can only be disabled and never re-enabled
/// @notice Defines decimals as per ERC-20 convention to make integrations with 3rd party governance platforms easier
uint8 public constant decimals = 0;
/// @notice A record of each accounts delegate
mapping(address => address) private _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 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 delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @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, uint256 previousBalance, uint256 newBalance);
/**
* @notice The votes a delegator can delegate, which is the current balance of the delegator.
* @dev Used when calling `_delegate()`
*/
function votesToDelegate(address delegator) public view returns (uint96) {
return safe96(balanceOf(delegator), "ERC721Checkpointable::votesToDelegate: amount exceeds 96 bits");
}
/**
* @notice Overrides the standard `Comp.sol` delegates mapping to return
* the delegator's own address if they haven't delegated.
* This avoids having to delegate to oneself.
*/
function delegates(address delegator) public view returns (address) {
address current = _delegates[delegator];
return current == address(0) ? delegator : current;
}
/**
* @notice Adapted from `_transferTokens()` in `Comp.sol` to update delegate votes.
* @dev hooks into ERC721Base's `ERC721._transfer`
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
super._beforeTokenTransfer(from, to, tokenId);
if (_useCheckpoints) {
/// @notice Differs from `_transferTokens()` to use `delegates` override method to simulate auto-delegation
_moveDelegates(delegates(from), delegates(to), 1);
}
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
if (delegatee == address(0)) delegatee = msg.sender;
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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry))
)
);
// TODO support smart contract wallet via IERC721, require change in function signature to know which signer to call first
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "ERC721Checkpointable::delegateBySig: invalid signature");
require(nonce == _userNonces[signatory]++, "ERC721Checkpointable::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "ERC721Checkpointable::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) public view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @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 getVotes(address account) external view returns (uint96) {
return getCurrentVotes(account);
}
/**
* @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, uint256 blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "ERC721Checkpointable::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;
}
/**
* @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 getPastVotes(address account, uint256 blockNumber) external view returns (uint96) {
return this.getPriorVotes(account, blockNumber);
}
function _delegate(address delegator, address delegatee) internal {
/// @notice differs from `_delegate()` in `Comp.sol` to use `delegates` override method to simulate auto-delegation
address currentDelegate = delegates(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
uint96 amount = votesToDelegate(delegator);
_moveDelegates(currentDelegate, delegatee, amount);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "ERC721Checkpointable::_moveDelegates: amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "ERC721Checkpointable::_moveDelegates: amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(
block.number,
"ERC721Checkpointable::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
interface IERC4494 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Allows to retrieve current nonce for token
/// @param tokenId token id
/// @return current token nonce
function nonces(uint256 tokenId) external view returns (uint256);
/// @notice function to be called by anyone to approve `spender` using a Permit signature
/// @dev Anyone can call this to approve `spender`, even a third-party
/// @param spender the actor to approve
/// @param tokenId the token id
/// @param deadline the deadline for the permit to be used
/// @param signature permit
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory signature
) external;
}
interface IERC4494Alternative {
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Allows to retrieve current nonce for token
/// @param tokenId token id
/// @return current token nonce
function tokenNonces(uint256 tokenId) external view returns (uint256);
/// @notice function to be called by anyone to approve `spender` using a Permit signature
/// @dev Anyone can call this to approve `spender`, even a third-party
/// @param spender the actor to approve
/// @param tokenId the token id
/// @param deadline the deadline for the permit to be used
/// @param signature permit
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory signature
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
abstract contract WithSupportForOpenSeaProxies {
address internal immutable _proxyRegistryAddress;
constructor(address proxyRegistryAddress) {
_proxyRegistryAddress = proxyRegistryAddress;
}
function _isOpenSeaProxy(address owner, address operator) internal view returns (bool) {
if (_proxyRegistryAddress == address(0)) {
return false;
}
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress);
return address(proxyRegistry.proxies(owner)) == operator;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "./BleepsRoles.sol";
import "../base/ERC721Checkpointable.sol";
import "../interfaces/ITokenURI.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "../base/WithSupportForOpenSeaProxies.sol";
contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ReverseRegistrar {
function setName(string memory name) external returns (bytes32);
}
interface ENS {
function owner(bytes32 node) external view returns (address);
}
contract BleepsRoles {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event TokenURIAdminSet(address newTokenURIAdmin);
event RoyaltyAdminSet(address newRoyaltyAdmin);
event MinterAdminSet(address newMinterAdmin);
event GuardianSet(address newGuardian);
event MinterSet(address newMinter);
bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
ENS internal immutable _ens;
///@notice the address of the current owner, that is able to set ENS names and withdraw ERC20 owned by the contract.
address public owner;
/// @notice tokenURIAdmin can update the tokenURI contract, this is intended to be relinquished once the tokenURI has been heavily tested in the wild and that no modification are needed.
address public tokenURIAdmin;
/// @notice address allowed to set royalty parameters
address public royaltyAdmin;
/// @notice minterAdmin can update the minter. At the time being there is 576 Bleeps but there is space for extra instrument and the upper limit is 1024.
/// could be given to the DAO later so instrument can be added, the sale of these new bleeps could benenfit the DAO too and add new members.
address public minterAdmin;
/// @notice address allowed to mint, allow the sale contract to be separated from the token contract that can focus on the core logic
/// Once all 1024 potential bleeps (there could be less, at minimum there are 576 bleeps) are minted, no minter can mint anymore
address public minter;
/// @notice guardian has some special vetoing power to guide the direction of the DAO. It can only remove rights from the DAO. It could be used to immortalize rules.
/// For example: the royalty setup could be frozen.
address public guardian;
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian
) {
_ens = ENS(ens);
owner = initialOwner;
tokenURIAdmin = initialTokenURIAdmin;
royaltyAdmin = initialRoyaltyAdmin;
minterAdmin = initialMinterAdmin;
guardian = initialGuardian;
emit OwnershipTransferred(address(0), initialOwner);
emit TokenURIAdminSet(initialTokenURIAdmin);
emit RoyaltyAdminSet(initialRoyaltyAdmin);
emit MinterAdminSet(initialMinterAdmin);
emit GuardianSet(initialGuardian);
}
function setENSName(string memory name) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
ReverseRegistrar reverseRegistrar = ReverseRegistrar(_ens.owner(ADDR_REVERSE_NODE));
reverseRegistrar.setName(name);
}
function withdrawERC20(IERC20 token, address to) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
token.transfer(to, token.balanceOf(address(this)));
}
/**
* @notice Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external {
address oldOwner = owner;
require(msg.sender == oldOwner);
owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @notice set the new tokenURIAdmin that can change the tokenURI
* Can only be called by the current tokenURI admin.
*/
function setTokenURIAdmin(address newTokenURIAdmin) external {
require(
msg.sender == tokenURIAdmin || (msg.sender == guardian && newTokenURIAdmin == address(0)),
"NOT_AUTHORIZED"
);
tokenURIAdmin = newTokenURIAdmin;
emit TokenURIAdminSet(newTokenURIAdmin);
}
/**
* @notice set the new royaltyAdmin that can change the royalties
* Can only be called by the current royalty admin.
*/
function setRoyaltyAdmin(address newRoyaltyAdmin) external {
require(
msg.sender == royaltyAdmin || (msg.sender == guardian && newRoyaltyAdmin == address(0)),
"NOT_AUTHORIZED"
);
royaltyAdmin = newRoyaltyAdmin;
emit RoyaltyAdminSet(newRoyaltyAdmin);
}
/**
* @notice set the new minterAdmin that can set the minter for Bleeps
* Can only be called by the current minter admin.
*/
function setMinterAdmin(address newMinterAdmin) external {
require(
msg.sender == minterAdmin || (msg.sender == guardian && newMinterAdmin == address(0)),
"NOT_AUTHORIZED"
);
minterAdmin = newMinterAdmin;
emit MinterAdminSet(newMinterAdmin);
}
/**
* @notice set the new guardian that can freeze the other admins (except owner).
* Can only be called by the current guardian.
*/
function setGuardian(address newGuardian) external {
require(msg.sender == guardian, "NOT_AUTHORIZED");
guardian = newGuardian;
emit GuardianSet(newGuardian);
}
/**
* @notice set the new minter that can mint Bleeps (up to 1024).
* Can only be called by the minter admin.
*/
function setMinter(address newMinter) external {
require(msg.sender == minterAdmin, "NOT_AUTHORIZED");
minter = newMinter;
emit MinterSet(newMinter);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
interface ITokenURI {
function tokenURI(uint256 id) external view returns (string memory);
function contractURI(address receiver, uint96 per10Thousands) external view returns (string memory);
} | gives the note and instrument for a particular Bleep id. id bleep id which represent a pair of (note, instrument). return note the note index (0 to 63) starting from C2 to D7 return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total). | function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
| 6,180,858 |
/**
*Submitted for verification at Etherscan.io on 2022-02-19
*/
// SPDX-License-Identifier: MIT
// Amended by HashLips
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
pragma solidity ^0.8.0;
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
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;
}
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
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");
}
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/IERC1155Receiver.sol
pragma solidity ^0.8.0;
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/IERC1155.sol
pragma solidity ^0.8.0;
/**
* @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;
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol
pragma solidity ^0.8.0;
/**
* @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);
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol
pragma solidity ^0.8.0;
/**
* @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 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;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @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) public 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 {
_setApprovalForAll(_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(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(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(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
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, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, 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 (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
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 `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, 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 from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
__ ______ ________ ______
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
*/
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.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.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;
}
}
pragma solidity ^0.8.0;
contract L2EPassPrinter is ERC1155, Ownable {
string public name;
string public symbol;
mapping(uint => string) public tokenURI;
constructor() ERC1155("") {
name = "[L2E]Pass";
symbol = "L2E";
}
function mint(address _to, uint _id, uint _amount) external onlyOwner {
_mint(_to, _id, _amount, "");
}
function mintBatch(address _to, uint[] memory _ids, uint[] memory _amounts) external onlyOwner {
_mintBatch(_to, _ids, _amounts, "");
}
function burn(uint _id, uint _amount) external {
_burn(msg.sender, _id, _amount);
}
function burnBatch(uint[] memory _ids, uint[] memory _amounts) external {
_burnBatch(msg.sender, _ids, _amounts);
}
function burnForMint(address _from, uint[] memory _burnIds, uint[] memory _burnAmounts, uint[] memory _mintIds, uint[] memory _mintAmounts) external onlyOwner {
_burnBatch(_from, _burnIds, _burnAmounts);
_mintBatch(_from, _mintIds, _mintAmounts, "");
}
function setURI(uint _id, string memory _uri) external onlyOwner {
tokenURI[_id] = _uri;
emit URI(_uri, _id);
}
function uri(uint _id) public override view returns (string memory) {
return tokenURI[_id];
}
} | 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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
| \ / \ | \ / \
| $$ | $$$$$$\| $$$$$$$$ | $$$$$$\ ______ ______ __ __ ______
| $$ \$$__| $$| $$__ | $$ __\$$ / \ / \ | \ | \ / \
| $$ / $$| $$ \ | $$| \| $$$$$$\| $$$$$$\| $$ | $$| $$$$$$\
| $$ | $$$$$$ | $$$$$ | $$ \$$$$| $$ \$$| $$ | $$| $$ | $$| $$ | $$
| $$_____ | $$_____ | $$_____ | $$__| $$| $$ | $$__/ $$| $$__/ $$| $$__/ $$
| $$ \| $$ \| $$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ $$
\$$$$$$$$ \$$$$$$$$ \$$$$$$$$ \$$$$$$ \$$ \$$$$$$ \$$$$$$ | $$$$$$$
| $$
| $$
\$$
| 15,086,163 |
pragma solidity ^0.4.23;
interface ApproveAndCallFallBack {
function receiveApproval(
address from,
uint256 _amount,
address _token,
bytes _data
) external;
}
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController {
require(msg.sender == controller);
_;
}
address public controller;
constructor() internal {
controller = msg.sender;
}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
/*
* Used to proxy function calls to the RLPReader for testing
*/
/*
* @author Hamdi Allam [email protected]
* Please reach our for any questions/concerns
*/
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
if (item.length == 0)
return RLPItem(0, 0);
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) {
require(isList(item));
uint items = numItems(item);
result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
}
/*
* Helpers
*/
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) internal pure returns (uint) {
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) internal pure returns (uint len) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 1;
else if (byte0 < STRING_LONG_START)
return byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
len := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
return byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
len := add(dataLen, add(byteLen, 1))
}
}
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) internal pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/** RLPItem conversions into data types **/
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte");
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix according to RLP spec
require(item.len == 21, "Invalid RLPItem. Addresses are encoded in 20 bytes");
uint memPtr = item.memPtr + 1; // skip the length prefix
uint addr;
assembly {
addr := div(mload(memPtr), exp(256, 12)) // right shift 12 bytes. we want the most significant 20 bytes
}
return address(addr);
}
function toUint(RLPItem memory item) internal pure returns (uint) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint memPtr = item.memPtr + offset;
uint result;
assembly {
result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset; // data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) internal pure {
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
contract RLPHelper {
using RLPReader for bytes;
using RLPReader for uint;
using RLPReader for RLPReader.RLPItem;
function isList(bytes memory item) public pure returns (bool) {
RLPReader.RLPItem memory rlpItem = item.toRlpItem();
return rlpItem.isList();
}
function itemLength(bytes memory item) public pure returns (uint) {
uint memPtr;
assembly {
memPtr := add(0x20, item)
}
return memPtr._itemLength();
}
function numItems(bytes memory item) public pure returns (uint) {
RLPReader.RLPItem memory rlpItem = item.toRlpItem();
return rlpItem.numItems();
}
function toBytes(bytes memory item) public pure returns (bytes) {
RLPReader.RLPItem memory rlpItem = item.toRlpItem();
return rlpItem.toBytes();
}
function toUint(bytes memory item) public pure returns (uint) {
RLPReader.RLPItem memory rlpItem = item.toRlpItem();
return rlpItem.toUint();
}
function toAddress(bytes memory item) public pure returns (address) {
RLPReader.RLPItem memory rlpItem = item.toRlpItem();
return rlpItem.toAddress();
}
function toBoolean(bytes memory item) public pure returns (bool) {
RLPReader.RLPItem memory rlpItem = item.toRlpItem();
return rlpItem.toBoolean();
}
function bytesToString(bytes memory item) public pure returns (string) {
RLPReader.RLPItem memory rlpItem = item.toRlpItem();
return string(rlpItem.toBytes());
}
/* custom destructuring */
/*function customDestructure(bytes memory item) public pure returns (address, bool, uint) {
// first three elements follow the return types in order. Ignore the rest
RLPReader.RLPItem[] memory items = item.toRlpItem().toList();
return (items[0].toAddress(), items[1].toBoolean(), items[2].toUint());
}
function customNestedDestructure(bytes memory item) public pure returns (address, uint) {
RLPReader.RLPItem[] memory items = item.toRlpItem().toList();
items = items[0].toList();
return (items[0].toAddress(), items[1].toUint());
}*/
//======================================
function pollTitle(bytes memory item) public pure returns (string) {
RLPReader.RLPItem[] memory items = item.toRlpItem().toList();
return string(items[0].toBytes());
}
function pollBallot(bytes memory item, uint ballotNum) public pure returns (string) {
RLPReader.RLPItem[] memory items = item.toRlpItem().toList();
items = items[1].toList();
return string(items[ballotNum].toBytes());
}
}
/*
Copyright 2016, Jordi Baylina
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 MiniMeToken Contract
* @author Jordi Baylina
* @dev This token contract's goal is to make it easy for anyone to clone this
* token using the token distribution at a given block, this will allow DAO's
* and DApps to upgrade their features in a decentralized manner without
* affecting the original token
* @dev It is ERC20 compliant, but still needs to under go further testing.
*/
/**
* @dev The token controller contract must implement these functions
*/
interface TokenController {
/**
* @notice Called when `_owner` sends ether to the MiniMe Token contract
* @param _owner The address that sent the ether to create tokens
* @return True if the ether is accepted, false if it throws
*/
function proxyPayment(address _owner) external payable returns(bool);
/**
* @notice Notifies the controller about a token transfer allowing the
* controller to react if desired
* @param _from The origin of the transfer
* @param _to The destination of the transfer
* @param _amount The amount of the transfer
* @return False if the controller does not authorize the transfer
*/
function onTransfer(address _from, address _to, uint _amount) external returns(bool);
/**
* @notice Notifies the controller about an approval allowing the
* controller to react if desired
* @param _owner The address that calls `approve()`
* @param _spender The spender in the `approve()` call
* @param _amount The amount in the `approve()` call
* @return False if the controller does not authorize the approval
*/
function onApprove(address _owner, address _spender, uint _amount) external
returns(bool);
}
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
interface ERC20Token {
/**
* @notice send `_value` token to `_to` from `msg.sender`
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transfer(address _to, uint256 _value) external returns (bool success);
/**
* @notice `msg.sender` approves `_spender` to spend `_value` tokens
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return Whether the approval was successful or not
*/
function approve(address _spender, uint256 _value) external returns (bool success);
/**
* @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
/**
* @param _owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address _owner) external view returns (uint256 balance);
/**
* @param _owner The address of the account owning tokens
* @param _spender The address of the account able to transfer the tokens
* @return Amount of remaining tokens allowed to spent
*/
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
/**
* @notice return total supply of tokens
*/
function totalSupply() external view returns (uint256 supply);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract MiniMeTokenInterface is ERC20Token {
/**
* @notice `msg.sender` approves `_spender` to send `_amount` tokens on
* its behalf, and then a function is triggered in the contract that is
* being approved, `_spender`. This allows users to use their tokens to
* interact with contracts in one function call instead of two
* @param _spender The address of the contract able to transfer the tokens
* @param _amount The amount of tokens to be approved for transfer
* @return True if the function call was successful
*/
function approveAndCall(
address _spender,
uint256 _amount,
bytes _extraData
)
external
returns (bool success);
/**
* @notice Creates a new clone token with the initial distribution being
* this token at `_snapshotBlock`
* @param _cloneTokenName Name of the clone token
* @param _cloneDecimalUnits Number of decimals of the smallest unit
* @param _cloneTokenSymbol Symbol of the clone token
* @param _snapshotBlock Block when the distribution of the parent token is
* copied to set the initial distribution of the new clone token;
* if the block is zero than the actual block, the current block is used
* @param _transfersEnabled True if transfers are allowed in the clone
* @return The address of the new MiniMeToken Contract
*/
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
)
public
returns(address);
/**
* @notice Generates `_amount` tokens that are assigned to `_owner`
* @param _owner The address that will be assigned the new tokens
* @param _amount The quantity of tokens generated
* @return True if the tokens are generated correctly
*/
function generateTokens(
address _owner,
uint _amount
)
public
returns (bool);
/**
* @notice Burns `_amount` tokens from `_owner`
* @param _owner The address that will lose the tokens
* @param _amount The quantity of tokens to burn
* @return True if the tokens are burned correctly
*/
function destroyTokens(
address _owner,
uint _amount
)
public
returns (bool);
/**
* @notice Enables token holders to transfer their tokens freely if true
* @param _transfersEnabled True if transfers are allowed in the clone
*/
function enableTransfers(bool _transfersEnabled) public;
/**
* @notice This method can be used by the controller to extract mistakenly
* sent tokens to this contract.
* @param _token The address of the token contract that you want to recover
* set to 0 in case you want to extract ether.
*/
function claimTokens(address _token) public;
/**
* @dev Queries the balance of `_owner` at a specific `_blockNumber`
* @param _owner The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at `_blockNumber`
*/
function balanceOfAt(
address _owner,
uint _blockNumber
)
public
constant
returns (uint);
/**
* @notice Total amount of tokens at a specific `_blockNumber`.
* @param _blockNumber The block number when the totalSupply is queried
* @return The total amount of tokens at `_blockNumber`
*/
function totalSupplyAt(uint _blockNumber) public view returns(uint);
}
////////////////
// MiniMeTokenFactory
////////////////
/**
* @dev This contract is used to generate clone contracts from a contract.
* In solidity this is the way to create a contract from a contract of the
* same class
*/
contract MiniMeTokenFactory {
/**
* @notice Update the DApp by creating a new token with new functionalities
* the msg.sender becomes the controller of this clone token
* @param _parentToken Address of the token being cloned
* @param _snapshotBlock Block of the parent token that will
* determine the initial distribution of the clone token
* @param _tokenName Name of the new token
* @param _decimalUnits Number of decimals of the new token
* @param _tokenSymbol Token Symbol for the new token
* @param _transfersEnabled If true, tokens will be able to be transferred
* @return The address of the new token contract
*/
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
/**
* @dev The actual token contract, the default controller is the msg.sender
* that deploys the contract, so usually this token will be deployed by a
* token controller contract, which Giveth will call a "Campaign"
*/
contract MiniMeToken is MiniMeTokenInterface, Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = "MMT_0.1"; //An arbitrary versioning scheme
/**
* @dev `Checkpoint` is the structure that attaches a block number to a
* given value, the block number attached is the one that last changed the
* value
*/
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/**
* @notice Constructor to create a MiniMeToken
* @param _tokenFactory The address of the MiniMeTokenFactory contract that
* will create the Clone token contracts, the token factory needs to be
* deployed first
* @param _parentToken Address of the parent token, set to 0x0 if it is a
* new token
* @param _parentSnapShotBlock Block of the parent token that will
* determine the initial distribution of the clone token, set to 0 if it
* is a new token
* @param _tokenName Name of the new token
* @param _decimalUnits Number of decimals of the new token
* @param _tokenSymbol Token Symbol for the new token
* @param _transfersEnabled If true, tokens will be able to be transferred
*/
constructor(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
)
public
{
require(_tokenFactory != address(0)); //if not set, clone feature will not work properly
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// 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 returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/**
* @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 True if the transfer was successful
*/
function transferFrom(
address _from,
address _to,
uint256 _amount
)
public
returns (bool success)
{
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount) {
return false;
}
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/**
* @dev This is the actual transfer function in the token contract, it can
* only be called by other functions in this contract.
* @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(
address _from,
address _to,
uint _amount
)
internal
returns(bool)
{
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
uint256 previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint256 previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
return true;
}
function doApprove(
address _from,
address _spender,
uint256 _amount
)
internal
returns (bool)
{
require(transfersEnabled);
// 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) || (allowed[_from][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(_from, _spender, _amount));
}
allowed[_from][_spender] = _amount;
emit Approval(_from, _spender, _amount);
return true;
}
/**
* @param _owner The address that's balance is being requested
* @return The balance of `_owner` at the current block
*/
function balanceOf(address _owner) external view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/**
* @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
* its behalf. This is a modified version of the ERC20 approve function
* to be a little 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) external returns (bool success) {
doApprove(msg.sender, _spender, _amount);
}
/**
* @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
)
external
view
returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
/**
* @notice `msg.sender` approves `_spender` to send `_amount` tokens on
* its behalf, and then a function is triggered in the contract that is
* being approved, `_spender`. This allows users to use their tokens to
* interact with contracts in one function call instead of two
* @param _spender The address of the contract able to transfer the tokens
* @param _amount The amount of tokens to be approved for transfer
* @return True if the function call was successful
*/
function approveAndCall(
address _spender,
uint256 _amount,
bytes _extraData
)
external
returns (bool success)
{
require(doApprove(msg.sender, _spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/**
* @dev This function makes it easy to get the total number of tokens
* @return The total number of tokens
*/
function totalSupply() external view returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/**
* @dev Queries the balance of `_owner` at a specific `_blockNumber`
* @param _owner The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at `_blockNumber`
*/
function balanceOfAt(
address _owner,
uint _blockNumber
)
public
view
returns (uint)
{
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/**
* @notice Total amount of tokens at a specific `_blockNumber`.
* @param _blockNumber The block number when the totalSupply is queried
* @return The total amount of tokens at `_blockNumber`
*/
function totalSupplyAt(uint _blockNumber) public view returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/**
* @notice Creates a new clone token with the initial distribution being
* this token at `_snapshotBlock`
* @param _cloneTokenName Name of the clone token
* @param _cloneDecimalUnits Number of decimals of the smallest unit
* @param _cloneTokenSymbol Symbol of the clone token
* @param _snapshotBlock Block when the distribution of the parent token is
* copied to set the initial distribution of the new clone token;
* if the block is zero than the actual block, the current block is used
* @param _transfersEnabled True if transfers are allowed in the clone
* @return The address of the new MiniMeToken Contract
*/
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
)
public
returns(address)
{
uint snapshotBlock = _snapshotBlock;
if (snapshotBlock == 0) {
snapshotBlock = block.number;
}
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
emit NewCloneToken(address(cloneToken), snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/**
* @notice Generates `_amount` tokens that are assigned to `_owner`
* @param _owner The address that will be assigned the new tokens
* @param _amount The quantity of tokens generated
* @return True if the tokens are generated correctly
*/
function generateTokens(
address _owner,
uint _amount
)
public
onlyController
returns (bool)
{
uint curTotalSupply = totalSupplyAt(block.number);
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOfAt(_owner, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
emit Transfer(0, _owner, _amount);
return true;
}
/**
* @notice Burns `_amount` tokens from `_owner`
* @param _owner The address that will lose the tokens
* @param _amount The quantity of tokens to burn
* @return True if the tokens are burned correctly
*/
function destroyTokens(
address _owner,
uint _amount
)
public
onlyController
returns (bool)
{
uint curTotalSupply = totalSupplyAt(block.number);
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOfAt(_owner, block.number);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/**
* @notice Enables token holders to transfer their tokens freely if true
* @param _transfersEnabled True if transfers are allowed in the clone
*/
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/**
* @dev `getValueAt` retrieves the number of tokens at a given block number
* @param checkpoints The history of values being queried
* @param _block The block number to retrieve the value at
* @return The number of tokens being queried
*/
function getValueAt(
Checkpoint[] storage checkpoints,
uint _block
)
view
internal
returns (uint)
{
if (checkpoints.length == 0) {
return 0;
}
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
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(Checkpoint[] storage checkpoints, uint _value) internal {
if (
(checkpoints.length == 0) ||
(checkpoints[checkpoints.length - 1].fromBlock < block.number))
{
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/**
* @dev Internal function to determine if an address is a contract
* @param _addr The address being queried
* @return True if `_addr` is a contract
*/
function isContract(address _addr) internal view returns(bool) {
uint size;
if (_addr == 0) {
return false;
}
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
/**
* @dev Helper function to return a min betwen the two uints
*/
function min(uint a, uint b) internal returns (uint) {
return a < b ? a : b;
}
/**
* @notice The fallback function: If the contract's controller has not been
* set to 0, then the `proxyPayment` method is called which relays the
* ether and creates tokens as described in the token controller contract
*/
function () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/**
* @notice This method can be used by the controller to extract mistakenly
* sent tokens to this contract.
* @param _token The address of the token contract that you want to recover
* set to 0 in case you want to extract ether.
*/
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(address(this).balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(address(this));
token.transfer(controller, balance);
emit ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
contract PollManager is Controlled {
struct Poll {
uint startBlock;
uint endTime;
bool canceled;
uint voters;
bytes description;
uint8 numBallots;
mapping(uint8 => mapping(address => uint)) ballots;
mapping(uint8 => uint) qvResults;
mapping(uint8 => uint) results;
mapping(uint8 => uint) votersByBallot;
address author;
}
Poll[] _polls;
MiniMeToken public token;
RLPHelper public rlpHelper;
/// @notice Contract constructor
/// @param _token Address of the token used for governance
constructor(address _token)
public {
token = MiniMeToken(_token);
rlpHelper = new RLPHelper();
}
/// @notice Only allow addresses that have > 0 SNT to perform an operation
modifier onlySNTHolder {
require(token.balanceOf(msg.sender) > 0, "SNT Balance is required to perform this operation");
_;
}
/// @notice Create a Poll and enable it immediatly
/// @param _endTime Block where the poll ends
/// @param _description IPFS hash with the description
/// @param _numBallots Number of ballots
function addPoll(
uint _endTime,
bytes _description,
uint8 _numBallots)
public
onlySNTHolder
returns (uint _idPoll)
{
_idPoll = addPoll(block.number, _endTime, _description, _numBallots);
}
/// @notice Create a Poll
/// @param _startBlock Block where the poll starts
/// @param _endTime Block where the poll ends
/// @param _description IPFS hash with the description
/// @param _numBallots Number of ballots
function addPoll(
uint _startBlock,
uint _endTime,
bytes _description,
uint8 _numBallots)
public
onlySNTHolder
returns (uint _idPoll)
{
require(_endTime > block.timestamp, "End time must be greater than current timestamp");
require(_startBlock >= block.number, "Start block must not be in the past");
require(_numBallots <= 100, "Only a max of 100 ballots are allowed");
_idPoll = _polls.length;
_polls.length ++;
Poll storage p = _polls[_idPoll];
p.startBlock = _startBlock;
p.endTime = _endTime;
p.voters = 0;
p.numBallots = _numBallots;
p.description = _description;
p.author = msg.sender;
emit PollCreated(_idPoll);
}
/// @notice Update poll description (title or ballots) as long as it hasn't started
/// @param _idPoll Poll to update
/// @param _description IPFS hash with the description
/// @param _numBallots Number of ballots
function updatePollDescription(
uint _idPoll,
bytes _description,
uint8 _numBallots)
public
{
require(_idPoll < _polls.length, "Invalid _idPoll");
require(_numBallots <= 100, "Only a max of 100 ballots are allowed");
Poll storage p = _polls[_idPoll];
require(p.startBlock > block.number, "You cannot modify an active poll");
require(p.author == msg.sender || msg.sender == controller, "Only the owner/controller can modify the poll");
p.numBallots = _numBallots;
p.description = _description;
p.author = msg.sender;
}
/// @notice Cancel an existing poll
/// @dev Can only be done by the controller (which should be a Multisig/DAO) at any time, or by the owner if the poll hasn't started
/// @param _idPoll Poll to cancel
function cancelPoll(uint _idPoll)
public {
require(_idPoll < _polls.length, "Invalid _idPoll");
Poll storage p = _polls[_idPoll];
require(!p.canceled, "Poll has been canceled already");
require(block.timestamp <= p.endTime, "Only active polls can be canceled");
if(p.startBlock < block.number){
require(msg.sender == controller, "Only the controller can cancel the poll");
} else {
require(p.author == msg.sender, "Only the owner can cancel the poll");
}
p.canceled = true;
emit PollCanceled(_idPoll);
}
/// @notice Determine if user can bote for a poll
/// @param _idPoll Id of the poll
/// @return bool Can vote or not
function canVote(uint _idPoll)
public
view
returns(bool)
{
if(_idPoll >= _polls.length) return false;
Poll storage p = _polls[_idPoll];
uint balance = token.balanceOfAt(msg.sender, p.startBlock);
return block.number >= p.startBlock && block.timestamp < p.endTime && !p.canceled && balance != 0;
}
/// @notice Calculate square root of a uint (It has some precision loss)
/// @param x Number to calculate the square root
/// @return Square root of x
function sqrt(uint256 x) public pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
/// @notice Vote for a poll
/// @param _idPoll Poll to vote
/// @param _ballots array of (number of ballots the poll has) elements, and their sum must be less or equal to the balance at the block start
function vote(uint _idPoll, uint[] _ballots) public {
require(_idPoll < _polls.length, "Invalid _idPoll");
Poll storage p = _polls[_idPoll];
require(block.number >= p.startBlock && block.timestamp < p.endTime && !p.canceled, "Poll is inactive");
require(_ballots.length == p.numBallots, "Number of ballots is incorrect");
unvote(_idPoll);
uint amount = token.balanceOfAt(msg.sender, p.startBlock);
require(amount != 0, "No SNT balance available at start block of poll");
p.voters++;
uint totalBallots = 0;
for(uint8 i = 0; i < _ballots.length; i++){
totalBallots += _ballots[i];
p.ballots[i][msg.sender] = _ballots[i];
if(_ballots[i] != 0){
p.qvResults[i] += sqrt(_ballots[i] / 1 ether);
p.results[i] += _ballots[i];
p.votersByBallot[i]++;
}
}
require(totalBallots <= amount, "Total ballots must be less than the SNT balance at poll start block");
emit Vote(_idPoll, msg.sender, _ballots);
}
/// @notice Cancel or reset a vote
/// @param _idPoll Poll
function unvote(uint _idPoll) public {
require(_idPoll < _polls.length, "Invalid _idPoll");
Poll storage p = _polls[_idPoll];
require(block.number >= p.startBlock && block.timestamp < p.endTime && !p.canceled, "Poll is inactive");
if(p.voters == 0) return;
uint prevVotes = 0;
for(uint8 i = 0; i < p.numBallots; i++){
uint ballotAmount = p.ballots[i][msg.sender];
prevVotes += ballotAmount;
p.ballots[i][msg.sender] = 0;
if(ballotAmount != 0){
p.qvResults[i] -= sqrt(ballotAmount / 1 ether);
p.results[i] -= ballotAmount;
p.votersByBallot[i]--;
}
}
if(prevVotes != 0){
p.voters--;
}
emit Unvote(_idPoll, msg.sender);
}
// Constant Helper Function
/// @notice Get number of polls
/// @return Num of polls
function nPolls()
public
view
returns(uint)
{
return _polls.length;
}
/// @notice Get Poll info
/// @param _idPoll Poll
function poll(uint _idPoll)
public
view
returns(
uint _startBlock,
uint _endTime,
bool _canVote,
bool _canceled,
bytes _description,
uint8 _numBallots,
bool _finalized,
uint _voters,
address _author,
uint[100] _tokenTotal,
uint[100] _quadraticVotes,
uint[100] _votersByBallot
)
{
require(_idPoll < _polls.length, "Invalid _idPoll");
Poll storage p = _polls[_idPoll];
_startBlock = p.startBlock;
_endTime = p.endTime;
_canceled = p.canceled;
_canVote = canVote(_idPoll);
_description = p.description;
_numBallots = p.numBallots;
_author = p.author;
_finalized = (!p.canceled) && (block.number >= _endTime);
_voters = p.voters;
for(uint8 i = 0; i < p.numBallots; i++){
_tokenTotal[i] = p.results[i];
_quadraticVotes[i] = p.qvResults[i];
_votersByBallot[i] = p.votersByBallot[i];
}
}
/// @notice Decode poll title
/// @param _idPoll Poll
/// @return string with the poll title
function pollTitle(uint _idPoll) public view returns (string){
require(_idPoll < _polls.length, "Invalid _idPoll");
Poll memory p = _polls[_idPoll];
return rlpHelper.pollTitle(p.description);
}
/// @notice Decode poll ballot
/// @param _idPoll Poll
/// @param _ballot Index (0-based) of the ballot to decode
/// @return string with the ballot text
function pollBallot(uint _idPoll, uint _ballot) public view returns (string){
require(_idPoll < _polls.length, "Invalid _idPoll");
Poll memory p = _polls[_idPoll];
return rlpHelper.pollBallot(p.description, _ballot);
}
/// @notice Get votes for poll/ballot
/// @param _idPoll Poll
/// @param _voter Address of the voter
function getVote(uint _idPoll, address _voter)
public
view
returns (uint[100] votes){
require(_idPoll < _polls.length, "Invalid _idPoll");
Poll storage p = _polls[_idPoll];
for(uint8 i = 0; i < p.numBallots; i++){
votes[i] = p.ballots[i][_voter];
}
return votes;
}
event Vote(uint indexed idPoll, address indexed _voter, uint[] ballots);
event Unvote(uint indexed idPoll, address indexed _voter);
event PollCanceled(uint indexed idPoll);
event PollCreated(uint indexed idPoll);
} | This function makes it easy to get the total number of tokens return The total number of tokens/ | function totalSupply() external view returns (uint) {
return totalSupplyAt(block.number);
}
| 5,388,937 |
./partial_match/42161/0xB4ee30dE6BF7e8F9eFBFcC9715021144DEFDe96F/sources/contracts/community-token/MintableERC20.sol | Creates `amount` new tokens for `to`. See {ERC20-_mint}. Requirements: - the caller must have the `MINTER_ROLE`./ | function mint(address to, uint256 amount) external virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
| 3,493,192 |
./full_match/1/0xfaE2266018B3f19346BDCeA68aE6a7d9B8B1f62a/sources/Pepe Juice.sol | _saleState is a number 0-1 to set the state of contract 0-ACTIVE, 1-PUBLIC | function setSaleState(SaleState _saleState) external onlyRole(DEV) {
saleState = _saleState;
}
| 4,964,315 |
pragma solidity ^0.4.11;
// Created for conduction of Zaber ICO - http://www.zabercoin.io/
// Copying in whole or in part is prohibited.
// This code is the property of ICORating and ICOmachine - http://ICORating.com
// Authors: Ivan Fedorov and Dmitry Borodin
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant 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 does not hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant 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;
/**
* @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) onlyOwner public{
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool _paused = false;
function paused() public constant returns(bool)
{
return _paused;
}
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused());
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner public {
require(!_paused);
_paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner public {
require(_paused);
_paused = false;
Unpause();
}
}
// Contract interface for transferring current tokens to another
contract MigrationAgent
{
function migrateFrom(address _from, uint256 _value) public;
}
// (A2)
// Contract token
contract Token is Pausable{
using SafeMath for uint256;
string public constant name = "ZABERcoin";
string public constant symbol = "ZAB";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) public unpausedWallet;
bool public mintingFinished = false;
uint256 public totalMigrated;
address public migrationAgent;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Migrate(address indexed _from, address indexed _to, uint256 _value);
modifier canMint() {
require(!mintingFinished);
_;
}
function Token(){
owner = 0x0;
}
function setOwner() public{
require(owner == 0x0);
owner = msg.sender;
}
// Balance of the specified address
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
// Transfer of tokens from one account to another
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
require (_value > 0);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
// Returns the number of tokens that _owner trusted to spend from his account _spender
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// Trust _sender and spend _value tokens from your account
function approve(address _spender, uint256 _value) public returns (bool) {
// 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((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
// Transfer of tokens from the trusted address _from to the address _to in the number _value
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
require (_value > 0);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
// Issue new tokens to the address _to in the amount _amount. Available to the owner of the contract (contract Crowdsale)
function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
// Stop the release of tokens. This is not possible to cancel. Available to the owner of the contract.
// function finishMinting() public onlyOwner returns (bool) {
// mintingFinished = true;
// MintFinished();
// return true;
// }
// Redefinition of the method of the returning status of the "Exchange pause".
// Never for the owner of an unpaused wallet.
function paused() public constant returns(bool) {
return super.paused() && !unpausedWallet[msg.sender];
}
// Add a wallet ignoring the "Exchange pause". Available to the owner of the contract.
function addUnpausedWallet(address _wallet) public onlyOwner {
unpausedWallet[_wallet] = true;
}
// Remove the wallet ignoring the "Exchange pause". Available to the owner of the contract.
function delUnpausedWallet(address _wallet) public onlyOwner {
unpausedWallet[_wallet] = false;
}
// Enable the transfer of current tokens to others. Only 1 time. Disabling this is not possible.
// Available to the owner of the contract.
function setMigrationAgent(address _migrationAgent) public onlyOwner {
require(migrationAgent == 0x0);
migrationAgent = _migrationAgent;
}
// Reissue your tokens.
function migrate() public
{
uint256 value = balances[msg.sender];
require(value > 0);
totalSupply = totalSupply.sub(value);
totalMigrated = totalMigrated.add(value);
MigrationAgent(migrationAgent).migrateFrom(msg.sender, value);
Migrate(msg.sender,migrationAgent,value);
balances[msg.sender] = 0;
}
}
// (A3)
// Contract for freezing of investors' funds. Hence, investors will be able to withdraw money if the
// round does not attain the softcap. From here the wallet of the beneficiary will receive all the
// money (namely, the beneficiary, not the manager's wallet).
contract RefundVault is Ownable {
using SafeMath for uint256;
uint8 public round = 0;
enum State { Active, Refunding, Closed }
mapping (uint8 => mapping (address => uint256)) public deposited;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
function RefundVault() public {
state = State.Active;
}
// Depositing funds on behalf of an ICO investor. Available to the owner of the contract (Crowdsale Contract).
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[round][investor] = deposited[round][investor].add(msg.value);
}
// Move the collected funds to a specified address. Available to the owner of the contract.
function close(address _wallet) onlyOwner public {
require(state == State.Active);
require(_wallet != 0x0);
state = State.Closed;
Closed();
_wallet.transfer(this.balance);
}
// Allow refund to investors. Available to the owner of the contract.
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
// Return the funds to a specified investor. In case of failure of the round, the investor
// should call this method of this contract (RefundVault) or call the method claimRefund of Crowdsale
// contract. This function should be called either by the investor himself, or the company
// (or anyone) can call this function in the loop to return funds to all investors en masse.
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[round][investor];
deposited[round][investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
function restart() onlyOwner public{
require(state == State.Closed);
round += 1;
state = State.Active;
}
// Destruction of the contract with return of funds to the specified address. Available to
// the owner of the contract.
function del(address _wallet) public onlyOwner {
selfdestruct(_wallet);
}
}
contract DistributorRefundVault is RefundVault{
address public taxCollector;
uint256 public taxValue;
function DistributorRefundVault(address _taxCollector, uint256 _taxValue) RefundVault() public{
taxCollector = _taxCollector;
taxValue = _taxValue;
}
function close(address _wallet) onlyOwner public {
require(state == State.Active);
require(_wallet != 0x0);
state = State.Closed;
Closed();
uint256 allPay = this.balance;
uint256 forTarget1;
uint256 forTarget2;
if(taxValue <= allPay){
forTarget1 = taxValue;
forTarget2 = allPay.sub(taxValue);
taxValue = 0;
}else {
taxValue = taxValue.sub(allPay);
forTarget1 = allPay;
forTarget2 = 0;
}
if(forTarget1 != 0){
taxCollector.transfer(forTarget1);
}
if(forTarget2 != 0){
_wallet.transfer(forTarget2);
}
}
}
// (A1)
// The main contract for the sale and management of rounds.
contract Crowdsale{
using SafeMath for uint256;
enum ICOType {preSale, sale}
enum Roles {beneficiary,accountant,manager,observer,team}
Token public token;
bool public isFinalized = false;
bool public isInitialized = false;
bool public isPausedCrowdsale = false;
mapping (uint8 => address) public wallets;
uint256 public maxProfit; // percent from 0 to 90
uint256 public minProfit; // percent from 0 to 90
uint256 public stepProfit; // percent step, from 1 to 50 (please, read doc!)
uint256 public startTime; // unixtime
uint256 public endDiscountTime; // unixtime
uint256 public endTime; // unixtime
// How many tokens (excluding the bonus) are transferred to the investor in exchange for 1 ETH
// **THOUSANDS** 10^3 for human, 1**3 for Solidity, 1e3 for MyEtherWallet (MEW).
// Example: if 1ETH = 40.5 Token ==> use 40500
uint256 public rate;
// If the round does not attain this value before the closing date, the round is recognized as a
// failure and investors take the money back (the founders will not interfere in any way).
// **QUINTILLIONS** 10^18 / 1**18 / 1e18. Example: softcap=15ETH ==> use 15**18 (Solidity) or 15e18 (MEW)
uint256 public softCap;
// The maximum possible amount of income
// **QUINTILLIONS** 10^18 / 1**18 / 1e18. Example: hardcap=123.45ETH ==> use 123450**15 (Solidity) or 12345e15 (MEW)
uint256 public hardCap;
// If the last payment is slightly higher than the hardcap, then the usual contracts do
// not accept it, because it goes beyond the hardcap. However it is more reasonable to accept the
// last payment, very slightly raising the hardcap. The value indicates by how many ETH the
// last payment can exceed the hardcap to allow it to be paid. Immediately after this payment, the
// round closes. The funders should write here a small number, not more than 1% of the CAP.
// Can be equal to zero, to cancel.
// **QUINTILLIONS** 10^18 / 1**18 / 1e18
uint256 public overLimit;
// The minimum possible payment from an investor in ETH. Payments below this value will be rejected.
// **QUINTILLIONS** 10^18 / 1**18 / 1e18. Example: minPay=0.1ETH ==> use 100**15 (Solidity) or 100e15 (MEW)
uint256 public minPay;
uint256 ethWeiRaised;
uint256 nonEthWeiRaised;
uint256 weiPreSale;
uint256 public tokenReserved;
DistributorRefundVault public vault;
SVTAllocation public lockedAllocation;
ICOType ICO = ICOType.preSale;
uint256 allToken;
bool public team = false;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
event Initialized();
function Crowdsale(Token _token) public
{
// Initially, all next 5-7 roles/wallets are given to the Manager. The Manager is an employee of the company
// with knowledge of IT, who publishes the contract and sets it up. However, money and tokens require
// a Beneficiary and other roles (Accountant, Team, etc.). The Manager will not have the right
// to receive them. To enable this, the Manager must either enter specific wallets here, or perform
// this via method changeWallet. In the finalization methods it is written which wallet and
// what percentage of tokens are received.
// Receives all the money (when finalizing pre-ICO & ICO)
wallets[uint8(Roles.beneficiary)] = 0x8d6b447f443ce7cAA12399B60BC9E601D03111f9;
// Receives all the tokens for non-ETH investors (when finalizing pre-ICO & ICO)
wallets[uint8(Roles.accountant)] = 0x99a280Dc34A996474e5140f34434CE59b5e65879;
// All rights except the rights to receive tokens or money. Has the right to change any other
// wallets (Beneficiary, Accountant, ...), but only if the round has not started. Once the
// round is initialized, the Manager has lost all rights to change the wallets.
// If the ICO is conducted by one person, then nothing needs to be changed. Permit all 7 roles
// point to a single wallet.
wallets[uint8(Roles.manager)] = msg.sender;
// Has only the right to call paymentsInOtherCurrency (please read the document)
wallets[uint8(Roles.observer)] = 0x8baf8F18256952362E485fEF1D0909F21f9a886C;
// When the round is finalized, all team tokens are transferred to a special freezing
// contract. As soon as defrosting is over, only the Team wallet will be able to
// collect all the tokens. It does not store the address of the freezing contract,
// but the final wallet of the project team.
wallets[uint8(Roles.team)] = 0x25365d4B293Ec34c39C00bBac3e5C5Ff2dC81F4F;
// startTime, endDiscountTime, endTime (then you can change it in the setup)
changePeriod(1510311600, 1511607600, 1511607600);
// softCap & hardCap (then you can change it in the setup)
changeTargets(0 ether, 51195 ether); // $15 000 000 / $293
// rate (10^3), overLimit (10^18), minPay (10^18) (then you can change it in the setup)
changeRate(61250, 500 ether, 10 ether);
// minProfit, maxProfit, stepProfit
changeDiscount(0,0,0);
token = _token;
token.setOwner();
token.pause(); // block exchange tokens
token.addUnpausedWallet(msg.sender);
// The return of funds to investors & pay fee for partner
vault = new DistributorRefundVault(0x793ADF4FB1E8a74Dfd548B5E2B5c55b6eeC9a3f8, 10 ether);
}
// Returns the name of the current round in plain text. Constant.
function ICOSaleType() public constant returns(string){
return (ICO == ICOType.preSale)?'pre ICO':'ICO';
}
// Transfers the funds of the investor to the contract of return of funds. Internal.
function forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
// Check for the possibility of buying tokens. Inside. Constant.
function validPurchase() internal constant returns (bool) {
// The round started and did not end
bool withinPeriod = (now > startTime && now < endTime);
// Rate is greater than or equal to the minimum
bool nonZeroPurchase = msg.value >= minPay;
// hardCap is not reached, and in the event of a transaction, it will not be exceeded by more than OverLimit
bool withinCap = msg.value <= hardCap.sub(weiRaised()).add(overLimit);
// round is initialized and no "Pause of trading" is set
return withinPeriod && nonZeroPurchase && withinCap && isInitialized && !isPausedCrowdsale;
}
// Check for the ability to finalize the round. Constant.
function hasEnded() public constant returns (bool) {
bool timeReached = now > endTime;
bool capReached = weiRaised() >= hardCap;
return (timeReached || capReached) && isInitialized;
}
// Finalize. Only available to the Manager and the Beneficiary. If the round failed, then
// anyone can call the finalization to unlock the return of funds to investors
// You must call a function to finalize each round (after the pre-ICO & after the ICO)
function finalize() public {
require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender || !goalReached());
require(!isFinalized);
require(hasEnded());
isFinalized = true;
finalization();
Finalized();
}
// The logic of finalization. Internal
function finalization() internal {
// If the goal of the achievement
if (goalReached()) {
// Send ether to Beneficiary
vault.close(wallets[uint8(Roles.beneficiary)]);
// if there is anything to give
if (tokenReserved > 0) {
// Issue tokens of non-eth investors to Accountant account
token.mint(wallets[uint8(Roles.accountant)],tokenReserved);
// Reset the counter
tokenReserved = 0;
}
// If the finalization is Round 1 pre-ICO
if (ICO == ICOType.preSale) {
// Reset settings
isInitialized = false;
isFinalized = false;
// Switch to the second round (to ICO)
ICO = ICOType.sale;
// Reset the collection counter
weiPreSale = weiRaised();
ethWeiRaised = 0;
nonEthWeiRaised = 0;
// Re-start a refund contract
vault.restart();
}
else // If the second round is finalized
{
// Record how many tokens we have issued
allToken = token.totalSupply();
// Permission to collect tokens to those who can pick them up
team = true;
}
}
else // If they failed round
{
// Allow investors to withdraw their funds
vault.enableRefunds();
}
}
// The Manager freezes the tokens for the Team.
// You must call a function to finalize Round 2 (only after the ICO)
function finalize1() public {
require(wallets[uint8(Roles.manager)] == msg.sender);
require(team);
team = false;
lockedAllocation = new SVTAllocation(token, wallets[uint8(Roles.team)]);
token.addUnpausedWallet(lockedAllocation);
// 20% - tokens to Team wallet after freeze (80% for investors)
// *** CHECK THESE NUMBERS ***
token.mint(lockedAllocation,allToken.mul(20).div(80));
}
// Initializing the round. Available to the manager. After calling the function,
// the Manager loses all rights: Manager can not change the settings (setup), change
// wallets, prevent the beginning of the round, etc. You must call a function after setup
// for the initial round (before the Pre-ICO and before the ICO)
function initialize() public{
// Only the Manager
require(wallets[uint8(Roles.manager)] == msg.sender);
// If not yet initialized
require(!isInitialized);
// And the specified start time has not yet come
// If initialization return an error, check the start date!
require(now <= startTime);
initialization();
Initialized();
isInitialized = true;
}
function initialization() internal {
// no code
}
// At the request of the investor, we raise the funds (if the round has failed because of the hardcap)
function claimRefund() public{
vault.refund(msg.sender);
}
// We check whether we collected the necessary minimum funds. Constant.
function goalReached() public constant returns (bool) {
return weiRaised() >= softCap;
}
// Customize. The arguments are described in the constructor above.
function setup(uint256 _startTime, uint256 _endDiscountTime, uint256 _endTime, uint256 _softCap, uint256 _hardCap, uint256 _rate, uint256 _overLimit, uint256 _minPay, uint256 _minProfit, uint256 _maxProfit, uint256 _stepProfit) public{
changePeriod(_startTime, _endDiscountTime, _endTime);
changeTargets(_softCap, _hardCap);
changeRate(_rate, _overLimit, _minPay);
changeDiscount(_minProfit, _maxProfit, _stepProfit);
}
// Change the date and time: the beginning of the round, the end of the bonus, the end of the round. Available to Manager
// Description in the Crowdsale constructor
function changePeriod(uint256 _startTime, uint256 _endDiscountTime, uint256 _endTime) public{
require(wallets[uint8(Roles.manager)] == msg.sender);
require(!isInitialized);
// Date and time are correct
require(now <= _startTime);
require(_endDiscountTime > _startTime && _endDiscountTime <= _endTime);
startTime = _startTime;
endTime = _endTime;
endDiscountTime = _endDiscountTime;
}
// We change the purpose of raising funds. Available to the manager.
// Description in the Crowdsale constructor.
function changeTargets(uint256 _softCap, uint256 _hardCap) public {
require(wallets[uint8(Roles.manager)] == msg.sender);
require(!isInitialized);
// The parameters are correct
require(_softCap <= _hardCap);
softCap = _softCap;
hardCap = _hardCap;
}
// Change the price (the number of tokens per 1 eth), the maximum hardCap for the last bet,
// the minimum bet. Available to the Manager.
// Description in the Crowdsale constructor
function changeRate(uint256 _rate, uint256 _overLimit, uint256 _minPay) public {
require(wallets[uint8(Roles.manager)] == msg.sender);
require(!isInitialized);
require(_rate > 0);
rate = _rate;
overLimit = _overLimit;
minPay = _minPay;
}
// We change the parameters of the discount:% min bonus,% max bonus, number of steps.
// Available to the manager. Description in the Crowdsale constructor
function changeDiscount(uint256 _minProfit, uint256 _maxProfit, uint256 _stepProfit) public {
require(wallets[uint8(Roles.manager)] == msg.sender);
require(!isInitialized);
// The parameters are correct
require(_stepProfit <= _maxProfit.sub(_minProfit));
// If not zero steps
if(_stepProfit > 0){
// We will specify the maximum percentage at which it is possible to provide
// the specified number of steps without fractional parts
maxProfit = _maxProfit.sub(_minProfit).div(_stepProfit).mul(_stepProfit).add(_minProfit);
}else{
// to avoid a divide to zero error, set the bonus as static
maxProfit = _minProfit;
}
minProfit = _minProfit;
stepProfit = _stepProfit;
}
// Collected funds for the current round. Constant.
function weiRaised() public constant returns(uint256){
return ethWeiRaised.add(nonEthWeiRaised);
}
// Returns the amount of fees for both phases. Constant.
function weiTotalRaised() public constant returns(uint256){
return weiPreSale.add(weiRaised());
}
// Returns the percentage of the bonus on the current date. Constant.
function getProfitPercent() public constant returns (uint256){
return getProfitPercentForData(now);
}
// Returns the percentage of the bonus on the given date. Constant.
function getProfitPercentForData(uint256 timeNow) public constant returns (uint256)
{
// if the discount is 0 or zero steps, or the round does not start, we return the minimum discount
if(maxProfit == 0 || stepProfit == 0 || timeNow > endDiscountTime) {
return minProfit.add(100);
}
// if the round is over - the maximum
if(timeNow<=startTime) {
return maxProfit.add(100);
}
// bonus period
uint256 range = endDiscountTime.sub(startTime);
// delta bonus percentage
uint256 profitRange = maxProfit.sub(minProfit);
// Time left
uint256 timeRest = endDiscountTime.sub(timeNow);
// Divide the delta of time into
uint256 profitProcent = profitRange.div(stepProfit).mul(timeRest.mul(stepProfit.add(1)).div(range));
return profitProcent.add(minProfit).add(100);
}
// The ability to quickly check pre-ICO (only for Round 1, only 1 time). Completes the pre-ICO by
// transferring the specified number of tokens to the Accountant's wallet. Available to the Manager.
// Use only if this is provided by the script and white paper. In the normal scenario, it
// does not call and the funds are raised normally. We recommend that you delete this
// function entirely, so as not to confuse the auditors. Initialize & Finalize not needed.
// ** QUINTILIONS ** 10^18 / 1**18 / 1e18
function fastICO(uint256 _totalSupply) public {
require(wallets[uint8(Roles.manager)] == msg.sender);
require(ICO == ICOType.preSale && !isInitialized);
token.mint(wallets[uint8(Roles.accountant)], _totalSupply);
ICO = ICOType.sale;
}
// Remove the "Pause of exchange". Available to the manager at any time. If the
// manager refuses to remove the pause, then 120 days after the successful
// completion of the ICO, anyone can remove a pause and allow the exchange to continue.
// The manager does not interfere and will not be able to delay the term.
// He can only cancel the pause before the appointed time.
function tokenUnpause() public {
require(wallets[uint8(Roles.manager)] == msg.sender
|| (now > endTime + 120 days && ICO == ICOType.sale && isFinalized && goalReached()));
token.unpause();
}
// Enable the "Pause of exchange". Available to the manager until the ICO is completed.
// The manager cannot turn on the pause, for example, 3 years after the end of the ICO.
function tokenPause() public {
require(wallets[uint8(Roles.manager)] == msg.sender && !isFinalized);
token.pause();
}
// Pause of sale. Available to the manager.
function crowdsalePause() public {
require(wallets[uint8(Roles.manager)] == msg.sender);
require(isPausedCrowdsale == false);
isPausedCrowdsale = true;
}
// Withdrawal from the pause of sale. Available to the manager.
function crowdsaleUnpause() public {
require(wallets[uint8(Roles.manager)] == msg.sender);
require(isPausedCrowdsale == true);
isPausedCrowdsale = false;
}
// Checking whether the rights to address ignore the "Pause of exchange". If the
// wallet is included in this list, it can translate tokens, ignoring the pause. By default,
// only the following wallets are included:
// - Accountant wallet (he should immediately transfer tokens, but not to non-ETH investors)
// - Contract for freezing the tokens for the Team (but Team wallet not included)
// Inside. Constant.
function unpausedWallet(address _wallet) internal constant returns(bool) {
bool _accountant = wallets[uint8(Roles.accountant)] == _wallet;
return _accountant;
}
// For example - After 5 years of the project's existence, all of us suddenly decided collectively
// (company + investors) that it would be more profitable for everyone to switch to another smart
// contract responsible for tokens. The company then prepares a new token, investors
// disassemble, study, discuss, etc. After a general agreement, the manager allows any investor:
// - to burn the tokens of the previous contract
// - generate new tokens for a new contract
// It is understood that after a general solution through this function all investors
// will collectively (and voluntarily) move to a new token.
function moveTokens(address _migrationAgent) public {
require(wallets[uint8(Roles.manager)] == msg.sender);
token.setMigrationAgent(_migrationAgent);
}
// Change the address for the specified role.
// Available to any wallet owner except the observer.
// Available to the manager until the round is initialized.
// The Observer's wallet or his own manager can change at any time.
function changeWallet(Roles _role, address _wallet) public
{
require(
(msg.sender == wallets[uint8(_role)] && _role != Roles.observer)
||
(msg.sender == wallets[uint8(Roles.manager)] && (!isInitialized || _role == Roles.observer))
);
address oldWallet = wallets[uint8(_role)];
wallets[uint8(_role)] = _wallet;
if(!unpausedWallet(oldWallet))
token.delUnpausedWallet(oldWallet);
if(unpausedWallet(_wallet))
token.addUnpausedWallet(_wallet);
}
// If a little more than a year has elapsed (ICO start date + 460 days), a smart contract
// will allow you to send all the money to the Beneficiary, if any money is present. This is
// possible if you mistakenly launch the ICO for 30 years (not 30 days), investors will transfer
// money there and you will not be able to pick them up within a reasonable time. It is also
// possible that in our checked script someone will make unforeseen mistakes, spoiling the
// finalization. Without finalization, money cannot be returned. This is a rescue option to
// get around this problem, but available only after a year (460 days).
// Another reason - the ICO was a failure, but not all ETH investors took their money during the year after.
// Some investors may have lost a wallet key, for example.
// The method works equally with the pre-ICO and ICO. When the pre-ICO starts, the time for unlocking
// the distructVault begins. If the ICO is then started, then the term starts anew from the first day of the ICO.
// Next, act independently, in accordance with obligations to investors.
// Within 400 days of the start of the Round, if it fails only investors can take money. After
// the deadline this can also include the company as well as investors, depending on who is the first to use the method.
function distructVault() public {
require(wallets[uint8(Roles.beneficiary)] == msg.sender);
require(now > startTime + 400 days);
vault.del(wallets[uint8(Roles.beneficiary)]);
}
// We accept payments other than Ethereum (ETH) and other currencies, for example, Bitcoin (BTC).
// Perhaps other types of cryptocurrency - see the original terms in the white paper and on the ICO website.
// We release tokens on Ethereum. During the pre-ICO and ICO with a smart contract, you directly transfer
// the tokens there and immediately, with the same transaction, receive tokens in your wallet.
// When paying in any other currency, for example in BTC, we accept your money via one common wallet.
// Our manager fixes the amount received for the bitcoin wallet and calls the method of the smart
// contract paymentsInOtherCurrency to inform him how much foreign currency has been received - on a daily basis.
// The smart contract pins the number of accepted ETH directly and the number of BTC. Smart contract
// monitors softcap and hardcap, so as not to go beyond this framework.
// In theory, it is possible that when approaching hardcap, we will receive a transfer (one or several
// transfers) to the wallet of BTC, that together with previously received money will exceed the hardcap in total.
// In this case, we will refund all the amounts above, in order not to exceed the hardcap.
// Collection of money in BTC will be carried out via one common wallet. The wallet's address will be published
// everywhere (in a white paper, on the ICO website, on Telegram, on Bitcointalk, in this code, etc.)
// Anyone interested can check that the administrator of the smart contract writes down exactly the amount
// in ETH (in equivalent for BTC) there. In theory, the ability to bypass a smart contract to accept money in
// BTC and not register them in ETH creates a possibility for manipulation by the company. Thanks to
// paymentsInOtherCurrency however, this threat is leveled.
// Any user can check the amounts in BTC and the variable of the smart contract that accounts for this
// (paymentsInOtherCurrency method). Any user can easily check the incoming transactions in a smart contract
// on a daily basis. Any hypothetical tricks on the part of the company can be exposed and panic during the ICO,
// simply pointing out the incompatibility of paymentsInOtherCurrency (ie, the amount of ETH + BTC collection)
// and the actual transactions in BTC. The company strictly adheres to the described principles of openness.
// The company administrator is required to synchronize paymentsInOtherCurrency every working day (but you
// cannot synchronize if there are no new BTC payments). In the case of unforeseen problems, such as
// brakes on the Ethereum network, this operation may be difficult. You should only worry if the
// administrator does not synchronize the amount for more than 96 hours in a row, and the BTC wallet
// receives significant amounts.
// This scenario ensures that for the sum of all fees in all currencies this value does not exceed hardcap.
// Our BTC wallet for audit in this function: 1CAyLcES1tNuatRhnL1ooPViZ32vF5KQ4A
// ** QUINTILLIONS ** 10^18 / 1**18 / 1e18
function paymentsInOtherCurrency(uint256 _token, uint256 _value) public {
require(wallets[uint8(Roles.observer)] == msg.sender);
bool withinPeriod = (now >= startTime && now <= endTime);
bool withinCap = _value.add(ethWeiRaised) <= hardCap.add(overLimit);
require(withinPeriod && withinCap && isInitialized);
nonEthWeiRaised = _value;
tokenReserved = _token;
}
// The function for obtaining smart contract funds in ETH. If all the checks are true, the token is
// transferred to the buyer, taking into account the current bonus.
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 ProfitProcent = getProfitPercent();
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate).mul(ProfitProcent).div(100000);
// update state
ethWeiRaised = ethWeiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// buyTokens alias
function () public payable {
buyTokens(msg.sender);
}
}
// (B)
// The contract for freezing tokens for the team..
contract SVTAllocation {
using SafeMath for uint256;
Token public token;
address public owner;
uint256 public unlockedAt;
uint256 tokensCreated = 0;
// The contract takes the ERC20 coin address from which this contract will work and from the
// owner (Team wallet) who owns the funds.
function SVTAllocation(Token _token, address _owner) public{
// How many days to freeze from the moment of finalizing ICO
unlockedAt = now + 365 days; // freeze TEAM tokens for 1 year
token = _token;
owner = _owner;
}
// If the time of freezing expired will return the funds to the owner.
function unlock() public{
require(now >= unlockedAt);
require(token.transfer(owner,token.balanceOf(this)));
}
} | Check for the possibility of buying tokens. Inside. Constant. The round started and did not end Rate is greater than or equal to the minimum hardCap is not reached, and in the event of a transaction, it will not be exceeded by more than OverLimit round is initialized and no "Pause of trading" is set | function validPurchase() internal constant returns (bool) {
bool withinPeriod = (now > startTime && now < endTime);
bool nonZeroPurchase = msg.value >= minPay;
bool withinCap = msg.value <= hardCap.sub(weiRaised()).add(overLimit);
return withinPeriod && nonZeroPurchase && withinCap && isInitialized && !isPausedCrowdsale;
}
| 2,524,415 |
./partial_match/3/0xE058599081394D1feE9df4f91bb00BD600fF7896/sources/LotteryTwo.sol | Get PPDEX in UniV2 addressGet Total LP tokenssubtract a small fudge factor | function MinLPTokensGolden() public view returns (uint){
uint totalPPDEX = IERC20(PPDEX).balanceOf(UniV2Address);
uint totalLP = IUniswapV2ERC20(UniV2Address).totalSupply();
return (minPPDEXGolden.mul(totalLP) / totalPPDEX).sub(10000);
}
| 5,226,042 |
./full_match/11155111/0xbB1Bc864b3e8170a584433D4bfC4c07B9CB91Bf1/sources/contracts/swap.sol | Cancels an order This function can only be called by the initiator of the order. It requires the order to not be fully filled, disapproved or cancelled. orderId The id of the order to cancel | function cancelOrder(uint256 orderId) public {
require(
msg.sender == orders[orderId].initiator,
"Only initiator can cancel"
);
require(!orders[orderId].status.isCancelled, "Order already cancelled");
require(
orders[orderId].filledAmount < orders[orderId].amount,
"Order already fully filled"
);
orders[orderId].status.isCancelled = true;
orders[orderId].status.isApproved = false;
orders[orderId].status.orderAccepted = false;
}
| 3,790,112 |
pragma solidity 0.5.11;
// WARNING - `executeActionWithAtomicBatchCalls` has a `bytes[]` argument that
// requires ABIEncoderV2, and the alternatives are pretty convoluted. Consider
// losing that function and ABIEncoderV2 for the V1 smart wallet implementation.
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../../interfaces/DharmaSmartWalletImplementationV0Interface.sol";
import "../../../interfaces/DharmaSmartWalletImplementationV1Interface.sol";
import "../../../interfaces/DharmaSmartWalletImplementationV4Interface.sol";
import "../../../interfaces/CTokenInterface.sol";
import "../../../interfaces/CEtherInterface.sol";
import "../../../interfaces/USDCV1Interface.sol";
import "../../../interfaces/ComptrollerInterface.sol";
import "../../../interfaces/DharmaKeyRegistryInterface.sol";
import "../../../interfaces/ERC1271.sol";
/**
* @title DharmaSmartWalletImplementationV4
* @notice The V4 implementation for the Dharma smart wallet is a non-custodial,
* meta-transaction-enabled wallet with helper functions to facilitate lending
* funds using CompoundV2, and with a security backstop provided by Dharma Labs
* prior to making withdrawals or borrows. It also contains methods to support
* account recovery and generic actions, including in an atomic batch. The smart
* wallet instances utilizing this implementation are deployed through the
* Dharma Smart Wallet Factory via `CREATE2`, which allows for their address to
* be known ahead of time, and any Dai, USDC, or Ether that has already been
* sent into that address will automatically be deposited into Compound upon
* deployment of the new smart wallet instance.
*
* NOTE: this implementation is still under development and has known bugs and
* areas for improvement. The actual V4 implementation will likely be quite
* different than what is currently contained here.
*/
contract DharmaSmartWalletImplementationVX is
DharmaSmartWalletImplementationV0Interface,
DharmaSmartWalletImplementationV1Interface,
DharmaSmartWalletImplementationV4Interface {
using Address for address;
using ECDSA for bytes32;
// WARNING: DO NOT REMOVE OR REORDER STORAGE WHEN WRITING NEW IMPLEMENTATIONS!
// The user signing key associated with this account is in storage slot 0.
// It is the core differentiator when it comes to the account in question.
address private _userSigningKey;
// The nonce associated with this account is in storage slot 1. Every time a
// signature is submitted, it must have the appropriate nonce, and once it has
// been accepted the nonce will be incremented.
uint256 private _nonce;
// The self-call context flag is in storage slot 2. Some protected functions
// may only be called externally from calls originating from other methods on
// this contract, which enables appropriate exception handling on reverts.
// Any storage should only be set immediately preceding a self-call and should
// be cleared upon entering the protected function being called.
bytes4 internal _selfCallContext;
// END STORAGE DECLARATIONS - DO NOT REMOVE OR REORDER STORAGE ABOVE HERE!
// The smart wallet version will be used when constructing valid signatures.
uint256 internal constant _DHARMA_SMART_WALLET_VERSION = 4;
// The Dharma Key Registry holds a public key for verifying meta-transactions.
DharmaKeyRegistryInterface internal constant _DHARMA_KEY_REGISTRY = (
DharmaKeyRegistryInterface(0x000000000D38df53b45C5733c7b34000dE0BDF52)
);
// Account recovery is facilitated using a hard-coded recovery manager,
// controlled by Dharma and implementing appropriate timelocks.
address internal constant _ACCOUNT_RECOVERY_MANAGER = address(
0x00000000004cDa75701EeA02D1F2F9BDcE54C10D
);
// This contract interfaces with Dai, USDC, and related CompoundV2 contracts.
CTokenInterface internal constant _CDAI = CTokenInterface(
0xF5DCe57282A584D2746FaF1593d3121Fcac444dC // mainnet
);
CTokenInterface internal constant _CUSDC = CTokenInterface(
0x39AA39c021dfbaE8faC545936693aC917d5E7563 // mainnet
);
CEtherInterface internal constant _CETH = CEtherInterface(
0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5 // mainnet
);
IERC20 internal constant _DAI = IERC20(
0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359 // mainnet
);
IERC20 internal constant _USDC = IERC20(
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
USDCV1Interface internal constant _USDC_NAUGHTY = USDCV1Interface(
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
ComptrollerInterface internal constant _COMPTROLLER = ComptrollerInterface(
0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B // mainnet
);
// Compound returns a value of 0 to indicate success, or lack of an error.
uint256 internal constant _COMPOUND_SUCCESS = 0;
// ERC-1271 must return this magic value when `isValidSignature` is called.
bytes4 internal constant _ERC_1271_MAGIC_VALUE = bytes4(0x20c13b0b);
// Automatically deposit ETH if enough gas is supplied to fallback function.
// TODO: determine the appropriate value to use!
uint256 internal constant _AUTOMATIC_ETH_DEPOSIT_GAS = 100000;
function () external payable {
if (
msg.sender != address(_CETH) && // do not redeposit on withdrawals.
gasleft() > _AUTOMATIC_ETH_DEPOSIT_GAS // only deposit with adequate gas.
) {
_depositEtherOnCompound();
}
}
/**
* @notice In initializer, set up user signing key, set approval on the cDAI
* and cUSDC contracts, deposit any Dai, USDC, and ETH already at the address
* to Compound, and enter markets for cDAI, cUSDC, and cETH. Note that this
* initializer is only callable while the smart wallet instance is still in
* the contract creation phase.
* @param userSigningKey address The initial user signing key for the smart
* wallet.
*/
function initialize(address userSigningKey) external {
// Ensure that this function is only callable during contract construction.
assembly { if extcodesize(address) { revert(0, 0) } }
// Set up the user's signing key and emit a corresponding event.
_setUserSigningKey(userSigningKey);
// Approve the cDAI contract to transfer Dai on behalf of this contract.
if (_setFullApproval(AssetType.DAI)) {
// Get the current Dai balance on this contract.
uint256 daiBalance = _DAI.balanceOf(address(this));
// Try to deposit any dai balance on Compound.
_depositOnCompound(AssetType.DAI, daiBalance);
}
// Approve the cUSDC contract to transfer USDC on behalf of this contract.
if (_setFullApproval(AssetType.USDC)) {
// Get the current USDC balance on this contract.
uint256 usdcBalance = _USDC.balanceOf(address(this));
// Try to deposit any USDC balance on Compound.
_depositOnCompound(AssetType.USDC, usdcBalance);
}
// Try to deposit any Ether balance on Compound.
_depositOnCompound(AssetType.ETH, address(this).balance);
// Enter DAI + USDC + ETH markets to enable using them as borrow collateral.
_enterMarkets();
}
/**
* @notice Use all Dai, USDC, and ETH currently residing at this address to
* first repay any outstanding borrows, then to deposit and mint corresponding
* cTokens on Compound. If some step of this function fails, the function
* itself will still succeed, but an ExternalError with information on what
* went wrong will be emitted.
*/
function repayAndDeposit() external {
// Get the current Dai balance on this contract.
uint256 daiBalance = _DAI.balanceOf(address(this));
if (daiBalance > 0) {
// First use funds to try to repay Dai borrow balance.
uint256 remainingDai = _repayOnCompound(AssetType.DAI, daiBalance);
// Then deposit any remaining Dai.
_depositOnCompound(AssetType.DAI, remainingDai);
}
// Get the current USDC balance on this contract.
uint256 usdcBalance = _USDC.balanceOf(address(this));
// If there is any USDC balance, check for adequate approval for cUSDC.
if (usdcBalance > 0) {
uint256 usdcAllowance = _USDC.allowance(address(this), address(_CUSDC));
// If allowance is insufficient, try to set it before depositing.
if (usdcAllowance < usdcBalance) {
if (_setFullApproval(AssetType.USDC)) {
// First use funds to try to repay Dai borrow balance.
uint256 remainingUsdc = _repayOnCompound(AssetType.USDC, usdcBalance);
// Then deposit any remaining USDC.
_depositOnCompound(AssetType.USDC, remainingUsdc);
}
// Otherwise, go ahead and try the deposit.
} else {
// First use funds to try to repay Dai borrow balance.
uint256 remainingUsdc = _repayOnCompound(AssetType.USDC, usdcBalance);
// Then deposit any remaining USDC.
_depositOnCompound(AssetType.USDC, remainingUsdc);
}
}
// Deposit any Ether balance on this contract.
_depositEtherOnCompound();
}
/**
* @notice Withdraw Dai to a provided recipient address by redeeming the
* underlying Dai from the cDAI contract and transferring it to the recipient.
* All Dai in Compound and in the smart wallet itself can be withdrawn by
* providing an amount of uint256(-1) or 0xfff...fff. This function can be
* called directly by the account set as the global key on the Dharma Key
* Registry, or by any relayer that provides a signed message from the same
* keyholder. The nonce used for the signature must match the current nonce on
* the smart wallet, and gas supplied to the call must exceed the specified
* minimum action gas, plus the gas that will be spent before the gas check is
* reached - usually somewhere around 25,000 gas. If the withdrawal fails, an
* ExternalError with additional details on what went wrong will be emitted.
* Note that some dust may still be left over, even in the event of a max
* withdrawal, due to the fact that Dai has a higher precision than cDAI. Also
* note that the withdrawal will fail in the event that Compound does not have
* sufficient Dai available to withdraw.
* @param amount uint256 The amount of Dai to withdraw.
* @param recipient address The account to transfer the withdrawn Dai to.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return True if the withdrawal succeeded, otherwise false.
*/
function withdrawDai(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.DAIWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set the self-call context so we can call _withdrawDaiAtomic.
_selfCallContext = this.withdrawDai.selector;
// Make the atomic self-call - if redeemUnderlying fails on cDAI, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (the Dai transfer) fails, it will revert
// and roll back the first part of the call, and we'll fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._withdrawDaiAtomic.selector, amount, recipient
));
// If the atomic call failed, diagnose the reason and emit an event.
if (!ok) {
// This revert could be caused by cDai MathError or Dai transfer error.
_diagnoseAndEmitErrorRelatedToWithdrawal(AssetType.DAI);
} else {
// Set ok to false if the call succeeded but the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
/**
* @notice Protected function that can only be called from `withdrawDai` on
* this contract. It will attempt to withdraw the supplied amount of Dai, or
* the maximum amount if specified using `uint256(-1)`, to the supplied
* recipient address by redeeming the underlying Dai from the cDAI contract
* and transferring it to the recipient. An ExternalError will be emitted and
* the transfer will be skipped if the call to `redeemUnderlying` fails, and
* any revert will be caught by `withdrawDai` and diagnosed in order to emit
* an appropriate ExternalError as well.
* @param amount uint256 The amount of Dai to withdraw.
* @param recipient address The account to transfer the withdrawn Dai to.
* @return True if the withdrawal succeeded, otherwise false.
*/
function _withdrawDaiAtomic(
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.withdrawDai.selector);
// If amount = 0xfff...fff, withdraw the maximum amount possible.
bool maxWithdraw = (amount == uint256(-1));
uint256 redeemUnderlyingAmount;
if (maxWithdraw) {
redeemUnderlyingAmount = _CDAI.balanceOfUnderlying(address(this));
} else {
redeemUnderlyingAmount = amount;
}
// Attempt to withdraw specified Dai amount from Compound before proceeding.
if (_withdrawFromCompound(AssetType.DAI, redeemUnderlyingAmount)) {
// At this point dai transfer *should* never fail - wrap it just in case.
if (maxWithdraw) {
require(_DAI.transfer(recipient, _DAI.balanceOf(address(this))));
} else {
require(_DAI.transfer(recipient, amount));
}
success = true;
}
}
function borrowDai(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.DAIBorrow,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set the self-call context so we can call _borrowDaiAtomic.
_selfCallContext = this.borrowDai.selector;
// Make the atomic self-call - if borrow fails on cDAI, it will succeed but
// nothing will happen except firing an ExternalError event. If the second
// part of the self-call (the Dai transfer) fails, it will revert and roll
// back the first part of the call, and we'll fire an ExternalError event
// after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._borrowDaiAtomic.selector, amount, recipient
));
if (!ok) {
emit ExternalError(address(_DAI), "DAI contract reverted on transfer.");
} else {
// Ensure that ok == false in the event the borrow failed.
ok = abi.decode(returnData, (bool));
}
}
function _borrowDaiAtomic(
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.borrowDai.selector);
if (_borrowFromCompound(AssetType.DAI, amount)) {
// at this point dai transfer *should* never fail - wrap it just in case.
require(_DAI.transfer(recipient, amount));
success = true;
}
}
/**
* @notice Withdraw USDC to a provided recipient address by redeeming the
* underlying USDC from the cUSDC contract and transferring it to recipient.
* All USDC in Compound and in the smart wallet itself can be withdrawn by
* providing an amount of uint256(-1) or 0xfff...fff. This function can be
* called directly by the account set as the global key on the Dharma Key
* Registry, or by any relayer that provides a signed message from the same
* keyholder. The nonce used for the signature must match the current nonce on
* the smart wallet, and gas supplied to the call must exceed the specified
* minimum action gas, plus the gas that will be spent before the gas check is
* reached - usually somewhere around 25,000 gas. If the withdrawal fails, an
* ExternalError with additional details on what went wrong will be emitted.
* Note that the USDC contract can be paused and also allows for blacklisting
* accounts - either of these possibilities may cause a withdrawal to fail. In
* addition, Compound may not have sufficient USDC available at the time to
* withdraw.
* @param amount uint256 The amount of USDC to withdraw.
* @param recipient address The account to transfer the withdrawn USDC to.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return True if the withdrawal succeeded, otherwise false.
*/
function withdrawUSDC(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.USDCWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set the self-call context so we can call _withdrawUSDCAtomic.
_selfCallContext = this.withdrawUSDC.selector;
// Make the atomic self-call - if redeemUnderlying fails on cUSDC, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (USDC transfer) fails, it will revert
// and roll back the first part of the call, and we'll fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._withdrawUSDCAtomic.selector, amount, recipient
));
if (!ok) {
// This revert could be caused by cUSDC MathError or USDC transfer error.
_diagnoseAndEmitErrorRelatedToWithdrawal(AssetType.USDC);
} else {
// Ensure that ok == false in the event the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
/**
* @notice Protected function that can only be called from `withdrawUSDC` on
* this contract. It will attempt to withdraw the supplied amount of USDC, or
* the maximum amount if specified using `uint256(-1)`, to the supplied
* recipient address by redeeming the underlying USDC from the cUSDC contract
* and transferring it to the recipient. An ExternalError will be emitted and
* the transfer will be skipped if the call to `redeemUnderlying` fails, and
* any revert will be caught by `withdrawUSDC` and diagnosed in order to emit
* an appropriate ExternalError as well.
* @param amount uint256 The amount of USDC to withdraw.
* @param recipient address The account to transfer the withdrawn USDC to.
* @return True if the withdrawal succeeded, otherwise false.
*/
function _withdrawUSDCAtomic(
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.withdrawUSDC.selector);
// If amount = 0xfff...fff, withdraw the maximum amount possible.
bool maxWithdraw = (amount == uint256(-1));
uint256 redeemUnderlyingAmount;
if (maxWithdraw) {
redeemUnderlyingAmount = _CUSDC.balanceOfUnderlying(address(this));
} else {
redeemUnderlyingAmount = amount;
}
// Try to withdraw specified USDC amount from Compound before proceeding.
if (_withdrawFromCompound(AssetType.USDC, redeemUnderlyingAmount)) {
// Ensure that the USDC transfer does not fail.
if (maxWithdraw) {
require(_USDC.transfer(recipient, _USDC.balanceOf(address(this))));
} else {
require(_USDC.transfer(recipient, amount));
}
success = true;
}
}
function borrowUSDC(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.USDCBorrow,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set the self-call context so we can call _borrowUSDCAtomic.
_selfCallContext = this.borrowUSDC.selector;
// Make the atomic self-call - if borrow fails on cUSDC, it will succeed but
// nothing will happen except firing an ExternalError event. If the second
// part of the self-call (USDC transfer) fails, it will revert and roll back
// the first part of the call, and we'll fire an ExternalError event after
// returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._borrowUSDCAtomic.selector, amount, recipient
));
if (!ok) {
// Find out why USDC transfer reverted (doesn't give revert reasons).
_diagnoseAndEmitUSDCSpecificError(_USDC.transfer.selector);
} else {
// Ensure that ok == false in the event the borrow failed.
ok = abi.decode(returnData, (bool));
}
}
function _borrowUSDCAtomic(uint256 amount, address recipient) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.borrowUSDC.selector);
if (_borrowFromCompound(AssetType.USDC, amount)) {
// ensure that the USDC transfer does not fail.
require(_USDC.transfer(recipient, amount));
success = true;
}
}
function withdrawEther(
uint256 amount,
address payable recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.ETHWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set the self-call context so we can call _withdrawEtherAtomic.
_selfCallContext = this.withdrawEther.selector;
// Make the atomic self-call - if redeemUnderlying fails on cDAI, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (the Dai transfer) fails, it will revert
// and roll back the first part of the call, and we'll fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._withdrawEtherAtomic.selector, amount, recipient
));
if (!ok) {
emit ExternalError(address(this), "Ether transfer was unsuccessful.");
} else {
// Ensure that ok == false in the event the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
function _withdrawEtherAtomic(
uint256 amount,
address payable recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.withdrawEther.selector);
if (_withdrawFromCompound(AssetType.ETH, amount)) {
recipient.transfer(amount);
success = true;
}
}
/**
* @notice Allow a signatory to increment the nonce at any point. The current
* nonce needs to be provided as an argument to the a signature so as not to
* enable griefing attacks. All arguments can be omitted if called directly.
* No value is returned from this function - it will either succeed or revert.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param signature bytes A signature that resolves to either the public key
* set for this account in storage slot zero, `_userSigningKey`, or the public
* key returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function cancel(
uint256 minimumActionGas,
bytes calldata signature
) external {
// Ensure the caller or the supplied signature is valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.Cancel,
abi.encode(),
minimumActionGas,
signature,
signature
);
}
function executeAction(
address to,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData) {
// Ensure that the `to` address is a contract and is not this contract.
_ensureValidGenericCallTarget(to);
// Ensure caller and/or supplied signatures are valid and increment nonce.
(bytes32 actionID, uint256 nonce) = _validateActionAndIncrementNonce(
ActionType.Generic,
abi.encode(to, data),
minimumActionGas,
userSignature,
dharmaSignature
);
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this action. However, the call
// itself may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Perform the action via low-level call and set return values using result.
(ok, returnData) = to.call(data);
// Emit a CallSuccess or CallFailure event based on the outcome of the call.
if (ok) {
// Note: while the call succeeded, the action may still have "failed"
// (for example, successful calls to Compound can still return an error).
emit CallSuccess(actionID, false, nonce, to, data, returnData);
} else {
// Note: while the call failed, the nonce will still be incremented, which
// will invalidate all supplied signatures.
emit CallFailure(actionID, nonce, to, data, string(returnData));
}
}
/**
* @notice Allow signatory to set a new user signing key. The current nonce
* needs to be provided as an argument to the a signature so as not to enable
* griefing attacks. No value is returned from this function - it will either
* succeed or revert.
* @param userSigningKey address The new user signing key to set on this smart
* wallet.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function setUserSigningKey(
address userSigningKey,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.SetUserSigningKey,
abi.encode(userSigningKey),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set new user signing key on smart wallet and emit a corresponding event.
_setUserSigningKey(userSigningKey);
}
// Allow the account recovery manager to change the user signing key.
function recover(address newUserSigningKey) external {
require(
msg.sender == _ACCOUNT_RECOVERY_MANAGER,
"Only the account recovery manager may call this function."
);
// Set up the user's new dharma key and emit a corresponding event.
_setUserSigningKey(newUserSigningKey);
}
/**
* @notice Retrieve the Dai, USDC, and ETH balances held by the smart wallet,
* both directly and in Compound. This is not a view function since Compound
* will calculate accrued interest as part of the underlying balance checks,
* but can still be called from an off-chain source as though it were a view
* function.
* @return The Dai balance, the USDC balance, the ETH balance, the underlying
* Dai balance of the cDAI balance, the underlying USDC balance of the cUSDC
* balance, and the underlying ETH balance of the cEther balance.
*/
function getBalances() external returns (
uint256 daiBalance,
uint256 usdcBalance,
uint256 etherBalance,
uint256 cDaiUnderlyingDaiBalance,
uint256 cUsdcUnderlyingUsdcBalance,
uint256 cEtherUnderlyingEtherBalance
) {
daiBalance = _DAI.balanceOf(address(this));
usdcBalance = _USDC.balanceOf(address(this));
etherBalance = address(this).balance;
cDaiUnderlyingDaiBalance = _CDAI.balanceOfUnderlying(address(this));
cUsdcUnderlyingUsdcBalance = _CUSDC.balanceOfUnderlying(address(this));
cEtherUnderlyingEtherBalance = _CETH.balanceOfUnderlying(address(this));
}
/**
* @notice View function for getting the current user signing key for the
* smart wallet.
* @return The current user signing key.
*/
function getUserSigningKey() external view returns (address userSigningKey) {
userSigningKey = _userSigningKey;
}
/**
* @notice View function for getting the current nonce of the smart wallet.
* This nonce is incremented whenever an action is taken that requires a
* signature and/or a specific caller.
* @return The current nonce.
*/
function getNonce() external view returns (uint256 nonce) {
nonce = _nonce;
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by the key designated by the Dharma Key
* Registry in order to construct a valid signature for the corresponding
* action. The current nonce will be used, which means that it will only be
* valid for the next action taken.
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V4 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (4), USDCWithdrawal (5),
* ETHWithdrawal (6), DAIBorrow (7), and USDCBorrow (8).
* @param amount uint256 The amount to withdraw for Withdrawal actions, or 0
* for other action types.
* @param recipient address The account to transfer withdrawn funds to, the
* new user signing key, or the null address for cancelling.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getNextCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
action,
abi.encode(amount, recipient),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by the key designated by the Dharma Key
* Registry in order to construct a valid signature for the corresponding
* action. Any nonce value may be supplied, which enables constructing valid
* message hashes for multiple future actions ahead of time.
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V4 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (4), USDCWithdrawal (5),
* ETHWithdrawal (6), DAIBorrow (7), and USDCBorrow (8).
* @param amount uint256 The amount to withdraw for Withdrawal actions, or 0
* for other action types.
* @param recipient address The account to transfer withdrawn funds to, the
* new user signing key, or the null address for cancelling.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
action,
abi.encode(amount, recipient),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
function getNextGenericActionID(
address to,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.Generic,
abi.encode(to, data),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
function getGenericActionID(
address to,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.Generic,
abi.encode(to, data),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice Pure function for getting the current Dharma Smart Wallet version.
* @return The current Dharma Smart Wallet version.
*/
function getVersion() external pure returns (uint256 version) {
version = _DHARMA_SMART_WALLET_VERSION;
}
// Note: this must currently be implemented as a public function (instead of
// as an external one) due to an ABIEncoderV2 `UnimplementedFeatureError`.
// Also note that the returned `ok` boolean only signifies that a call was
// successfully completed during execution - the call will be rolled back
// unless EVERY call succeeded and therefore the whole `ok` array is true.
function executeActionWithAtomicBatchCalls(
Call[] memory calls,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) public returns (bool[] memory ok, bytes[] memory returnData) {
// Ensure that each `to` address is a contract and is not this contract.
for (uint256 i = 0; i < calls.length; i++) {
_ensureValidGenericCallTarget(calls[i].to);
}
// Ensure caller and/or supplied signatures are valid and increment nonce.
(bytes32 actionID, uint256 nonce) = _validateActionAndIncrementNonce(
ActionType.GenericAtomicBatch,
abi.encode(calls),
minimumActionGas,
userSignature,
dharmaSignature
);
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this contract. However, one of the
// calls may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Specify length of returned values in order to work with them in memory.
ok = new bool[](calls.length);
returnData = new bytes[](calls.length);
// Set self-call context to call _executeActionWithAtomicBatchCallsAtomic.
_selfCallContext = this.executeActionWithAtomicBatchCalls.selector;
// Make the atomic self-call - if any call fails, calls that preceded it
// will be rolled back and calls that follow it will not be made.
(bool externalOk, bytes memory rawCallResults) = address(this).call(
abi.encodeWithSelector(
this._executeActionWithAtomicBatchCallsAtomic.selector, calls
)
);
// Parse data returned from self-call into each call result and store / log.
CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[]));
for (uint256 i = 0; i < callResults.length; i++) {
Call memory currentCall = calls[i];
// Set the status and the return data / revert reason from the call.
ok[i] = callResults[i].ok;
returnData[i] = callResults[i].returnData;
// Emit CallSuccess or CallFailure event based on the outcome of the call.
if (callResults[i].ok) {
// Note: while the call succeeded, the action may still have "failed"
// (i.e. a successful calls to Compound can still return an error).
emit CallSuccess(
actionID,
!externalOk, // if another call failed this will have been rolled back
nonce,
currentCall.to,
currentCall.data,
callResults[i].returnData
);
} else {
// Note: while the call failed, the nonce will still be incremented,
// which will invalidate all supplied signatures.
emit CallFailure(
actionID,
nonce,
currentCall.to,
currentCall.data,
string(callResults[i].returnData)
);
// exit early - any calls after the first failed call will not execute.
break;
}
}
}
// Note: this must currently be implemented as a public function (instead of
// as an external one) due to an ABIEncoderV2 `UnimplementedFeatureError`
function _executeActionWithAtomicBatchCallsAtomic(
Call[] memory calls
) public returns (CallReturn[] memory callResults) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.executeActionWithAtomicBatchCalls.selector);
bool rollBack = false;
callResults = new CallReturn[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
// Perform low-level call and set return values using result.
(bool ok, bytes memory returnData) = calls[i].to.call(calls[i].data);
callResults[i] = CallReturn({ok: ok, returnData: returnData});
if (!ok) {
// exit early - any calls after the first failed call will not execute.
rollBack = true;
break;
}
}
if (rollBack) {
// wrap in length encoding and revert (provide data instead of a string)
bytes memory callResultsBytes = abi.encode(callResults);
assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) }
}
}
// cannot be implemented as an external function: `UnimplementedFeatureError`
function getNextGenericAtomicBatchActionID(
Call[] memory calls,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.GenericAtomicBatch,
abi.encode(calls),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
// cannot be implemented as an external function: `UnimplementedFeatureError`
function getGenericAtomicBatchActionID(
Call[] memory calls,
uint256 nonce,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.GenericAtomicBatch,
abi.encode(calls),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice Internal function for setting a new user signing key. A
* NewUserSigningKey event will also be emitted.
* @param userSigningKey address The new user signing key to set on this smart
* wallet.
*/
function _setUserSigningKey(address userSigningKey) internal {
// Ensure that a user signing key is set on this smart wallet.
require(userSigningKey != address(0), "No user signing key provided.");
_userSigningKey = userSigningKey;
emit NewUserSigningKey(userSigningKey);
}
/**
* @notice Internal function for incrementing the nonce.
*/
function _incrementNonce() internal {
_nonce++;
}
/**
* @notice Internal function for setting the allowance of a given ERC20 asset
* to the maximum value. This enables the corresponding cToken for the asset
* to pull in tokens in order to make deposits.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @return True if the approval succeeded, otherwise false.
*/
function _setFullApproval(AssetType asset) internal returns (bool ok) {
// Get asset's underlying token address and corresponding cToken address.
address token;
address cToken;
if (asset == AssetType.DAI) {
token = address(_DAI);
cToken = address(_CDAI);
} else {
token = address(_USDC);
cToken = address(_CUSDC);
}
// Approve cToken contract to transfer underlying on behalf of this wallet.
(ok, ) = token.call(abi.encodeWithSelector(
// Note: since both cTokens have the same interface, just use cDAI's.
_DAI.approve.selector, cToken, uint256(-1)
));
// Emit a corresponding event if the approval failed.
if (!ok) {
if (asset == AssetType.DAI) {
emit ExternalError(address(_DAI), "DAI contract reverted on approval.");
} else {
// Find out why USDC transfer reverted (it doesn't give revert reasons).
_diagnoseAndEmitUSDCSpecificError(_USDC.approve.selector);
}
}
}
/**
* @notice Internal function for depositing a given ERC20 asset and balance on
* the corresponding cToken. No value is returned, as no additional steps need
* to be conditionally performed after the deposit.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @param balance uint256 The amount of the asset to deposit. Note that an
* attempt to deposit "dust" (i.e. very small amounts) may result in 0 cTokens
* being minted, or in fewer cTokens being minted than is implied by the
* current exchange rate (due to lack of sufficient precision on the tokens).
*/
function _depositOnCompound(AssetType asset, uint256 balance) internal {
// Get cToken address for the asset type.
address cToken = asset == AssetType.DAI ? address(_CDAI) : address(_CUSDC);
// Attempt to mint the balance on the cToken contract.
(bool ok, bytes memory data) = cToken.call(abi.encodeWithSelector(
// Note: since both cTokens have the same interface, just use cDAI's.
_CDAI.mint.selector, balance
));
// Log an external error if something went wrong with the attempt.
_checkCompoundInteractionAndLogAnyErrors(
asset, _CDAI.mint.selector, ok, data
);
}
/**
* @notice Internal function for withdrawing a given underlying asset balance
* from the corresponding cToken. Note that the requested balance may not be
* currently available on Compound, which will cause the withdrawal to fail.
* @param asset uint256 The asset's ID, either Dai (0), USDC (1), or ETH (2).
* @param balance uint256 The amount of the asset to withdraw, denominated in
* the underlying token. Note that an attempt to withdraw "dust" (i.e. very
* small amounts) may result in 0 underlying tokens being redeemed, or in
* fewer tokens being redeemed than is implied by the current exchange rate
* (due to lack of sufficient precision on the tokens).
* @return True if the withdrawal succeeded, otherwise false.
*/
function _withdrawFromCompound(
AssetType asset,
uint256 balance
) internal returns (bool success) {
// Get cToken address for the asset type.
address cToken;
if (asset == AssetType.DAI) {
cToken = address(_CDAI);
} else { // Note: `else if` breaks code coverage.
if (asset == AssetType.USDC) {
cToken = address(_CUSDC);
} else {
cToken = address(_CETH);
}
}
// Attempt to redeem the underlying balance from the cToken contract.
(bool ok, bytes memory data) = cToken.call(abi.encodeWithSelector(
// Note: function selector is the same for each cToken so just use cDAI's.
_CDAI.redeemUnderlying.selector, balance
));
// Log an external error if something went wrong with the attempt.
success = _checkCompoundInteractionAndLogAnyErrors(
asset, _CDAI.redeemUnderlying.selector, ok, data
);
}
function _repayOnCompound(
AssetType asset,
uint256 balance
) internal returns (uint256 remainingBalance) {
// Get cToken address for the asset type. (ETH borrowing is not supported.)
address cToken = asset == AssetType.DAI ? address(_CDAI) : address(_CUSDC);
// TODO: handle errors originating from this call (reverts on MathError).
uint256 borrowBalance = CTokenInterface(cToken).borrowBalanceCurrent(
address(this)
);
// Skip repayment if there is no borrow balance.
if (borrowBalance == 0) {
return balance;
}
uint256 borrowBalanceToRepay;
if (borrowBalance > balance) {
borrowBalanceToRepay = balance;
} else {
borrowBalanceToRepay = borrowBalance;
}
// Note: SafeMath not needed since balance >= borrowBalanceToRepay
remainingBalance = balance - borrowBalanceToRepay;
// Attempt to repay the balance on the cToken contract.
(bool ok, bytes memory data) = cToken.call(abi.encodeWithSelector(
// Note: since both cTokens have the same interface, just use cDAI's.
_CDAI.repayBorrow.selector, borrowBalanceToRepay
));
// Log an external error if something went wrong with the attempt.
bool success = _checkCompoundInteractionAndLogAnyErrors(
asset, _CDAI.repayBorrow.selector, ok, data
);
// Reset remaining balance to initial balance if repay was not successful.
if (!success) {
remainingBalance = balance;
}
}
function _borrowFromCompound(
AssetType asset,
uint256 underlyingToBorrow
) internal returns (bool success) {
// Get cToken address for the asset type. (ETH borrowing is not supported.)
address cToken = asset == AssetType.DAI ? address(_CDAI) : address(_CUSDC);
// Attempt to borrow the underlying amount from the cToken contract.
(bool ok, bytes memory data) = cToken.call(abi.encodeWithSelector(
// Note: since both cTokens have the same interface, just use cDAI's.
_CDAI.borrow.selector, underlyingToBorrow
));
// Log an external error if something went wrong with the attempt.
success = _checkCompoundInteractionAndLogAnyErrors(
asset, _CDAI.borrow.selector, ok, data
);
}
function _depositEtherOnCompound() internal {
uint256 balance = address(this).balance;
if (balance > 0) {
// Attempt to mint the full ETH balance on the cEther contract.
(bool ok, bytes memory data) = address(_CETH).call.value(balance)(
abi.encodeWithSelector(_CETH.mint.selector)
);
// Log an external error if something went wrong with the attempt.
_checkCompoundInteractionAndLogAnyErrors(
AssetType.ETH, _CETH.mint.selector, ok, data
);
}
}
/**
* @notice Internal function for validating supplied gas (if specified),
* retrieving the signer's public key from the Dharma Key Registry, deriving
* the action ID, validating the provided caller and/or signatures using that
* action ID, and incrementing the nonce. This function serves as the
* entrypoint for all protected "actions" on the smart wallet, and is the only
* area where these functions should revert (other than due to out-of-gas
* errors, which can be guarded against by supplying a minimum action gas
* requirement).
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V4 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (4), USDCWithdrawal (5),
* ETHWithdrawal (6), DAIBorrow (7), and USDCBorrow (8).
* @param arguments bytes ABI-encoded arguments for the action.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return The nonce of the current action (prior to incrementing it).
*/
function _validateActionAndIncrementNonce(
ActionType action,
bytes memory arguments,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) internal returns (bytes32 actionID, uint256 actionNonce) {
// Ensure that the current gas exceeds the minimum required action gas.
// This prevents griefing attacks where an attacker can invalidate a
// signature without providing enough gas for the action to succeed. Also
// note that some gas will be spent before this check is reached - supplying
// ~30,000 additional gas should suffice when submitting transactions. To
// skip this requirement, supply zero for the minimumActionGas argument.
if (minimumActionGas != 0) {
require(
gasleft() >= minimumActionGas,
"Invalid action - insufficient gas supplied by transaction submitter."
);
}
// Get the current nonce for the action to be performed.
actionNonce = _nonce;
// Get the user signing key that will be used to verify their signature.
address userSigningKey = _userSigningKey;
// Get the Dharma signing key that will be used to verify their signature.
address dharmaSigningKey = _getDharmaSigningKey();
// Determine the actionID - this serves as the signature hash.
actionID = _getActionID(
action,
arguments,
actionNonce,
minimumActionGas,
userSigningKey,
dharmaSigningKey
);
// Compute the message hash - the hashed, EIP-191-0x45-prefixed action ID.
bytes32 messageHash = actionID.toEthSignedMessageHash();
// Actions other than Cancel require both signatures; Cancel only needs one.
if (action != ActionType.Cancel) {
// Validate user signing key signature unless it is `msg.sender`.
if (msg.sender != userSigningKey) {
require(
_validateUserSignature(
messageHash, action, arguments, userSigningKey, userSignature
),
"Invalid action - invalid user signature."
);
}
// Validate Dharma signing key signature unless it is `msg.sender`.
if (msg.sender != dharmaSigningKey) {
require(
dharmaSigningKey == messageHash.recover(dharmaSignature),
"Invalid action - invalid Dharma signature."
);
}
} else {
// Validate signing key signature unless user or Dharma is `msg.sender`.
if (msg.sender != userSigningKey && msg.sender != dharmaSigningKey) {
require(
dharmaSigningKey == messageHash.recover(dharmaSignature) ||
_validateUserSignature(
messageHash, action, arguments, userSigningKey, userSignature
),
"Invalid action - invalid signature."
);
}
}
// Increment nonce in order to prevent reuse of signatures after the call.
_incrementNonce();
}
/**
* @notice Internal function for entering cDAI, cUSDC, and cETH markets. This
* is performed now so that V0 smart wallets will not need to be reinitialized
* in order to support using these assets as collateral when borrowing funds.
*/
function _enterMarkets() internal {
// Create input array with each cToken address on which to enter a market.
address[] memory marketsToEnter = new address[](3);
marketsToEnter[0] = address(_CDAI);
marketsToEnter[1] = address(_CUSDC);
marketsToEnter[2] = address(_CETH);
// Attempt to enter each market by calling into the Comptroller contract.
(bool ok, bytes memory data) = address(_COMPTROLLER).call(
abi.encodeWithSelector(_COMPTROLLER.enterMarkets.selector, marketsToEnter)
);
// Log an external error if something went wrong with the attempt.
if (ok) {
uint256[] memory compoundErrors = abi.decode(data, (uint256[]));
for (uint256 i = 0; i < compoundErrors.length; i++) {
uint256 compoundError = compoundErrors[i];
if (compoundError != _COMPOUND_SUCCESS) {
emit ExternalError(
address(_COMPTROLLER),
string(
abi.encodePacked(
"Compound Comptroller contract returned error code ",
uint8((compoundError / 10) + 48),
uint8((compoundError % 10) + 48),
" while attempting to call enterMarkets."
)
)
);
}
}
} else {
// Decode the revert reason in the event one was returned.
string memory revertReason = _decodeRevertReason(data);
emit ExternalError(
address(_COMPTROLLER),
string(
abi.encodePacked(
"Compound Comptroller contract reverted on enterMarkets: ",
revertReason
)
)
);
}
}
/**
* @notice Internal function to determine whether a call to a given cToken
* succeeded, and to emit a relevant ExternalError event if it failed. The
* failure can be caused by a call that reverts, or by a call that does not
* revert but returns a non-zero error code.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @param functionSelector bytes4 The function selector that was called on the
* corresponding cToken of the asset type.
* @param ok bool A boolean representing whether the call returned or
* reverted.
* @param data bytes The data provided by the returned or reverted call.
* @return True if the interaction was successful, otherwise false. This will
* be used to determine if subsequent steps in the action should be attempted
* or not, specifically a transfer following a withdrawal.
*/
function _checkCompoundInteractionAndLogAnyErrors(
AssetType asset,
bytes4 functionSelector,
bool ok,
bytes memory data
) internal returns (bool success) {
// Log an external error if something went wrong with the attempt.
if (ok) {
uint256 compoundError = abi.decode(data, (uint256));
if (compoundError != _COMPOUND_SUCCESS) {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_getCTokenDetails(asset, functionSelector)
);
emit ExternalError(
account,
string(
abi.encodePacked(
"Compound ",
name,
" contract returned error code ",
uint8((compoundError / 10) + 48),
uint8((compoundError % 10) + 48),
" while attempting to call ",
functionName,
"."
)
)
);
} else {
success = true;
}
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_getCTokenDetails(asset, functionSelector)
);
// Decode the revert reason in the event one was returned.
string memory revertReason = _decodeRevertReason(data);
emit ExternalError(
account,
string(
abi.encodePacked(
"Compound ",
name,
" contract reverted while attempting to call ",
functionName,
": ",
revertReason
)
)
);
}
}
/**
* @notice Internal function to diagnose the reason that a withdrawal attempt
* failed and to emit a corresponding ExternalError event. Errors related to
* the call to `redeemUnderlying` on the cToken are handled by
* `_checkCompoundInteractionAndLogAnyErrors` - if the error did not originate
* from that call, it could be caused by a call to `balanceOfUnderlying` (i.e.
* when attempting a maximum withdrawal) or by the call to `transfer` on the
* underlying token after the withdrawal has been completed.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
*/
function _diagnoseAndEmitErrorRelatedToWithdrawal(AssetType asset) internal {
// Get called contract address and name of contract (no need for selector).
(address cToken, string memory name, ) = _getCTokenDetails(
asset, bytes4(0)
);
// Revert could be caused by cToken MathError or underlying transfer error.
(bool check, ) = cToken.call(abi.encodeWithSelector(
// Note: since both cTokens have the same interface, just use cDAI's.
_CDAI.balanceOfUnderlying.selector, address(this)
));
if (!check) {
emit ExternalError(
cToken,
string(
abi.encodePacked(
name, " contract reverted on call to balanceOfUnderlying."
)
)
);
} else {
if (asset == AssetType.DAI) {
emit ExternalError(address(_DAI), "DAI contract reverted on transfer.");
} else { // Note: `else if` breaks code coverage.
if (asset == AssetType.ETH) {
// Note: this should log the address of the recipient.
emit ExternalError(address(this), "ETH transfer reverted.");
} else {
// Find out why USDC transfer reverted (doesn't give revert reasons).
_diagnoseAndEmitUSDCSpecificError(_USDC.transfer.selector);
}
}
}
}
/**
* @notice Internal function to diagnose the reason that a call to the USDC
* contract failed and to emit a corresponding ExternalError event. USDC can
* blacklist accounts and pause the contract, which can both cause a transfer
* or approval to fail.
* @param functionSelector bytes4 The function selector that was called on the
* USDC contract.
*/
function _diagnoseAndEmitUSDCSpecificError(bytes4 functionSelector) internal {
// Determine the name of the function that was called on USDC.
string memory functionName;
if (functionSelector == _USDC.transfer.selector) {
functionName = "transfer";
} else {
functionName = "approve";
}
// Find out why USDC transfer reverted (it doesn't give revert reasons).
if (_USDC_NAUGHTY.isBlacklisted(address(this))) {
emit ExternalError(
address(_USDC),
string(
abi.encodePacked(
functionName, " failed - USDC has blacklisted this user."
)
)
);
} else { // Note: `else if` breaks coverage.
if (_USDC_NAUGHTY.paused()) {
emit ExternalError(
address(_USDC),
string(
abi.encodePacked(
functionName, " failed - USDC contract is currently paused."
)
)
);
} else {
emit ExternalError(
address(_USDC),
string(
abi.encodePacked(
"USDC contract reverted on ", functionName, "."
)
)
);
}
}
}
/**
* @notice Internal function to ensure that protected functions can only be
* called from this contract and that they have the appropriate context set.
* The self-call context is then cleared. It is used as an additional guard
* against reentrancy, especially once generic actions are supported by the
* smart wallet in future versions.
* @param selfCallContext bytes4 The expected self-call context, equal to the
* function selector of the approved calling function.
*/
function _enforceSelfCallFrom(bytes4 selfCallContext) internal {
// Ensure caller is this contract and self-call context is correctly set.
require(
msg.sender == address(this) &&
_selfCallContext == selfCallContext,
"External accounts or unapproved internal functions cannot call this."
);
// Clear the self-call context.
delete _selfCallContext;
}
/**
* @notice Internal view function for validating a user's signature. If the
* user's signing key does not have contract code, it will be validated via
* ecrecover; otherwise, it will be validated using ERC-1271, passing the
* message hash that was signed, the action type, and the arguments as data.
* @param messageHash bytes32 The message hash that is signed by the user. It
* is derived by prefixing (according to EIP-191 0x45) and hashing an actionID
* returned from `getCustomActionID`.
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V4 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (4), USDCWithdrawal (5),
* ETHWithdrawal (6), DAIBorrow (7), and USDCBorrow (8).
* @param arguments bytes ABI-encoded arguments for the action.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used.
* @return A boolean representing the validity of the supplied user signature.
*/
function _validateUserSignature(
bytes32 messageHash,
ActionType action,
bytes memory arguments,
address userSigningKey,
bytes memory userSignature
) internal view returns (bool valid) {
if (!userSigningKey.isContract()) {
valid = userSigningKey == messageHash.recover(userSignature);
} else {
bytes memory data = abi.encode(messageHash, action, arguments);
valid = (
ERC1271(userSigningKey).isValidSignature(
data, userSignature
) == _ERC_1271_MAGIC_VALUE
);
}
}
/**
* @notice Internal view function to get the Dharma signing key for the smart
* wallet from the Dharma Key Registry. This key can be set for each specific
* smart wallet - if none has been set, a global fallback key will be used.
* @return The address of the Dharma signing key, or public key corresponding
* to the secondary signer.
*/
function _getDharmaSigningKey() internal view returns (
address dharmaSigningKey
) {
dharmaSigningKey = _DHARMA_KEY_REGISTRY.getKey();
}
/**
* @notice Internal view function that, given an action type and arguments,
* will return the action ID or message hash that will need to be prefixed
* (according to EIP-191 0x45), hashed, and signed by the key designated by
* the Dharma Key Registry in order to construct a valid signature for the
* corresponding action. The current nonce will be supplied to this function
* when reconstructing an action ID during protected function execution based
* on the supplied parameters.
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V4 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (4), USDCWithdrawal (5),
* ETHWithdrawal (6), DAIBorrow (7), and USDCBorrow (8).
* @param arguments bytes ABI-encoded arguments for the action.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param dharmaSigningKey address The address of the secondary key, or public
* key corresponding to the secondary signer.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function _getActionID(
ActionType action,
bytes memory arguments,
uint256 nonce,
uint256 minimumActionGas,
address userSigningKey,
address dharmaSigningKey
) internal view returns (bytes32 actionID) {
// The actionID is constructed according to EIP-191-0x45 to prevent replays.
actionID = keccak256(
abi.encodePacked(
address(this),
_DHARMA_SMART_WALLET_VERSION,
userSigningKey,
dharmaSigningKey,
nonce,
minimumActionGas,
action,
arguments
)
);
}
/**
* @notice Internal pure function to get the cToken address, it's name, and
* the name of the called function, based on a supplied asset type and
* function selector. It is used to help construct ExternalError events.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @param functionSelector bytes4 The function selector that was called on the
* corresponding cToken of the asset type.
* @return The cToken address, it's name, and the name of the called function.
*/
function _getCTokenDetails(
AssetType asset,
bytes4 functionSelector
) internal pure returns (
address account,
string memory name,
string memory functionName
) {
if (asset == AssetType.DAI) {
account = address(_CDAI);
name = "cDAI";
} else { // Note: `else if` breaks code coverage.
if (asset == AssetType.USDC) {
account = address(_CUSDC);
name = "cUSDC";
} else {
account = address(_CETH);
name = "cEther";
}
}
// Note: since both cTokens have the same interface, just use cDAI's.
if (functionSelector == _CDAI.mint.selector) {
functionName = "mint";
} else { // Note: `else if` breaks code coverage.
if (functionSelector == _CDAI.redeemUnderlying.selector) {
functionName = "redeemUnderlying";
} else {
if (functionSelector == _CDAI.borrow.selector) {
functionName = "borrow";
} else {
functionName = "repayBorrow";
}
}
}
}
/**
* @notice Internal pure function to ensure that a given `to` address provided
* as part of a generic action is valid. Calls cannot be performed to accounts
* without code or back into the smart wallet itself.
*/
function _ensureValidGenericCallTarget(address to) internal view {
require(
to.isContract(),
"Invalid `to` parameter - must supply a contract address containing code."
);
require(
to != address(this),
"Invalid `to` parameter - cannot supply the address of this contract."
);
}
/**
* @notice Internal pure function to decode revert reasons. The revert reason
* prefix is removed and the remaining string argument is decoded.
* @param revertData bytes The raw data supplied alongside the revert.
* @return The decoded revert reason string.
*/
function _decodeRevertReason(
bytes memory revertData
) internal pure returns (string memory revertReason) {
// Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector
if (
revertData.length > 68 && // prefix (4) + position (32) + length (32)
revertData[0] == byte(0x08) &&
revertData[1] == byte(0xc3) &&
revertData[2] == byte(0x79) &&
revertData[3] == byte(0xa0)
) {
// Get the revert reason without the prefix from the revert data.
bytes memory revertReasonBytes = new bytes(revertData.length - 4);
for (uint256 i = 4; i < revertData.length; i++) {
revertReasonBytes[i - 4] = revertData[i];
}
// Decode the resultant revert reason as a string.
revertReason = abi.decode(revertReasonBytes, (string));
} else {
// Simply return the default, with no revert reason.
revertReason = "(no revert reason)";
}
}
} | Protected function that can only be called from `withdrawUSDC` on this contract. It will attempt to withdraw the supplied amount of USDC, or the maximum amount if specified using `uint256(-1)`, to the supplied recipient address by redeeming the underlying USDC from the cUSDC contract and transferring it to the recipient. An ExternalError will be emitted and the transfer will be skipped if the call to `redeemUnderlying` fails, and any revert will be caught by `withdrawUSDC` and diagnosed in order to emit an appropriate ExternalError as well. amount uint256 The amount of USDC to withdraw. recipient address The account to transfer the withdrawn USDC to. return True if the withdrawal succeeded, otherwise false./ Ensure caller is this contract and self-call context is correctly set. If amount = 0xfff...fff, withdraw the maximum amount possible. Try to withdraw specified USDC amount from Compound before proceeding. Ensure that the USDC transfer does not fail. | function _withdrawUSDCAtomic(
uint256 amount,
address recipient
) external returns (bool success) {
_enforceSelfCallFrom(this.withdrawUSDC.selector);
bool maxWithdraw = (amount == uint256(-1));
uint256 redeemUnderlyingAmount;
if (maxWithdraw) {
redeemUnderlyingAmount = _CUSDC.balanceOfUnderlying(address(this));
redeemUnderlyingAmount = amount;
}
if (_withdrawFromCompound(AssetType.USDC, redeemUnderlyingAmount)) {
if (maxWithdraw) {
require(_USDC.transfer(recipient, _USDC.balanceOf(address(this))));
require(_USDC.transfer(recipient, amount));
}
success = true;
}
}
| 12,781,678 |
/**
*Submitted for verification at Etherscan.io on 2020-09-18
*/
/**
*Submitted for verification at Etherscan.io on 2020-09-18
*/
// File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/token/ERC20/IERC20.sol
pragma solidity 0.5.7;
/**
* @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: nexusmutual-contracts/contracts/external/openzeppelin-solidity/math/SafeMath.sol
pragma solidity 0.5.7;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, 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 numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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;
}
/**
* @dev Subtracts two numbers, 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 numbers, 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 numbers 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: nexusmutual-contracts/contracts/NXMToken.sol
/* Copyright (C) 2017 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract NXMToken is IERC20 {
using SafeMath for uint256;
event WhiteListed(address indexed member);
event BlackListed(address indexed member);
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
mapping (address => bool) public whiteListed;
mapping(address => uint) public isLockedForMV;
uint256 private _totalSupply;
string public name = "NXM";
string public symbol = "NXM";
uint8 public decimals = 18;
address public operator;
modifier canTransfer(address _to) {
require(whiteListed[_to]);
_;
}
modifier onlyOperator() {
if (operator != address(0))
require(msg.sender == operator);
_;
}
constructor(address _founderAddress, uint _initialSupply) public {
_mint(_founderAddress, _initialSupply);
}
/**
* @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 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 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
* @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
* @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 Adds a user to whitelist
* @param _member address to add to whitelist
*/
function addToWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = true;
emit WhiteListed(_member);
return true;
}
/**
* @dev removes a user from whitelist
* @param _member address to remove from whitelist
*/
function removeFromWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = false;
emit BlackListed(_member);
return true;
}
/**
* @dev change operator address
* @param _newOperator address of new operator
*/
function changeOperator(address _newOperator) public onlyOperator returns (bool) {
operator = _newOperator;
return true;
}
/**
* @dev burns an amount of the tokens of the message sender
* account.
* @param amount The amount that will be burnt.
*/
function burn(uint256 amount) public returns (bool) {
_burn(msg.sender, amount);
return true;
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public returns (bool) {
_burnFrom(from, value);
return true;
}
/**
* @dev function that mints an amount of the token and assigns it to
* an account.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function mint(address account, uint256 amount) public onlyOperator {
_mint(account, amount);
}
/**
* @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 canTransfer(to) returns (bool) {
require(isLockedForMV[msg.sender] < now); // if not voted under governance
require(value <= _balances[msg.sender]);
_transfer(to, value);
return true;
}
/**
* @dev Transfer tokens to the operator from the specified address
* @param from The address to transfer from.
* @param value The amount to be transferred.
*/
function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) {
require(value <= _balances[from]);
_transferFrom(from, operator, value);
return true;
}
/**
* @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
canTransfer(to)
returns (bool)
{
require(isLockedForMV[from] < now); // if not voted under governance
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
_transferFrom(from, to, value);
return true;
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyOperator {
if (_days.add(now) > isLockedForMV[_of])
isLockedForMV[_of] = _days.add(now);
}
/**
* @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) internal {
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
}
/**
* @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
)
internal
{
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(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 amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @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.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IProposalCategory.sol
/* Copyright (C) 2017 GovBlocks.io
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/ */
pragma solidity 0.5.7;
contract IProposalCategory {
event Category(
uint indexed categoryId,
string categoryName,
string actionHash
);
/// @dev Adds new category
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
)
external;
/// @dev gets category details
function category(uint _categoryId)
external
view
returns(
uint categoryId,
uint memberRoleToVote,
uint majorityVotePerc,
uint quorumPerc,
uint[] memory allowedToCreateProposal,
uint closingTime,
uint minStake
);
///@dev gets category action details
function categoryAction(uint _categoryId)
external
view
returns(
uint categoryId,
address contractAddress,
bytes2 contractName,
uint defaultIncentive
);
/// @dev Gets Total number of categories added till now
function totalCategories() external view returns(uint numberOfCategories);
/// @dev Updates category details
/// @param _categoryId Category id that needs to be updated
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
public;
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/Governed.sol
/* Copyright (C) 2017 GovBlocks.io
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/ */
pragma solidity 0.5.7;
contract IMaster {
function getLatestAddress(bytes2 _module) public view returns(address);
}
contract Governed {
address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract
/// @dev modifier that allows only the authorized addresses to execute the function
modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
/// @dev checks if an address is authorized to govern
function isAuthorizedToGovern(address _toCheck) public view returns(bool) {
IMaster ms = IMaster(masterAddress);
return (ms.getLatestAddress("GV") == _toCheck);
}
}
// File: nexusmutual-contracts/contracts/INXMMaster.sol
/* Copyright (C) 2017 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract INXMMaster {
address public tokenAddress;
address public owner;
uint public pauseTime;
function delegateCallBack(bytes32 myid) external;
function masterInitialized() public view returns(bool);
function isInternal(address _add) public view returns(bool);
function isPause() public view returns(bool check);
function isOwner(address _add) public view returns(bool);
function isMember(address _add) public view returns(bool);
function checkIsAuthToGoverned(address _add) public view returns(bool);
function updatePauseTime(uint _time) public;
function dAppLocker() public view returns(address _add);
function dAppToken() public view returns(address _add);
function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress);
}
// File: nexusmutual-contracts/contracts/Iupgradable.sol
pragma solidity 0.5.7;
contract Iupgradable {
INXMMaster public ms;
address public nxMasterAddress;
modifier onlyInternal {
require(ms.isInternal(msg.sender));
_;
}
modifier isMemberAndcheckPause {
require(ms.isPause() == false && ms.isMember(msg.sender) == true);
_;
}
modifier onlyOwner {
require(ms.isOwner(msg.sender));
_;
}
modifier checkPause {
require(ms.isPause() == false);
_;
}
modifier isMember {
require(ms.isMember(msg.sender), "Not member");
_;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public;
/**
* @dev change master address
* @param _masterAddress is the new address
*/
function changeMasterAddress(address _masterAddress) public {
if (address(ms) != address(0)) {
require(address(ms) == msg.sender, "Not master");
}
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
}
// File: nexusmutual-contracts/contracts/interfaces/IPooledStaking.sol
pragma solidity ^0.5.7;
interface IPooledStaking {
function accumulateReward(address contractAddress, uint amount) external;
function pushBurn(address contractAddress, uint amount) external;
function hasPendingActions() external view returns (bool);
function contractStake(address contractAddress) external view returns (uint);
function stakerReward(address staker) external view returns (uint);
function stakerDeposit(address staker) external view returns (uint);
function stakerContractStake(address staker, address contractAddress) external view returns (uint);
function withdraw(uint amount) external;
function stakerMaxWithdrawable(address stakerAddress) external view returns (uint);
function withdrawReward(address stakerAddress) external;
}
// File: nexusmutual-contracts/contracts/TokenFunctions.sol
/* Copyright (C) 2020 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract TokenFunctions is Iupgradable {
using SafeMath for uint;
MCR internal m1;
MemberRoles internal mr;
NXMToken public tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
PoolData internal pd;
IPooledStaking pooledStaking;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev Rewards stakers on purchase of cover on smart contract.
* @param _contractAddress smart contract address.
* @param _coverPriceNXM cover price in NXM.
*/
function pushStakerRewards(address _contractAddress, uint _coverPriceNXM) external onlyInternal {
uint rewardValue = _coverPriceNXM.mul(td.stakerCommissionPer()).div(100);
pooledStaking.accumulateReward(_contractAddress, rewardValue);
}
/**
* @dev Deprecated in favor of burnStakedTokens
*/
function burnStakerLockedToken(uint, bytes4, uint) external {
// noop
}
/**
* @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed.
* @param coverId cover id
* @param coverCurrency cover currency
* @param sumAssured amount of $curr to burn
*/
function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal {
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = m1.calculateTokenPrice(coverCurrency);
uint burnNXMAmount = sumAssured.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnNXMAmount);
}
/**
* @dev Gets the total staked NXM tokens against
* Smart contract by all stakers
* @param _stakedContractAddress smart contract address.
* @return amount total staked NXM tokens.
*/
function deprecated_getTotalStakedTokensOnSmartContract(
address _stakedContractAddress
)
external
view
returns(uint)
{
uint stakedAmount = 0;
address stakerAddress;
uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress);
for (uint i = 0; i < staketLen; i++) {
stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i);
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, i);
uint currentlyStaked;
(, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress,
_stakedContractAddress, stakerIndex);
stakedAmount = stakedAmount.add(currentlyStaked);
}
return stakedAmount;
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note for given coverId.
* @param _of address of the coverHolder.
* @param _coverId coverId of the cover.
*/
function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) {
return _getUserLockedCNTokens(_of, _coverId);
}
/**
* @dev to get the all the cover locked tokens of a user
* @param _of is the user address in concern
* @return amount locked
*/
function getUserAllLockedCNTokens(address _of) external view returns(uint amount) {
for (uint i = 0; i < qd.getUserCoverLength(_of); i++) {
amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i]));
}
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note against given coverId.
* @param _coverId coverId of the cover.
*/
function getLockedCNAgainstCover(uint _coverId) external view returns(uint) {
return _getLockedCNAgainstCover(_coverId);
}
/**
* @dev Returns total amount of staked NXM Tokens on all smart contracts.
* @param _stakerAddress address of the Staker.
*/
function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) {
uint stakedAmount = 0;
address scAddress;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
uint currentlyStaked;
(, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i);
stakedAmount = stakedAmount.add(currentlyStaked);
}
amount = stakedAmount;
}
/**
* @dev Returns total unlockable amount of staked NXM Tokens on all smart contract .
* @param _stakerAddress address of the Staker.
*/
function deprecated_getStakerAllUnlockableStakedTokens(
address _stakerAddress
)
external
view
returns (uint amount)
{
uint unlockableAmount = 0;
address scAddress;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = unlockableAmount.add(
_deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress,
scIndex));
}
amount = unlockableAmount;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tk = NXMToken(ms.tokenAddress());
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
m1 = MCR(ms.getLatestAddress("MC"));
gv = Governance(ms.getLatestAddress("GV"));
mr = MemberRoles(ms.getLatestAddress("MR"));
pd = PoolData(ms.getLatestAddress("PD"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
/**
* @dev Gets the Token price in a given currency
* @param curr Currency name.
* @return price Token Price.
*/
function getTokenPrice(bytes4 curr) public view returns(uint price) {
price = m1.calculateTokenPrice(curr);
}
/**
* @dev Set the flag to check if cover note is deposited against the cover id
* @param coverId Cover Id.
*/
function depositCN(uint coverId) public onlyInternal returns (bool success) {
require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available");
td.setDepositCN(coverId, true);
success = true;
}
/**
* @param _of address of Member
* @param _coverId Cover Id
* @param _lockTime Pending Time + Cover Period 7*1 days
*/
function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal {
uint timeStamp = now.add(_lockTime);
uint coverValidUntil = qd.getValidityOfCover(_coverId);
if (timeStamp >= coverValidUntil) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId));
tc.extendLockOf(_of, reason, timeStamp);
}
}
/**
* @dev to burn the deposited cover tokens
* @param coverId is id of cover whose tokens have to be burned
* @return the status of the successful burning
*/
function burnDepositCN(uint coverId) public onlyInternal returns (bool success) {
address _of = qd.getCoverMemberAddress(coverId);
uint amount;
(amount, ) = td.depositedCN(coverId);
amount = (amount.mul(50)).div(100);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
tc.burnLockedTokens(_of, reason, amount);
success = true;
}
/**
* @dev Unlocks covernote locked against a given cover
* @param coverId id of cover
*/
function unlockCN(uint coverId) public onlyInternal {
(, bool isDeposited) = td.depositedCN(coverId);
require(!isDeposited,"Cover note is deposited and can not be released");
uint lockedCN = _getLockedCNAgainstCover(coverId);
if (lockedCN != 0) {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/**
* @dev Burns tokens used for fraudulent voting against a claim
* @param claimid Claim Id.
* @param _value number of tokens to be burned
* @param _of Claim Assessor's address.
*/
function burnCAToken(uint claimid, uint _value, address _of) public {
require(ms.checkIsAuthToGoverned(msg.sender));
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to lock cover note tokens
* @param coverNoteAmount is number of tokens to be locked
* @param coverPeriod is cover period in concern
* @param coverId is the cover id of cover in concern
* @param _of address whose tokens are to be locked
*/
function lockCN(
uint coverNoteAmount,
uint coverPeriod,
uint coverId,
address _of
)
public
onlyInternal
{
uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp());
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
td.setDepositCNAmount(coverId, coverNoteAmount);
tc.lockOf(_of, reason, coverNoteAmount, validity);
}
/**
* @dev to check if a member is locked for member vote
* @param _of is the member address in concern
* @return the boolean status
*/
function isLockedForMemberVote(address _of) public view returns(bool) {
return now < tk.isLockedForMV(_of);
}
/**
* @dev Internal function to gets amount of locked NXM tokens,
* staked against smartcontract by index
* @param _stakerAddress address of user
* @param _stakedContractAddress staked contract address
* @param _stakedContractIndex index of staking
*/
function deprecated_getStakerLockedTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns
(uint amount)
{
amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress,
_stakedContractAddress, _stakedContractIndex);
}
/**
* @dev Function to gets unlockable amount of locked NXM
* tokens, staked against smartcontract by index
* @param stakerAddress address of staker
* @param stakedContractAddress staked contract address
* @param stakerIndex index of staking
*/
function deprecated_getStakerUnlockableTokensOnSmartContract (
address stakerAddress,
address stakedContractAddress,
uint stakerIndex
)
public
view
returns (uint)
{
return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress,
td.getStakerStakedContractIndex(stakerAddress, stakerIndex));
}
/**
* @dev releases unlockable staked tokens to staker
*/
function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause {
uint unlockableAmount;
address scAddress;
bytes32 reason;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract(
_stakerAddress, scAddress,
scIndex);
td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0);
td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount);
reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex));
tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount);
}
}
/**
* @dev to get tokens of staker locked before burning that are allowed to burn
* @param stakerAdd is the address of the staker
* @param stakedAdd is the address of staked contract in concern
* @param stakerIndex is the staker index in concern
* @return amount of unlockable tokens
* @return amount of tokens that can burn
*/
function _deprecated_unlockableBeforeBurningAndCanBurn(
address stakerAdd,
address stakedAdd,
uint stakerIndex
)
public
view
returns
(uint amount, uint canBurn) {
uint dateAdd;
uint initialStake;
uint totalBurnt;
uint ub;
(, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex);
canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays());
// Can't use SafeMaths for int.
int v = int(initialStake - (canBurn) - (totalBurnt) - (
td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub));
uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract(
stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex));
if (v < 0) {
v = 0;
}
amount = uint(v);
if (canBurn > currentLockedTokens.sub(amount).sub(ub)) {
canBurn = currentLockedTokens.sub(amount).sub(ub);
}
}
/**
* @dev to get tokens of staker that are unlockable
* @param _stakerAddress is the address of the staker
* @param _stakedContractAddress is the address of staked contract in concern
* @param _stakedContractIndex is the staked contract index in concern
* @return amount of unlockable tokens
*/
function _deprecated_getStakerUnlockableTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns
(uint amount)
{
uint initialStake;
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, _stakedContractIndex);
uint burnt;
(, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex);
uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex);
uint currentStakedTokens;
(, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress,
_stakedContractAddress, stakerIndex);
amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt);
}
/**
* @dev Internal function to get the amount of locked NXM tokens,
* staked against smartcontract by index
* @param _stakerAddress address of user
* @param _stakedContractAddress staked contract address
* @param _stakedContractIndex index of staking
*/
function _deprecated_getStakerLockedTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
internal
view
returns
(uint amount)
{
bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress,
_stakedContractAddress, _stakedContractIndex));
amount = tc.tokensLocked(_stakerAddress, reason);
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note for given coverId.
* @param _coverId coverId of the cover.
*/
function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) {
address coverHolder = qd.getCoverMemberAddress(_coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId));
return tc.tokensLockedAtTime(coverHolder, reason, now);
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note for given coverId.
* @param _of address of the coverHolder.
* @param _coverId coverId of the cover.
*/
function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId));
return tc.tokensLockedAtTime(_of, reason, now);
}
/**
* @dev Internal function to gets remaining amount of staked NXM tokens,
* against smartcontract by index
* @param _stakeAmount address of user
* @param _stakeDays staked contract address
* @param _validDays index of staking
*/
function _deprecated_calculateStakedTokens(
uint _stakeAmount,
uint _stakeDays,
uint _validDays
)
internal
pure
returns (uint amount)
{
if (_validDays > _stakeDays) {
uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays);
amount = (rf.mul(_stakeAmount)).div(100000);
} else {
amount = 0;
}
}
/**
* @dev Gets the total staked NXM tokens against Smart contract
* by all stakers
* @param _stakedContractAddress smart contract address.
* @return amount total staked NXM tokens.
*/
function _deprecated_burnStakerTokenLockedAgainstSmartContract(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _amount
)
internal
{
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, _stakedContractIndex);
td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount);
bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress,
_stakedContractAddress, _stakedContractIndex));
tc.burnLockedTokens(_stakerAddress, reason, _amount);
}
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IMemberRoles.sol
/* Copyright (C) 2017 GovBlocks.io
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/ */
pragma solidity 0.5.7;
contract IMemberRoles {
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole(bytes32 _roleName, string memory _roleDescription, address _authorized) public;
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole(address _memberAddress, uint _roleId, bool _active) public;
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _authorized New authorized address against role id
function changeAuthorized(uint _roleId, address _authorized) public;
/// @dev Return number of member roles
function totalRoles() public view returns(uint256);
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns(uint, address[] memory allMemberAddress);
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberAddress.length Member length
function numberOfMembers(uint _memberRoleId) public view returns(uint);
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns(address);
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns(uint[] memory assignedRoles);
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns(bool);
}
// File: nexusmutual-contracts/contracts/external/ERC1132/IERC1132.sol
pragma solidity 0.5.7;
/**
* @title ERC1132 interface
* @dev see https://github.com/ethereum/EIPs/issues/1132
*/
contract IERC1132 {
/**
* @dev Reasons why a user's tokens have been locked
*/
mapping(address => bytes32[]) public lockReason;
/**
* @dev locked token structure
*/
struct LockToken {
uint256 amount;
uint256 validity;
bool claimed;
}
/**
* @dev Holds number & validity of tokens locked for a given reason for
* a specified address
*/
mapping(address => mapping(bytes32 => LockToken)) public locked;
/**
* @dev Records data of all the tokens Locked
*/
event Locked(
address indexed _of,
bytes32 indexed _reason,
uint256 _amount,
uint256 _validity
);
/**
* @dev Records data of all the tokens unlocked
*/
event Unlocked(
address indexed _of,
bytes32 indexed _reason,
uint256 _amount
);
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lock(bytes32 _reason, uint256 _amount, uint256 _time)
public returns (bool);
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public view returns (uint256 amount);
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public view returns (uint256 amount);
/**
* @dev Returns total tokens held by an address (locked + transferable)
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of)
public view returns (uint256 amount);
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLock(bytes32 _reason, uint256 _time)
public returns (bool);
/**
* @dev Increase number of tokens locked for a specified reason
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be increased
*/
function increaseLockAmount(bytes32 _reason, uint256 _amount)
public returns (bool);
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public view returns (uint256 amount);
/**
* @dev Unlocks the unlockable tokens of a specified address
* @param _of Address of user, claiming back unlockable tokens
*/
function unlock(address _of)
public returns (uint256 unlockableTokens);
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public view returns (uint256 unlockableTokens);
}
// File: nexusmutual-contracts/contracts/TokenController.sol
/* Copyright (C) 2020 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract TokenController is IERC1132, Iupgradable {
using SafeMath for uint256;
event Burned(address indexed member, bytes32 lockedUnder, uint256 amount);
NXMToken public token;
IPooledStaking public pooledStaking;
uint public minCALockTime = uint(30).mul(1 days);
bytes32 private constant CLA = bytes32("CLA");
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {
token = NXMToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress('PS'));
}
/**
* @dev to change the operator address
* @param _newOperator is the new address of operator
*/
function changeOperator(address _newOperator) public onlyInternal {
token.changeOperator(_newOperator);
}
/**
* @dev Proxies token transfer through this contract to allow staking when members are locked for voting
* @param _from Source address
* @param _to Destination address
* @param _value Amount to transfer
*/
function operatorTransfer(address _from, address _to, uint _value) onlyInternal external returns (bool) {
require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address");
require(token.operatorTransfer(_from, _value), "Operator transfer failed");
require(token.transfer(_to, _value), "Internal transfer failed");
return true;
}
/**
* @dev Locks a specified amount of tokens,
* for CLA reason and for a specified time
* @param _reason The reason to lock tokens, currently restricted to CLA
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
require(minCALockTime <= _time,"Should lock for minimum time");
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(msg.sender, _reason, _amount, _time);
return true;
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
* @param _of address whose tokens are to be locked
*/
function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time)
public
onlyInternal
returns (bool)
{
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(_of, _reason, _amount, _time);
return true;
}
/**
* @dev Extends lock for reason CLA for a specified time
* @param _reason The reason to lock tokens, currently restricted to CLA
* @param _time Lock extension time in seconds
*/
function extendLock(bytes32 _reason, uint256 _time)
public
checkPause
returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
_extendLock(msg.sender, _reason, _time);
return true;
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLockOf(address _of, bytes32 _reason, uint256 _time)
public
onlyInternal
returns (bool)
{
_extendLock(_of, _reason, _time);
return true;
}
/**
* @dev Increase number of tokens locked for a CLA reason
* @param _reason The reason to lock tokens, currently restricted to CLA
* @param _amount Number of tokens to be increased
*/
function increaseLockAmount(bytes32 _reason, uint256 _amount)
public
checkPause
returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
require(_tokensLocked(msg.sender, _reason) > 0);
token.operatorTransfer(msg.sender, _amount);
locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity);
return true;
}
/**
* @dev burns tokens of an address
* @param _of is the address to burn tokens of
* @param amount is the amount to burn
* @return the boolean status of the burning process
*/
function burnFrom (address _of, uint amount) public onlyInternal returns (bool) {
return token.burnFrom(_of, amount);
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal {
_burnLockedTokens(_of, _reason, _amount);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal {
_reduceLock(_of, _reason, _time);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
{
_releaseLockedTokens(_of, _reason, _amount);
}
/**
* @dev Adds an address to whitelist maintained in the contract
* @param _member address to add to whitelist
*/
function addToWhitelist(address _member) public onlyInternal {
token.addToWhiteList(_member);
}
/**
* @dev Removes an address from the whitelist in the token
* @param _member address to remove
*/
function removeFromWhitelist(address _member) public onlyInternal {
token.removeFromWhiteList(_member);
}
/**
* @dev Mints new token for an address
* @param _member address to reward the minted tokens
* @param _amount number of tokens to mint
*/
function mint(address _member, uint _amount) public onlyInternal {
token.mint(_member, _amount);
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyInternal {
token.lockForMemberVote(_of, _days);
}
/**
* @dev Unlocks the unlockable tokens against CLA of a specified address
* @param _of Address of user, claiming back unlockable tokens against CLA
*/
function unlock(address _of)
public
checkPause
returns (uint256 unlockableTokens)
{
unlockableTokens = _tokensUnlockable(_of, CLA);
if (unlockableTokens > 0) {
locked[_of][CLA].claimed = true;
emit Unlocked(_of, CLA, unlockableTokens);
require(token.transfer(_of, unlockableTokens));
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "MNCLT") {
minCALockTime = val.mul(1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Gets the validity of locked tokens of a specified address
* @param _of The address to query the validity
* @param reason reason for which tokens were locked
*/
function getLockedTokensValidity(address _of, bytes32 reason)
public
view
returns (uint256 validity)
{
validity = locked[_of][reason].validity;
}
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public
view
returns (uint256 unlockableTokens)
{
for (uint256 i = 0; i < lockReason[_of].length; i++) {
unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i]));
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensLocked(_of, _reason);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensUnlockable(_of, _reason);
}
function totalSupply() public view returns (uint256)
{
return token.totalSupply();
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public
view
returns (uint256 amount)
{
return _tokensLockedAtTime(_of, _reason, _time);
}
/**
* @dev Returns the total amount of tokens held by an address:
* transferable + locked + staked for pooled staking - pending burns.
* Used by Claims and Governance in member voting to calculate the user's vote weight.
*
* @param _of The address to query the total balance of
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of) public view returns (uint256 amount) {
amount = token.balanceOf(_of);
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
uint stakerReward = pooledStaking.stakerReward(_of);
uint stakerDeposit = pooledStaking.stakerDeposit(_of);
amount = amount.add(stakerDeposit).add(stakerReward);
}
/**
* @dev Returns the total locked tokens at time
* Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility
* for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment.
* Does not take into account pending burns.
*
* @param _of member whose locked tokens are to be calculate
* @param _time timestamp when the tokens should be locked
*/
function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal {
require(_tokensLocked(_of, _reason) == 0);
require(_amount != 0);
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
require(token.operatorTransfer(_of, _amount));
uint256 validUntil = now.add(_time); //solhint-disable-line
locked[_of][_reason] = LockToken(_amount, validUntil, false);
emit Locked(_of, _reason, _amount, validUntil);
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function _tokensLocked(address _of, bytes32 _reason)
internal
view
returns (uint256 amount)
{
if (!locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
internal
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Extends lock for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function _extendLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0);
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0);
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount)
{
if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal {
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount);
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
if (locked[_of][_reason].amount == 0) {
_removeReason(_of, _reason);
}
token.burn(_amount);
emit Burned(_of, _reason, _amount);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal
{
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount);
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
if (locked[_of][_reason].amount == 0) {
_removeReason(_of, _reason);
}
require(token.transfer(_of, _amount));
emit Unlocked(_of, _reason, _amount);
}
function _removeReason(address _of, bytes32 _reason) internal {
uint len = lockReason[_of].length;
for (uint i = 0; i < len; i++) {
if (lockReason[_of][i] == _reason) {
lockReason[_of][i] = lockReason[_of][len.sub(1)];
lockReason[_of].pop();
break;
}
}
}
}
// File: nexusmutual-contracts/contracts/ClaimsData.sol
/* Copyright (C) 2017 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract ClaimsData is Iupgradable {
using SafeMath for uint;
struct Claim {
uint coverId;
uint dateUpd;
}
struct Vote {
address voter;
uint tokens;
uint claimId;
int8 verdict;
bool rewardClaimed;
}
struct ClaimsPause {
uint coverid;
uint dateUpd;
bool submit;
}
struct ClaimPauseVoting {
uint claimid;
uint pendingTime;
bool voting;
}
struct RewardDistributed {
uint lastCAvoteIndex;
uint lastMVvoteIndex;
}
struct ClaimRewardDetails {
uint percCA;
uint percMV;
uint tokenToBeDist;
}
struct ClaimTotalTokens {
uint accept;
uint deny;
}
struct ClaimRewardStatus {
uint percCA;
uint percMV;
}
ClaimRewardStatus[] internal rewardStatus;
Claim[] internal allClaims;
Vote[] internal allvotes;
ClaimsPause[] internal claimPause;
ClaimPauseVoting[] internal claimPauseVotingEP;
mapping(address => RewardDistributed) internal voterVoteRewardReceived;
mapping(uint => ClaimRewardDetails) internal claimRewardDetail;
mapping(uint => ClaimTotalTokens) internal claimTokensCA;
mapping(uint => ClaimTotalTokens) internal claimTokensMV;
mapping(uint => int8) internal claimVote;
mapping(uint => uint) internal claimsStatus;
mapping(uint => uint) internal claimState12Count;
mapping(uint => uint[]) internal claimVoteCA;
mapping(uint => uint[]) internal claimVoteMember;
mapping(address => uint[]) internal voteAddressCA;
mapping(address => uint[]) internal voteAddressMember;
mapping(address => uint[]) internal allClaimsByAddress;
mapping(address => mapping(uint => uint)) internal userClaimVoteCA;
mapping(address => mapping(uint => uint)) internal userClaimVoteMember;
mapping(address => uint) public userClaimVotePausedOn;
uint internal claimPauseLastsubmit;
uint internal claimStartVotingFirstIndex;
uint public pendingClaimStart;
uint public claimDepositTime;
uint public maxVotingTime;
uint public minVotingTime;
uint public payoutRetryTime;
uint public claimRewardPerc;
uint public minVoteThreshold;
uint public maxVoteThreshold;
uint public majorityConsensus;
uint public pauseDaysCA;
event ClaimRaise(
uint indexed coverId,
address indexed userAddress,
uint claimId,
uint dateSubmit
);
event VoteCast(
address indexed userAddress,
uint indexed claimId,
bytes4 indexed typeOf,
uint tokens,
uint submitDate,
int8 verdict
);
constructor() public {
pendingClaimStart = 1;
maxVotingTime = 48 * 1 hours;
minVotingTime = 12 * 1 hours;
payoutRetryTime = 24 * 1 hours;
allvotes.push(Vote(address(0), 0, 0, 0, false));
allClaims.push(Claim(0, 0));
claimDepositTime = 7 days;
claimRewardPerc = 20;
minVoteThreshold = 5;
maxVoteThreshold = 10;
majorityConsensus = 70;
pauseDaysCA = 3 days;
_addRewardIncentive();
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function setpendingClaimStart(uint _start) external onlyInternal {
require(pendingClaimStart <= _start);
pendingClaimStart = _start;
}
/**
* @dev Updates the max vote index for which claim assessor has received reward
* @param _voter address of the voter.
* @param caIndex last index till which reward was distributed for CA
*/
function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex;
}
/**
* @dev Used to pause claim assessor activity for 3 days
* @param user Member address whose claim voting ability needs to be paused
*/
function setUserClaimVotePausedOn(address user) external {
require(ms.checkIsAuthToGoverned(msg.sender));
userClaimVotePausedOn[user] = now;
}
/**
* @dev Updates the max vote index for which member has received reward
* @param _voter address of the voter.
* @param mvIndex last index till which reward was distributed for member
*/
function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex;
}
/**
* @param claimid claim id.
* @param percCA reward Percentage reward for claim assessor
* @param percMV reward Percentage reward for members
* @param tokens total tokens to be rewarded
*/
function setClaimRewardDetail(
uint claimid,
uint percCA,
uint percMV,
uint tokens
)
external
onlyInternal
{
claimRewardDetail[claimid].percCA = percCA;
claimRewardDetail[claimid].percMV = percMV;
claimRewardDetail[claimid].tokenToBeDist = tokens;
}
/**
* @dev Sets the reward claim status against a vote id.
* @param _voteid vote Id.
* @param claimed true if reward for vote is claimed, else false.
*/
function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal {
allvotes[_voteid].rewardClaimed = claimed;
}
/**
* @dev Sets the final vote's result(either accepted or declined)of a claim.
* @param _claimId Claim Id.
* @param _verdict 1 if claim is accepted,-1 if declined.
*/
function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal {
claimVote[_claimId] = _verdict;
}
/**
* @dev Creates a new claim.
*/
function addClaim(
uint _claimId,
uint _coverId,
address _from,
uint _nowtime
)
external
onlyInternal
{
allClaims.push(Claim(_coverId, _nowtime));
allClaimsByAddress[_from].push(_claimId);
}
/**
* @dev Add Vote's details of a given claim.
*/
function addVote(
address _voter,
uint _tokens,
uint claimId,
int8 _verdict
)
external
onlyInternal
{
allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false));
}
/**
* @dev Stores the id of the claim assessor vote given to a claim.
* Maintains record of all votes given by all the CA to a claim.
* @param _claimId Claim Id to which vote has given by the CA.
* @param _voteid Vote Id.
*/
function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal {
claimVoteCA[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Claim assessor's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the CA.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteCA(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteCA[_from][_claimId] = _voteid;
voteAddressCA[_from].push(_voteid);
}
/**
* @dev Stores the tokens locked by the Claim Assessors during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
if (_vote == -1)
claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev Stores the tokens locked by the Members during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
if (_vote == -1)
claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev Stores the id of the member vote given to a claim.
* Maintains record of all votes given by all the Members to a claim.
* @param _claimId Claim Id to which vote has been given by the Member.
* @param _voteid Vote Id.
*/
function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal {
claimVoteMember[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Member's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the Member.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteMember(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteMember[_from][_claimId] = _voteid;
voteAddressMember[_from].push(_voteid);
}
/**
* @dev Increases the count of failure until payout of a claim is successful.
*/
function updateState12Count(uint _claimId, uint _cnt) external onlyInternal {
claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev Sets status of a claim.
* @param _claimId Claim Id.
* @param _stat Status number.
*/
function setClaimStatus(uint _claimId, uint _stat) external onlyInternal {
claimsStatus[_claimId] = _stat;
}
/**
* @dev Sets the timestamp of a given claim at which the Claim's details has been updated.
* @param _claimId Claim Id of claim which has been changed.
* @param _dateUpd timestamp at which claim is updated.
*/
function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal {
allClaims[_claimId].dateUpd = _dateUpd;
}
/**
@dev Queues Claims during Emergency Pause.
*/
function setClaimAtEmergencyPause(
uint _coverId,
uint _dateUpd,
bool _submit
)
external
onlyInternal
{
claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit));
}
/**
* @dev Set submission flag for Claims queued during emergency pause.
* Set to true after EP is turned off and the claim is submitted .
*/
function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal {
claimPause[_index].submit = _submit;
}
/**
* @dev Sets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function setFirstClaimIndexToSubmitAfterEP(
uint _firstClaimIndexToSubmit
)
external
onlyInternal
{
claimPauseLastsubmit = _firstClaimIndexToSubmit;
}
/**
* @dev Sets the pending vote duration for a claim in case of emergency pause.
*/
function setPendingClaimDetails(
uint _claimId,
uint _pendingTime,
bool _voting
)
external
onlyInternal
{
claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting));
}
/**
* @dev Sets voting flag true after claim is reopened for voting after emergency pause.
*/
function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal {
claimPauseVotingEP[_claimId].voting = _vote;
}
/**
* @dev Sets the index from which claim needs to be
* reopened when emergency pause is swithched off.
*/
function setFirstClaimIndexToStartVotingAfterEP(
uint _claimStartVotingFirstIndex
)
external
onlyInternal
{
claimStartVotingFirstIndex = _claimStartVotingFirstIndex;
}
/**
* @dev Calls Vote Event.
*/
function callVoteEvent(
address _userAddress,
uint _claimId,
bytes4 _typeOf,
uint _tokens,
uint _submitDate,
int8 _verdict
)
external
onlyInternal
{
emit VoteCast(
_userAddress,
_claimId,
_typeOf,
_tokens,
_submitDate,
_verdict
);
}
/**
* @dev Calls Claim Event.
*/
function callClaimEvent(
uint _coverId,
address _userAddress,
uint _claimId,
uint _datesubmit
)
external
onlyInternal
{
emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit);
}
/**
* @dev Gets Uint Parameters by parameter code
* @param code whose details we want
* @return string value of the parameter
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "CAMAXVT") {
val = maxVotingTime / (1 hours);
} else if (code == "CAMINVT") {
val = minVotingTime / (1 hours);
} else if (code == "CAPRETRY") {
val = payoutRetryTime / (1 hours);
} else if (code == "CADEPT") {
val = claimDepositTime / (1 days);
} else if (code == "CAREWPER") {
val = claimRewardPerc;
} else if (code == "CAMINTH") {
val = minVoteThreshold;
} else if (code == "CAMAXTH") {
val = maxVoteThreshold;
} else if (code == "CACONPER") {
val = majorityConsensus;
} else if (code == "CAPAUSET") {
val = pauseDaysCA / (1 days);
}
}
/**
* @dev Get claim queued during emergency pause by index.
*/
function getClaimOfEmergencyPauseByIndex(
uint _index
)
external
view
returns(
uint coverId,
uint dateUpd,
bool submit
)
{
coverId = claimPause[_index].coverid;
dateUpd = claimPause[_index].dateUpd;
submit = claimPause[_index].submit;
}
/**
* @dev Gets the Claim's details of given claimid.
*/
function getAllClaimsByIndex(
uint _claimId
)
external
view
returns(
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return(
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the vote id of a given claim of a given Claim Assessor.
*/
function getUserClaimVoteCA(
address _add,
uint _claimId
)
external
view
returns(uint idVote)
{
return userClaimVoteCA[_add][_claimId];
}
/**
* @dev Gets the vote id of a given claim of a given member.
*/
function getUserClaimVoteMember(
address _add,
uint _claimId
)
external
view
returns(uint idVote)
{
return userClaimVoteMember[_add][_claimId];
}
/**
* @dev Gets the count of all votes.
*/
function getAllVoteLength() external view returns(uint voteCount) {
return allvotes.length.sub(1); //Start Index always from 1.
}
/**
* @dev Gets the status number of a given claim.
* @param _claimId Claim id.
* @return statno Status Number.
*/
function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) {
return (_claimId, claimsStatus[_claimId]);
}
/**
* @dev Gets the reward percentage to be distributed for a given status id
* @param statusNumber the number of type of status
* @return percCA reward Percentage for claim assessor
* @return percMV reward Percentage for members
*/
function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) {
return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV);
}
/**
* @dev Gets the number of tries that have been made for a successful payout of a Claim.
*/
function getClaimState12Count(uint _claimId) external view returns(uint num) {
num = claimState12Count[_claimId];
}
/**
* @dev Gets the last update date of a claim.
*/
function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) {
dateupd = allClaims[_claimId].dateUpd;
}
/**
* @dev Gets all Claims created by a user till date.
* @param _member user's address.
* @return claimarr List of Claims id.
*/
function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) {
return allClaimsByAddress[_member];
}
/**
* @dev Gets the number of tokens that has been locked
* while giving vote to a claim by Claim Assessors.
* @param _claimId Claim Id.
* @return accept Total number of tokens when CA accepts the claim.
* @return deny Total number of tokens when CA declines the claim.
*/
function getClaimsTokenCA(
uint _claimId
)
external
view
returns(
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensCA[_claimId].accept,
claimTokensCA[_claimId].deny
);
}
/**
* @dev Gets the number of tokens that have been
* locked while assessing a claim as a member.
* @param _claimId Claim Id.
* @return accept Total number of tokens in acceptance of the claim.
* @return deny Total number of tokens against the claim.
*/
function getClaimsTokenMV(
uint _claimId
)
external
view
returns(
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensMV[_claimId].accept,
claimTokensMV[_claimId].deny
);
}
/**
* @dev Gets the total number of votes cast as Claims assessor for/against a given claim
*/
function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) {
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets the total number of tokens cast as a member for/against a given claim
*/
function getMemberClaimVotesToken(
uint _claimId
)
external
view
returns(uint claimId, uint cnt)
{
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @dev Provides information of a vote when given its vote id.
* @param _voteid Vote Id.
*/
function getVoteDetails(uint _voteid)
external view
returns(
uint tokens,
uint claimId,
int8 verdict,
bool rewardClaimed
)
{
return (
allvotes[_voteid].tokens,
allvotes[_voteid].claimId,
allvotes[_voteid].verdict,
allvotes[_voteid].rewardClaimed
);
}
/**
* @dev Gets the voter's address of a given vote id.
*/
function getVoterVote(uint _voteid) external view returns(address voter) {
return allvotes[_voteid].voter;
}
/**
* @dev Provides information of a Claim when given its claim id.
* @param _claimId Claim Id.
*/
function getClaim(
uint _claimId
)
external
view
returns(
uint claimId,
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
_claimId,
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the total number of votes of a given claim.
* @param _claimId Claim Id.
* @param _ca if 1: votes given by Claim Assessors to a claim,
* else returns the number of votes of given by Members to a claim.
* @return len total number of votes for/against a given claim.
*/
function getClaimVoteLength(
uint _claimId,
uint8 _ca
)
external
view
returns(uint claimId, uint len)
{
claimId = _claimId;
if (_ca == 1)
len = claimVoteCA[_claimId].length;
else
len = claimVoteMember[_claimId].length;
}
/**
* @dev Gets the verdict of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return ver 1 if vote was given in favour,-1 if given in against.
*/
function getVoteVerdict(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns(int8 ver)
{
if (_ca == 1)
ver = allvotes[claimVoteCA[_claimId][_index]].verdict;
else
ver = allvotes[claimVoteMember[_claimId][_index]].verdict;
}
/**
* @dev Gets the Number of tokens of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return tok Number of tokens.
*/
function getVoteToken(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns(uint tok)
{
if (_ca == 1)
tok = allvotes[claimVoteCA[_claimId][_index]].tokens;
else
tok = allvotes[claimVoteMember[_claimId][_index]].tokens;
}
/**
* @dev Gets the Voter's address of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return voter Voter's address.
*/
function getVoteVoter(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns(address voter)
{
if (_ca == 1)
voter = allvotes[claimVoteCA[_claimId][_index]].voter;
else
voter = allvotes[claimVoteMember[_claimId][_index]].voter;
}
/**
* @dev Gets total number of Claims created by a user till date.
* @param _add User's address.
*/
function getUserClaimCount(address _add) external view returns(uint len) {
len = allClaimsByAddress[_add].length;
}
/**
* @dev Calculates number of Claims that are in pending state.
*/
function getClaimLength() external view returns(uint len) {
len = allClaims.length.sub(pendingClaimStart);
}
/**
* @dev Gets the Number of all the Claims created till date.
*/
function actualClaimLength() external view returns(uint len) {
len = allClaims.length;
}
/**
* @dev Gets details of a claim.
* @param _index claim id = pending claim start + given index
* @param _add User's address.
* @return coverid cover against which claim has been submitted.
* @return claimId Claim Id.
* @return voteCA verdict of vote given as a Claim Assessor.
* @return voteMV verdict of vote given as a Member.
* @return statusnumber Status of claim.
*/
function getClaimFromNewStart(
uint _index,
address _add
)
external
view
returns(
uint coverid,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
uint i = pendingClaimStart.add(_index);
coverid = allClaims[i].coverId;
claimId = i;
if (userClaimVoteCA[_add][i] > 0)
voteCA = allvotes[userClaimVoteCA[_add][i]].verdict;
else
voteCA = 0;
if (userClaimVoteMember[_add][i] > 0)
voteMV = allvotes[userClaimVoteMember[_add][i]].verdict;
else
voteMV = 0;
statusnumber = claimsStatus[i];
}
/**
* @dev Gets details of a claim of a user at a given index.
*/
function getUserClaimByIndex(
uint _index,
address _add
)
external
view
returns(
uint status,
uint coverid,
uint claimId
)
{
claimId = allClaimsByAddress[_add][_index];
status = claimsStatus[claimId];
coverid = allClaims[claimId].coverId;
}
/**
* @dev Gets Id of all the votes given to a claim.
* @param _claimId Claim Id.
* @return ca id of all the votes given by Claim assessors to a claim.
* @return mv id of all the votes given by members to a claim.
*/
function getAllVotesForClaim(
uint _claimId
)
external
view
returns(
uint claimId,
uint[] memory ca,
uint[] memory mv
)
{
return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]);
}
/**
* @dev Gets Number of tokens deposit in a vote using
* Claim assessor's address and claim id.
* @return tokens Number of deposited tokens.
*/
function getTokensClaim(
address _of,
uint _claimId
)
external
view
returns(
uint claimId,
uint tokens
)
{
return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens);
}
/**
* @param _voter address of the voter.
* @return lastCAvoteIndex last index till which reward was distributed for CA
* @return lastMVvoteIndex last index till which reward was distributed for member
*/
function getRewardDistributedIndex(
address _voter
)
external
view
returns(
uint lastCAvoteIndex,
uint lastMVvoteIndex
)
{
return (
voterVoteRewardReceived[_voter].lastCAvoteIndex,
voterVoteRewardReceived[_voter].lastMVvoteIndex
);
}
/**
* @param claimid claim id.
* @return perc_CA reward Percentage for claim assessor
* @return perc_MV reward Percentage for members
* @return tokens total tokens to be rewarded
*/
function getClaimRewardDetail(
uint claimid
)
external
view
returns(
uint percCA,
uint percMV,
uint tokens
)
{
return (
claimRewardDetail[claimid].percCA,
claimRewardDetail[claimid].percMV,
claimRewardDetail[claimid].tokenToBeDist
);
}
/**
* @dev Gets cover id of a claim.
*/
function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) {
return (_claimId, allClaims[_claimId].coverId);
}
/**
* @dev Gets total number of tokens staked during voting by Claim Assessors.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter).
*/
function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets total number of tokens staked during voting by Members.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens,
* -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or
* deny on the basis of verdict given as parameter).
*/
function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @param _voter address of voteid
* @param index index to get voteid in CA
*/
function getVoteAddressCA(address _voter, uint index) external view returns(uint) {
return voteAddressCA[_voter][index];
}
/**
* @param _voter address of voter
* @param index index to get voteid in member vote
*/
function getVoteAddressMember(address _voter, uint index) external view returns(uint) {
return voteAddressMember[_voter][index];
}
/**
* @param _voter address of voter
*/
function getVoteAddressCALength(address _voter) external view returns(uint) {
return voteAddressCA[_voter].length;
}
/**
* @param _voter address of voter
*/
function getVoteAddressMemberLength(address _voter) external view returns(uint) {
return voteAddressMember[_voter].length;
}
/**
* @dev Gets the Final result of voting of a claim.
* @param _claimId Claim id.
* @return verdict 1 if claim is accepted, -1 if declined.
*/
function getFinalVerdict(uint _claimId) external view returns(int8 verdict) {
return claimVote[_claimId];
}
/**
* @dev Get number of Claims queued for submission during emergency pause.
*/
function getLengthOfClaimSubmittedAtEP() external view returns(uint len) {
len = claimPause.length;
}
/**
* @dev Gets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) {
indexToSubmit = claimPauseLastsubmit;
}
/**
* @dev Gets number of Claims to be reopened for voting post emergency pause period.
*/
function getLengthOfClaimVotingPause() external view returns(uint len) {
len = claimPauseVotingEP.length;
}
/**
* @dev Gets claim details to be reopened for voting after emergency pause.
*/
function getPendingClaimDetailsByIndex(
uint _index
)
external
view
returns(
uint claimId,
uint pendingTime,
bool voting
)
{
claimId = claimPauseVotingEP[_index].claimid;
pendingTime = claimPauseVotingEP[_index].pendingTime;
voting = claimPauseVotingEP[_index].voting;
}
/**
* @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off.
*/
function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) {
firstindex = claimStartVotingFirstIndex;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "CAMAXVT") {
_setMaxVotingTime(val * 1 hours);
} else if (code == "CAMINVT") {
_setMinVotingTime(val * 1 hours);
} else if (code == "CAPRETRY") {
_setPayoutRetryTime(val * 1 hours);
} else if (code == "CADEPT") {
_setClaimDepositTime(val * 1 days);
} else if (code == "CAREWPER") {
_setClaimRewardPerc(val);
} else if (code == "CAMINTH") {
_setMinVoteThreshold(val);
} else if (code == "CAMAXTH") {
_setMaxVoteThreshold(val);
} else if (code == "CACONPER") {
_setMajorityConsensus(val);
} else if (code == "CAPAUSET") {
_setPauseDaysCA(val * 1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {}
/**
* @dev Adds status under which a claim can lie.
* @param percCA reward percentage for claim assessor
* @param percMV reward percentage for members
*/
function _pushStatus(uint percCA, uint percMV) internal {
rewardStatus.push(ClaimRewardStatus(percCA, percMV));
}
/**
* @dev adds reward incentive for all possible claim status for Claim assessors and members
*/
function _addRewardIncentive() internal {
_pushStatus(0, 0); //0 Pending-Claim Assessor Vote
_pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote
_pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote
_pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote
_pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote
_pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote
_pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied
_pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted
_pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted
_pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied
_pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision
_pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision
_pushStatus(0, 0); //12 Claim Accepted Payout Pending
_pushStatus(0, 0); //13 Claim Accepted No Payout
_pushStatus(0, 0); //14 Claim Accepted Payout Done
}
/**
* @dev Sets Maximum time(in seconds) for which claim assessment voting is open
*/
function _setMaxVotingTime(uint _time) internal {
maxVotingTime = _time;
}
/**
* @dev Sets Minimum time(in seconds) for which claim assessment voting is open
*/
function _setMinVotingTime(uint _time) internal {
minVotingTime = _time;
}
/**
* @dev Sets Minimum vote threshold required
*/
function _setMinVoteThreshold(uint val) internal {
minVoteThreshold = val;
}
/**
* @dev Sets Maximum vote threshold required
*/
function _setMaxVoteThreshold(uint val) internal {
maxVoteThreshold = val;
}
/**
* @dev Sets the value considered as Majority Consenus in voting
*/
function _setMajorityConsensus(uint val) internal {
majorityConsensus = val;
}
/**
* @dev Sets the payout retry time
*/
function _setPayoutRetryTime(uint _time) internal {
payoutRetryTime = _time;
}
/**
* @dev Sets percentage of reward given for claim assessment
*/
function _setClaimRewardPerc(uint _val) internal {
claimRewardPerc = _val;
}
/**
* @dev Sets the time for which claim is deposited.
*/
function _setClaimDepositTime(uint _time) internal {
claimDepositTime = _time;
}
/**
* @dev Sets number of days claim assessment will be paused
*/
function _setPauseDaysCA(uint val) internal {
pauseDaysCA = val;
}
}
// File: nexusmutual-contracts/contracts/PoolData.sol
/* Copyright (C) 2017 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract DSValue {
function peek() public view returns (bytes32, bool);
function read() public view returns (bytes32);
}
contract PoolData is Iupgradable {
using SafeMath for uint;
struct ApiId {
bytes4 typeOf;
bytes4 currency;
uint id;
uint64 dateAdd;
uint64 dateUpd;
}
struct CurrencyAssets {
address currAddress;
uint baseMin;
uint varMin;
}
struct InvestmentAssets {
address currAddress;
bool status;
uint64 minHoldingPercX100;
uint64 maxHoldingPercX100;
uint8 decimals;
}
struct IARankDetails {
bytes4 maxIACurr;
uint64 maxRate;
bytes4 minIACurr;
uint64 minRate;
}
struct McrData {
uint mcrPercx100;
uint mcrEther;
uint vFull; //Pool funds
uint64 date;
}
IARankDetails[] internal allIARankDetails;
McrData[] public allMCRData;
bytes4[] internal allInvestmentCurrencies;
bytes4[] internal allCurrencies;
bytes32[] public allAPIcall;
mapping(bytes32 => ApiId) public allAPIid;
mapping(uint64 => uint) internal datewiseId;
mapping(bytes16 => uint) internal currencyLastIndex;
mapping(bytes4 => CurrencyAssets) internal allCurrencyAssets;
mapping(bytes4 => InvestmentAssets) internal allInvestmentAssets;
mapping(bytes4 => uint) internal caAvgRate;
mapping(bytes4 => uint) internal iaAvgRate;
address public notariseMCR;
address public daiFeedAddress;
uint private constant DECIMAL1E18 = uint(10) ** 18;
uint public uniswapDeadline;
uint public liquidityTradeCallbackTime;
uint public lastLiquidityTradeTrigger;
uint64 internal lastDate;
uint public variationPercX100;
uint public iaRatesTime;
uint public minCap;
uint public mcrTime;
uint public a;
uint public shockParameter;
uint public c;
uint public mcrFailTime;
uint public ethVolumeLimit;
uint public capReached;
uint public capacityLimit;
constructor(address _notariseAdd, address _daiFeedAdd, address _daiAdd) public {
notariseMCR = _notariseAdd;
daiFeedAddress = _daiFeedAdd;
c = 5800000;
a = 1028;
mcrTime = 24 hours;
mcrFailTime = 6 hours;
allMCRData.push(McrData(0, 0, 0, 0));
minCap = 12000 * DECIMAL1E18;
shockParameter = 50;
variationPercX100 = 100; //1%
iaRatesTime = 24 hours; //24 hours in seconds
uniswapDeadline = 20 minutes;
liquidityTradeCallbackTime = 4 hours;
ethVolumeLimit = 4;
capacityLimit = 10;
allCurrencies.push("ETH");
allCurrencyAssets["ETH"] = CurrencyAssets(address(0), 1000 * DECIMAL1E18, 0);
allCurrencies.push("DAI");
allCurrencyAssets["DAI"] = CurrencyAssets(_daiAdd, 50000 * DECIMAL1E18, 0);
allInvestmentCurrencies.push("ETH");
allInvestmentAssets["ETH"] = InvestmentAssets(address(0), true, 2500, 10000, 18);
allInvestmentCurrencies.push("DAI");
allInvestmentAssets["DAI"] = InvestmentAssets(_daiAdd, true, 250, 1500, 18);
}
/**
* @dev to set the maximum cap allowed
* @param val is the new value
*/
function setCapReached(uint val) external onlyInternal {
capReached = val;
}
/// @dev Updates the 3 day average rate of a IA currency.
/// To be replaced by MakerDao's on chain rates
/// @param curr IA Currency Name.
/// @param rate Average exchange rate X 100 (of last 3 days).
function updateIAAvgRate(bytes4 curr, uint rate) external onlyInternal {
iaAvgRate[curr] = rate;
}
/// @dev Updates the 3 day average rate of a CA currency.
/// To be replaced by MakerDao's on chain rates
/// @param curr Currency Name.
/// @param rate Average exchange rate X 100 (of last 3 days).
function updateCAAvgRate(bytes4 curr, uint rate) external onlyInternal {
caAvgRate[curr] = rate;
}
/// @dev Adds details of (Minimum Capital Requirement)MCR.
/// @param mcrp Minimum Capital Requirement percentage (MCR% * 100 ,Ex:for 54.56% ,given 5456)
/// @param vf Pool fund value in Ether used in the last full daily calculation from the Capital model.
function pushMCRData(uint mcrp, uint mcre, uint vf, uint64 time) external onlyInternal {
allMCRData.push(McrData(mcrp, mcre, vf, time));
}
/**
* @dev Updates the Timestamp at which result of oracalize call is received.
*/
function updateDateUpdOfAPI(bytes32 myid) external onlyInternal {
allAPIid[myid].dateUpd = uint64(now);
}
/**
* @dev Saves the details of the Oraclize API.
* @param myid Id return by the oraclize query.
* @param _typeof type of the query for which oraclize call is made.
* @param id ID of the proposal,quote,cover etc. for which oraclize call is made
*/
function saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) external onlyInternal {
allAPIid[myid] = ApiId(_typeof, "", id, uint64(now), uint64(now));
}
/**
* @dev Stores the id return by the oraclize query.
* Maintains record of all the Ids return by oraclize query.
* @param myid Id return by the oraclize query.
*/
function addInAllApiCall(bytes32 myid) external onlyInternal {
allAPIcall.push(myid);
}
/**
* @dev Saves investment asset rank details.
* @param maxIACurr Maximum ranked investment asset currency.
* @param maxRate Maximum ranked investment asset rate.
* @param minIACurr Minimum ranked investment asset currency.
* @param minRate Minimum ranked investment asset rate.
* @param date in yyyymmdd.
*/
function saveIARankDetails(
bytes4 maxIACurr,
uint64 maxRate,
bytes4 minIACurr,
uint64 minRate,
uint64 date
)
external
onlyInternal
{
allIARankDetails.push(IARankDetails(maxIACurr, maxRate, minIACurr, minRate));
datewiseId[date] = allIARankDetails.length.sub(1);
}
/**
* @dev to get the time for the laste liquidity trade trigger
*/
function setLastLiquidityTradeTrigger() external onlyInternal {
lastLiquidityTradeTrigger = now;
}
/**
* @dev Updates Last Date.
*/
function updatelastDate(uint64 newDate) external onlyInternal {
lastDate = newDate;
}
/**
* @dev Adds currency asset currency.
* @param curr currency of the asset
* @param currAddress address of the currency
* @param baseMin base minimum in 10^18.
*/
function addCurrencyAssetCurrency(
bytes4 curr,
address currAddress,
uint baseMin
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allCurrencies.push(curr);
allCurrencyAssets[curr] = CurrencyAssets(currAddress, baseMin, 0);
}
/**
* @dev Adds investment asset.
*/
function addInvestmentAssetCurrency(
bytes4 curr,
address currAddress,
bool status,
uint64 minHoldingPercX100,
uint64 maxHoldingPercX100,
uint8 decimals
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentCurrencies.push(curr);
allInvestmentAssets[curr] = InvestmentAssets(currAddress, status,
minHoldingPercX100, maxHoldingPercX100, decimals);
}
/**
* @dev Changes base minimum of a given currency asset.
*/
function changeCurrencyAssetBaseMin(bytes4 curr, uint baseMin) external {
require(ms.checkIsAuthToGoverned(msg.sender));
allCurrencyAssets[curr].baseMin = baseMin;
}
/**
* @dev changes variable minimum of a given currency asset.
*/
function changeCurrencyAssetVarMin(bytes4 curr, uint varMin) external onlyInternal {
allCurrencyAssets[curr].varMin = varMin;
}
/**
* @dev Changes the investment asset status.
*/
function changeInvestmentAssetStatus(bytes4 curr, bool status) external {
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentAssets[curr].status = status;
}
/**
* @dev Changes the investment asset Holding percentage of a given currency.
*/
function changeInvestmentAssetHoldingPerc(
bytes4 curr,
uint64 minPercX100,
uint64 maxPercX100
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentAssets[curr].minHoldingPercX100 = minPercX100;
allInvestmentAssets[curr].maxHoldingPercX100 = maxPercX100;
}
/**
* @dev Gets Currency asset token address.
*/
function changeCurrencyAssetAddress(bytes4 curr, address currAdd) external {
require(ms.checkIsAuthToGoverned(msg.sender));
allCurrencyAssets[curr].currAddress = currAdd;
}
/**
* @dev Changes Investment asset token address.
*/
function changeInvestmentAssetAddressAndDecimal(
bytes4 curr,
address currAdd,
uint8 newDecimal
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentAssets[curr].currAddress = currAdd;
allInvestmentAssets[curr].decimals = newDecimal;
}
/// @dev Changes address allowed to post MCR.
function changeNotariseAddress(address _add) external onlyInternal {
notariseMCR = _add;
}
/// @dev updates daiFeedAddress address.
/// @param _add address of DAI feed.
function changeDAIfeedAddress(address _add) external onlyInternal {
daiFeedAddress = _add;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) {
codeVal = code;
if (code == "MCRTIM") {
val = mcrTime / (1 hours);
} else if (code == "MCRFTIM") {
val = mcrFailTime / (1 hours);
} else if (code == "MCRMIN") {
val = minCap;
} else if (code == "MCRSHOCK") {
val = shockParameter;
} else if (code == "MCRCAPL") {
val = capacityLimit;
} else if (code == "IMZ") {
val = variationPercX100;
} else if (code == "IMRATET") {
val = iaRatesTime / (1 hours);
} else if (code == "IMUNIDL") {
val = uniswapDeadline / (1 minutes);
} else if (code == "IMLIQT") {
val = liquidityTradeCallbackTime / (1 hours);
} else if (code == "IMETHVL") {
val = ethVolumeLimit;
} else if (code == "C") {
val = c;
} else if (code == "A") {
val = a;
}
}
/// @dev Checks whether a given address can notaise MCR data or not.
/// @param _add Address.
/// @return res Returns 0 if address is not authorized, else 1.
function isnotarise(address _add) external view returns(bool res) {
res = false;
if (_add == notariseMCR)
res = true;
}
/// @dev Gets the details of last added MCR.
/// @return mcrPercx100 Total Minimum Capital Requirement percentage of that month of year(multiplied by 100).
/// @return vFull Total Pool fund value in Ether used in the last full daily calculation.
function getLastMCR() external view returns(uint mcrPercx100, uint mcrEtherx1E18, uint vFull, uint64 date) {
uint index = allMCRData.length.sub(1);
return (
allMCRData[index].mcrPercx100,
allMCRData[index].mcrEther,
allMCRData[index].vFull,
allMCRData[index].date
);
}
/// @dev Gets last Minimum Capital Requirement percentage of Capital Model
/// @return val MCR% value,multiplied by 100.
function getLastMCRPerc() external view returns(uint) {
return allMCRData[allMCRData.length.sub(1)].mcrPercx100;
}
/// @dev Gets last Ether price of Capital Model
/// @return val ether value,multiplied by 100.
function getLastMCREther() external view returns(uint) {
return allMCRData[allMCRData.length.sub(1)].mcrEther;
}
/// @dev Gets Pool fund value in Ether used in the last full daily calculation from the Capital model.
function getLastVfull() external view returns(uint) {
return allMCRData[allMCRData.length.sub(1)].vFull;
}
/// @dev Gets last Minimum Capital Requirement in Ether.
/// @return date of MCR.
function getLastMCRDate() external view returns(uint64 date) {
date = allMCRData[allMCRData.length.sub(1)].date;
}
/// @dev Gets details for token price calculation.
function getTokenPriceDetails(bytes4 curr) external view returns(uint _a, uint _c, uint rate) {
_a = a;
_c = c;
rate = _getAvgRate(curr, false);
}
/// @dev Gets the total number of times MCR calculation has been made.
function getMCRDataLength() external view returns(uint len) {
len = allMCRData.length;
}
/**
* @dev Gets investment asset rank details by given date.
*/
function getIARankDetailsByDate(
uint64 date
)
external
view
returns(
bytes4 maxIACurr,
uint64 maxRate,
bytes4 minIACurr,
uint64 minRate
)
{
uint index = datewiseId[date];
return (
allIARankDetails[index].maxIACurr,
allIARankDetails[index].maxRate,
allIARankDetails[index].minIACurr,
allIARankDetails[index].minRate
);
}
/**
* @dev Gets Last Date.
*/
function getLastDate() external view returns(uint64 date) {
return lastDate;
}
/**
* @dev Gets investment currency for a given index.
*/
function getInvestmentCurrencyByIndex(uint index) external view returns(bytes4 currName) {
return allInvestmentCurrencies[index];
}
/**
* @dev Gets count of investment currency.
*/
function getInvestmentCurrencyLen() external view returns(uint len) {
return allInvestmentCurrencies.length;
}
/**
* @dev Gets all the investment currencies.
*/
function getAllInvestmentCurrencies() external view returns(bytes4[] memory currencies) {
return allInvestmentCurrencies;
}
/**
* @dev Gets All currency for a given index.
*/
function getCurrenciesByIndex(uint index) external view returns(bytes4 currName) {
return allCurrencies[index];
}
/**
* @dev Gets count of All currency.
*/
function getAllCurrenciesLen() external view returns(uint len) {
return allCurrencies.length;
}
/**
* @dev Gets all currencies
*/
function getAllCurrencies() external view returns(bytes4[] memory currencies) {
return allCurrencies;
}
/**
* @dev Gets currency asset details for a given currency.
*/
function getCurrencyAssetVarBase(
bytes4 curr
)
external
view
returns(
bytes4 currency,
uint baseMin,
uint varMin
)
{
return (
curr,
allCurrencyAssets[curr].baseMin,
allCurrencyAssets[curr].varMin
);
}
/**
* @dev Gets minimum variable value for currency asset.
*/
function getCurrencyAssetVarMin(bytes4 curr) external view returns(uint varMin) {
return allCurrencyAssets[curr].varMin;
}
/**
* @dev Gets base minimum of a given currency asset.
*/
function getCurrencyAssetBaseMin(bytes4 curr) external view returns(uint baseMin) {
return allCurrencyAssets[curr].baseMin;
}
/**
* @dev Gets investment asset maximum and minimum holding percentage of a given currency.
*/
function getInvestmentAssetHoldingPerc(
bytes4 curr
)
external
view
returns(
uint64 minHoldingPercX100,
uint64 maxHoldingPercX100
)
{
return (
allInvestmentAssets[curr].minHoldingPercX100,
allInvestmentAssets[curr].maxHoldingPercX100
);
}
/**
* @dev Gets investment asset decimals.
*/
function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) {
return allInvestmentAssets[curr].decimals;
}
/**
* @dev Gets investment asset maximum holding percentage of a given currency.
*/
function getInvestmentAssetMaxHoldingPerc(bytes4 curr) external view returns(uint64 maxHoldingPercX100) {
return allInvestmentAssets[curr].maxHoldingPercX100;
}
/**
* @dev Gets investment asset minimum holding percentage of a given currency.
*/
function getInvestmentAssetMinHoldingPerc(bytes4 curr) external view returns(uint64 minHoldingPercX100) {
return allInvestmentAssets[curr].minHoldingPercX100;
}
/**
* @dev Gets investment asset details of a given currency
*/
function getInvestmentAssetDetails(
bytes4 curr
)
external
view
returns(
bytes4 currency,
address currAddress,
bool status,
uint64 minHoldingPerc,
uint64 maxHoldingPerc,
uint8 decimals
)
{
return (
curr,
allInvestmentAssets[curr].currAddress,
allInvestmentAssets[curr].status,
allInvestmentAssets[curr].minHoldingPercX100,
allInvestmentAssets[curr].maxHoldingPercX100,
allInvestmentAssets[curr].decimals
);
}
/**
* @dev Gets Currency asset token address.
*/
function getCurrencyAssetAddress(bytes4 curr) external view returns(address) {
return allCurrencyAssets[curr].currAddress;
}
/**
* @dev Gets investment asset token address.
*/
function getInvestmentAssetAddress(bytes4 curr) external view returns(address) {
return allInvestmentAssets[curr].currAddress;
}
/**
* @dev Gets investment asset active Status of a given currency.
*/
function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) {
return allInvestmentAssets[curr].status;
}
/**
* @dev Gets type of oraclize query for a given Oraclize Query ID.
* @param myid Oraclize Query ID identifying the query for which the result is being received.
* @return _typeof It could be of type "quote","quotation","cover","claim" etc.
*/
function getApiIdTypeOf(bytes32 myid) external view returns(bytes4) {
return allAPIid[myid].typeOf;
}
/**
* @dev Gets ID associated to oraclize query for a given Oraclize Query ID.
* @param myid Oraclize Query ID identifying the query for which the result is being received.
* @return id1 It could be the ID of "proposal","quotation","cover","claim" etc.
*/
function getIdOfApiId(bytes32 myid) external view returns(uint) {
return allAPIid[myid].id;
}
/**
* @dev Gets the Timestamp of a oracalize call.
*/
function getDateAddOfAPI(bytes32 myid) external view returns(uint64) {
return allAPIid[myid].dateAdd;
}
/**
* @dev Gets the Timestamp at which result of oracalize call is received.
*/
function getDateUpdOfAPI(bytes32 myid) external view returns(uint64) {
return allAPIid[myid].dateUpd;
}
/**
* @dev Gets currency by oracalize id.
*/
function getCurrOfApiId(bytes32 myid) external view returns(bytes4) {
return allAPIid[myid].currency;
}
/**
* @dev Gets ID return by the oraclize query of a given index.
* @param index Index.
* @return myid ID return by the oraclize query.
*/
function getApiCallIndex(uint index) external view returns(bytes32 myid) {
myid = allAPIcall[index];
}
/**
* @dev Gets Length of API call.
*/
function getApilCallLength() external view returns(uint) {
return allAPIcall.length;
}
/**
* @dev Get Details of Oraclize API when given Oraclize Id.
* @param myid ID return by the oraclize query.
* @return _typeof ype of the query for which oraclize
* call is made.("proposal","quote","quotation" etc.)
*/
function getApiCallDetails(
bytes32 myid
)
external
view
returns(
bytes4 _typeof,
bytes4 curr,
uint id,
uint64 dateAdd,
uint64 dateUpd
)
{
return (
allAPIid[myid].typeOf,
allAPIid[myid].currency,
allAPIid[myid].id,
allAPIid[myid].dateAdd,
allAPIid[myid].dateUpd
);
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "MCRTIM") {
_changeMCRTime(val * 1 hours);
} else if (code == "MCRFTIM") {
_changeMCRFailTime(val * 1 hours);
} else if (code == "MCRMIN") {
_changeMinCap(val);
} else if (code == "MCRSHOCK") {
_changeShockParameter(val);
} else if (code == "MCRCAPL") {
_changeCapacityLimit(val);
} else if (code == "IMZ") {
_changeVariationPercX100(val);
} else if (code == "IMRATET") {
_changeIARatesTime(val * 1 hours);
} else if (code == "IMUNIDL") {
_changeUniswapDeadlineTime(val * 1 minutes);
} else if (code == "IMLIQT") {
_changeliquidityTradeCallbackTime(val * 1 hours);
} else if (code == "IMETHVL") {
_setEthVolumeLimit(val);
} else if (code == "C") {
_changeC(val);
} else if (code == "A") {
_changeA(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev to get the average rate of currency rate
* @param curr is the currency in concern
* @return required rate
*/
function getCAAvgRate(bytes4 curr) public view returns(uint rate) {
return _getAvgRate(curr, false);
}
/**
* @dev to get the average rate of investment rate
* @param curr is the investment in concern
* @return required rate
*/
function getIAAvgRate(bytes4 curr) public view returns(uint rate) {
return _getAvgRate(curr, true);
}
function changeDependentContractAddress() public onlyInternal {}
/// @dev Gets the average rate of a CA currency.
/// @param curr Currency Name.
/// @return rate Average rate X 100(of last 3 days).
function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) {
if (curr == "DAI") {
DSValue ds = DSValue(daiFeedAddress);
rate = uint(ds.read()).div(uint(10) ** 16);
} else if (isIA) {
rate = iaAvgRate[curr];
} else {
rate = caAvgRate[curr];
}
}
/**
* @dev to set the ethereum volume limit
* @param val is the new limit value
*/
function _setEthVolumeLimit(uint val) internal {
ethVolumeLimit = val;
}
/// @dev Sets minimum Cap.
function _changeMinCap(uint newCap) internal {
minCap = newCap;
}
/// @dev Sets Shock Parameter.
function _changeShockParameter(uint newParam) internal {
shockParameter = newParam;
}
/// @dev Changes time period for obtaining new MCR data from external oracle query.
function _changeMCRTime(uint _time) internal {
mcrTime = _time;
}
/// @dev Sets MCR Fail time.
function _changeMCRFailTime(uint _time) internal {
mcrFailTime = _time;
}
/**
* @dev to change the uniswap deadline time
* @param newDeadline is the value
*/
function _changeUniswapDeadlineTime(uint newDeadline) internal {
uniswapDeadline = newDeadline;
}
/**
* @dev to change the liquidity trade call back time
* @param newTime is the new value to be set
*/
function _changeliquidityTradeCallbackTime(uint newTime) internal {
liquidityTradeCallbackTime = newTime;
}
/**
* @dev Changes time after which investment asset rates need to be fed.
*/
function _changeIARatesTime(uint _newTime) internal {
iaRatesTime = _newTime;
}
/**
* @dev Changes the variation range percentage.
*/
function _changeVariationPercX100(uint newPercX100) internal {
variationPercX100 = newPercX100;
}
/// @dev Changes Growth Step
function _changeC(uint newC) internal {
c = newC;
}
/// @dev Changes scaling factor.
function _changeA(uint val) internal {
a = val;
}
/**
* @dev to change the capacity limit
* @param val is the new value
*/
function _changeCapacityLimit(uint val) internal {
capacityLimit = val;
}
}
// File: nexusmutual-contracts/contracts/QuotationData.sol
/* Copyright (C) 2017 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract QuotationData is Iupgradable {
using SafeMath for uint;
enum HCIDStatus { NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover }
enum CoverStatus { Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested }
struct Cover {
address payable memberAddress;
bytes4 currencyCode;
uint sumAssured;
uint16 coverPeriod;
uint validUntil;
address scAddress;
uint premiumNXM;
}
struct HoldCover {
uint holdCoverId;
address payable userAddress;
address scAddress;
bytes4 coverCurr;
uint[] coverDetails;
uint16 coverPeriod;
}
address public authQuoteEngine;
mapping(bytes4 => uint) internal currencyCSA;
mapping(address => uint[]) internal userCover;
mapping(address => uint[]) public userHoldedCover;
mapping(address => bool) public refundEligible;
mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd;
mapping(uint => uint8) public coverStatus;
mapping(uint => uint) public holdedCoverIDStatus;
mapping(uint => bool) public timestampRepeated;
Cover[] internal allCovers;
HoldCover[] internal allCoverHolded;
uint public stlp;
uint public stl;
uint public pm;
uint public minDays;
uint public tokensRetained;
address public kycAuthAddress;
event CoverDetailsEvent(
uint indexed cid,
address scAdd,
uint sumAssured,
uint expiry,
uint premium,
uint premiumNXM,
bytes4 curr
);
event CoverStatusEvent(uint indexed cid, uint8 statusNum);
constructor(address _authQuoteAdd, address _kycAuthAdd) public {
authQuoteEngine = _authQuoteAdd;
kycAuthAddress = _kycAuthAdd;
stlp = 90;
stl = 100;
pm = 30;
minDays = 30;
tokensRetained = 10;
allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0));
uint[] memory arr = new uint[](1);
allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0));
}
/// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be added.
function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/// @dev Adds the amount in Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be added.
function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/// @dev sets bit for timestamp to avoid replay attacks.
function setTimestampRepeated(uint _timestamp) external onlyInternal {
timestampRepeated[_timestamp] = true;
}
/// @dev Creates a blank new cover.
function addCover(
uint16 _coverPeriod,
uint _sumAssured,
address payable _userAddress,
bytes4 _currencyCode,
address _scAddress,
uint premium,
uint premiumNXM
)
external
onlyInternal
{
uint expiryDate = now.add(uint(_coverPeriod).mul(1 days));
allCovers.push(Cover(_userAddress, _currencyCode,
_sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM));
uint cid = allCovers.length.sub(1);
userCover[_userAddress].push(cid);
emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode);
}
/// @dev create holded cover which will process after verdict of KYC.
function addHoldCover(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] calldata coverDetails,
uint16 coverPeriod
)
external
onlyInternal
{
uint holdedCoverLen = allCoverHolded.length;
holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending);
allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress,
coverCurr, coverDetails, coverPeriod));
userHoldedCover[from].push(allCoverHolded.length.sub(1));
}
///@dev sets refund eligible bit.
///@param _add user address.
///@param status indicates if user have pending kyc.
function setRefundEligible(address _add, bool status) external onlyInternal {
refundEligible[_add] = status;
}
/// @dev to set current status of particular holded coverID (1 for not completed KYC,
/// 2 for KYC passed, 3 for failed KYC or full refunded,
/// 4 for KYC completed but cover not processed)
function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal {
holdedCoverIDStatus[holdedCoverID] = status;
}
/**
* @dev to set address of kyc authentication
* @param _add is the new address
*/
function setKycAuthAddress(address _add) external onlyInternal {
kycAuthAddress = _add;
}
/// @dev Changes authorised address for generating quote off chain.
function changeAuthQuoteEngine(address _add) external onlyInternal {
authQuoteEngine = _add;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) {
codeVal = code;
if (code == "STLP") {
val = stlp;
} else if (code == "STL") {
val = stl;
} else if (code == "PM") {
val = pm;
} else if (code == "QUOMIND") {
val = minDays;
} else if (code == "QUOTOK") {
val = tokensRetained;
}
}
/// @dev Gets Product details.
/// @return _minDays minimum cover period.
/// @return _PM Profit margin.
/// @return _STL short term Load.
/// @return _STLP short term load period.
function getProductDetails()
external
view
returns (
uint _minDays,
uint _pm,
uint _stl,
uint _stlp
)
{
_minDays = minDays;
_pm = pm;
_stl = stl;
_stlp = stlp;
}
/// @dev Gets total number covers created till date.
function getCoverLength() external view returns(uint len) {
return (allCovers.length);
}
/// @dev Gets Authorised Engine address.
function getAuthQuoteEngine() external view returns(address _add) {
_add = authQuoteEngine;
}
/// @dev Gets the Total Sum Assured amount of a given currency.
function getTotalSumAssured(bytes4 _curr) external view returns(uint amount) {
amount = currencyCSA[_curr];
}
/// @dev Gets all the Cover ids generated by a given address.
/// @param _add User's address.
/// @return allCover array of covers.
function getAllCoversOfUser(address _add) external view returns(uint[] memory allCover) {
return (userCover[_add]);
}
/// @dev Gets total number of covers generated by a given address
function getUserCoverLength(address _add) external view returns(uint len) {
len = userCover[_add].length;
}
/// @dev Gets the status of a given cover.
function getCoverStatusNo(uint _cid) external view returns(uint8) {
return coverStatus[_cid];
}
/// @dev Gets the Cover Period (in days) of a given cover.
function getCoverPeriod(uint _cid) external view returns(uint32 cp) {
cp = allCovers[_cid].coverPeriod;
}
/// @dev Gets the Sum Assured Amount of a given cover.
function getCoverSumAssured(uint _cid) external view returns(uint sa) {
sa = allCovers[_cid].sumAssured;
}
/// @dev Gets the Currency Name in which a given cover is assured.
function getCurrencyOfCover(uint _cid) external view returns(bytes4 curr) {
curr = allCovers[_cid].currencyCode;
}
/// @dev Gets the validity date (timestamp) of a given cover.
function getValidityOfCover(uint _cid) external view returns(uint date) {
date = allCovers[_cid].validUntil;
}
/// @dev Gets Smart contract address of cover.
function getscAddressOfCover(uint _cid) external view returns(uint, address) {
return (_cid, allCovers[_cid].scAddress);
}
/// @dev Gets the owner address of a given cover.
function getCoverMemberAddress(uint _cid) external view returns(address payable _add) {
_add = allCovers[_cid].memberAddress;
}
/// @dev Gets the premium amount of a given cover in NXM.
function getCoverPremiumNXM(uint _cid) external view returns(uint _premiumNXM) {
_premiumNXM = allCovers[_cid].premiumNXM;
}
/// @dev Provides the details of a cover Id
/// @param _cid cover Id
/// @return memberAddress cover user address.
/// @return scAddress smart contract Address
/// @return currencyCode currency of cover
/// @return sumAssured sum assured of cover
/// @return premiumNXM premium in NXM
function getCoverDetailsByCoverID1(
uint _cid
)
external
view
returns (
uint cid,
address _memberAddress,
address _scAddress,
bytes4 _currencyCode,
uint _sumAssured,
uint premiumNXM
)
{
return (
_cid,
allCovers[_cid].memberAddress,
allCovers[_cid].scAddress,
allCovers[_cid].currencyCode,
allCovers[_cid].sumAssured,
allCovers[_cid].premiumNXM
);
}
/// @dev Provides details of a cover Id
/// @param _cid cover Id
/// @return status status of cover.
/// @return sumAssured Sum assurance of cover.
/// @return coverPeriod Cover Period of cover (in days).
/// @return validUntil is validity of cover.
function getCoverDetailsByCoverID2(
uint _cid
)
external
view
returns (
uint cid,
uint8 status,
uint sumAssured,
uint16 coverPeriod,
uint validUntil
)
{
return (
_cid,
coverStatus[_cid],
allCovers[_cid].sumAssured,
allCovers[_cid].coverPeriod,
allCovers[_cid].validUntil
);
}
/// @dev Provides details of a holded cover Id
/// @param _hcid holded cover Id
/// @return scAddress SmartCover address of cover.
/// @return coverCurr currency of cover.
/// @return coverPeriod Cover Period of cover (in days).
function getHoldedCoverDetailsByID1(
uint _hcid
)
external
view
returns (
uint hcid,
address scAddress,
bytes4 coverCurr,
uint16 coverPeriod
)
{
return (
_hcid,
allCoverHolded[_hcid].scAddress,
allCoverHolded[_hcid].coverCurr,
allCoverHolded[_hcid].coverPeriod
);
}
/// @dev Gets total number holded covers created till date.
function getUserHoldedCoverLength(address _add) external view returns (uint) {
return userHoldedCover[_add].length;
}
/// @dev Gets holded cover index by index of user holded covers.
function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) {
return userHoldedCover[_add][index];
}
/// @dev Provides the details of a holded cover Id
/// @param _hcid holded cover Id
/// @return memberAddress holded cover user address.
/// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute.
function getHoldedCoverDetailsByID2(
uint _hcid
)
external
view
returns (
uint hcid,
address payable memberAddress,
uint[] memory coverDetails
)
{
return (
_hcid,
allCoverHolded[_hcid].userAddress,
allCoverHolded[_hcid].coverDetails
);
}
/// @dev Gets the Total Sum Assured amount of a given currency and smart contract address.
function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns(uint amount) {
amount = currencyCSAOfSCAdd[_add][_curr];
}
//solhint-disable-next-line
function changeDependentContractAddress() public {}
/// @dev Changes the status of a given cover.
/// @param _cid cover Id.
/// @param _stat New status.
function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal {
coverStatus[_cid] = _stat;
emit CoverStatusEvent(_cid, _stat);
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "STLP") {
_changeSTLP(val);
} else if (code == "STL") {
_changeSTL(val);
} else if (code == "PM") {
_changePM(val);
} else if (code == "QUOMIND") {
_changeMinDays(val);
} else if (code == "QUOTOK") {
_setTokensRetained(val);
} else {
revert("Invalid param code");
}
}
/// @dev Changes the existing Profit Margin value
function _changePM(uint _pm) internal {
pm = _pm;
}
/// @dev Changes the existing Short Term Load Period (STLP) value.
function _changeSTLP(uint _stlp) internal {
stlp = _stlp;
}
/// @dev Changes the existing Short Term Load (STL) value.
function _changeSTL(uint _stl) internal {
stl = _stl;
}
/// @dev Changes the existing Minimum cover period (in days)
function _changeMinDays(uint _days) internal {
minDays = _days;
}
/**
* @dev to set the the amount of tokens retained
* @param val is the amount retained
*/
function _setTokensRetained(uint val) internal {
tokensRetained = val;
}
}
// File: nexusmutual-contracts/contracts/TokenData.sol
/* Copyright (C) 2017 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract TokenData is Iupgradable {
using SafeMath for uint;
address payable public walletAddress;
uint public lockTokenTimeAfterCoverExp;
uint public bookTime;
uint public lockCADays;
uint public lockMVDays;
uint public scValidDays;
uint public joiningFee;
uint public stakerCommissionPer;
uint public stakerMaxCommissionPer;
uint public tokenExponent;
uint public priceStep;
struct StakeCommission {
uint commissionEarned;
uint commissionRedeemed;
}
struct Stake {
address stakedContractAddress;
uint stakedContractIndex;
uint dateAdd;
uint stakeAmount;
uint unlockedAmount;
uint burnedAmount;
uint unLockableBeforeLastBurn;
}
struct Staker {
address stakerAddress;
uint stakerIndex;
}
struct CoverNote {
uint amount;
bool isDeposited;
}
/**
* @dev mapping of uw address to array of sc address to fetch
* all staked contract address of underwriter, pushing
* data into this array of Stake returns stakerIndex
*/
mapping(address => Stake[]) public stakerStakedContracts;
/**
* @dev mapping of sc address to array of UW address to fetch
* all underwritters of the staked smart contract
* pushing data into this mapped array returns scIndex
*/
mapping(address => Staker[]) public stakedContractStakers;
/**
* @dev mapping of staked contract Address to the array of StakeCommission
* here index of this array is stakedContractIndex
*/
mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission;
mapping(address => uint) public lastCompletedStakeCommission;
/**
* @dev mapping of the staked contract address to the current
* staker index who will receive commission.
*/
mapping(address => uint) public stakedContractCurrentCommissionIndex;
/**
* @dev mapping of the staked contract address to the
* current staker index to burn token from.
*/
mapping(address => uint) public stakedContractCurrentBurnIndex;
/**
* @dev mapping to return true if Cover Note deposited against coverId
*/
mapping(uint => CoverNote) public depositedCN;
mapping(address => uint) internal isBookedTokens;
event Commission(
address indexed stakedContractAddress,
address indexed stakerAddress,
uint indexed scIndex,
uint commissionAmount
);
constructor(address payable _walletAdd) public {
walletAddress = _walletAdd;
bookTime = 12 hours;
joiningFee = 2000000000000000; // 0.002 Ether
lockTokenTimeAfterCoverExp = 35 days;
scValidDays = 250;
lockCADays = 7 days;
lockMVDays = 2 days;
stakerCommissionPer = 20;
stakerMaxCommissionPer = 50;
tokenExponent = 4;
priceStep = 1000;
}
/**
* @dev Change the wallet address which receive Joining Fee
*/
function changeWalletAddress(address payable _address) external onlyInternal {
walletAddress = _address;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) {
codeVal = code;
if (code == "TOKEXP") {
val = tokenExponent;
} else if (code == "TOKSTEP") {
val = priceStep;
} else if (code == "RALOCKT") {
val = scValidDays;
} else if (code == "RACOMM") {
val = stakerCommissionPer;
} else if (code == "RAMAXC") {
val = stakerMaxCommissionPer;
} else if (code == "CABOOKT") {
val = bookTime / (1 hours);
} else if (code == "CALOCKT") {
val = lockCADays / (1 days);
} else if (code == "MVLOCKT") {
val = lockMVDays / (1 days);
} else if (code == "QUOLOCKT") {
val = lockTokenTimeAfterCoverExp / (1 days);
} else if (code == "JOINFEE") {
val = joiningFee;
}
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public { //solhint-disable-line
}
/**
* @dev to get the contract staked by a staker
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return the address of staked contract
*/
function getStakerStakedContractByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (address stakedContractAddress)
{
stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
}
/**
* @dev to get the staker's staked burned
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount burned
*/
function getStakerStakedBurnedByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint burnedAmount)
{
burnedAmount = stakerStakedContracts[
_stakerAddress][_stakerIndex].burnedAmount;
}
/**
* @dev to get the staker's staked unlockable before the last burn
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return unlockable staked tokens
*/
function getStakerStakedUnlockableBeforeLastBurnByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint unlockable)
{
unlockable = stakerStakedContracts[
_stakerAddress][_stakerIndex].unLockableBeforeLastBurn;
}
/**
* @dev to get the staker's staked contract index
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return is the index of the smart contract address
*/
function getStakerStakedContractIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint scIndex)
{
scIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
}
/**
* @dev to get the staker index of the staked contract
* @param _stakedContractAddress is the address of the staked contract
* @param _stakedContractIndex is the index of staked contract
* @return is the index of the staker
*/
function getStakedContractStakerIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (uint sIndex)
{
sIndex = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerIndex;
}
/**
* @dev to get the staker's initial staked amount on the contract
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return staked amount
*/
function getStakerInitialStakedAmountOnContract(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakeAmount;
}
/**
* @dev to get the staker's staked contract length
* @param _stakerAddress is the address of the staker
* @return length of staked contract
*/
function getStakerStakedContractLength(
address _stakerAddress
)
public
view
returns (uint length)
{
length = stakerStakedContracts[_stakerAddress].length;
}
/**
* @dev to get the staker's unlocked tokens which were staked
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount
*/
function getStakerUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].unlockedAmount;
}
/**
* @dev pushes the unlocked staked tokens by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev pushes the Burned tokens for a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be burned.
*/
function pushBurnedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev pushes the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function pushUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev sets the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function setUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = _amount;
}
/**
* @dev pushes the earned commission earned by a staker.
* @param _stakerAddress address of staker.
* @param _stakedContractAddress address of smart contract.
* @param _stakedContractIndex index of the staker to distribute commission.
* @param _commissionAmount amount to be given as commission.
*/
function pushEarnedStakeCommissions(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _commissionAmount
)
public
onlyInternal
{
stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex].
commissionEarned = stakedContractStakeCommission[_stakedContractAddress][
_stakedContractIndex].commissionEarned.add(_commissionAmount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Commission(
_stakerAddress,
_stakedContractAddress,
_stakedContractIndex,
_commissionAmount
);
}
/**
* @dev pushes the redeemed commission redeemed by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushRedeemedStakeCommissions(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
uint stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
address stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
stakedContractStakeCommission[stakedContractAddress][stakedContractIndex].
commissionRedeemed = stakedContractStakeCommission[
stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @dev Gets stake commission given to an underwriter
* for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets stake commission redeemed by an underwriter
* for particular staked contract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
* @return commissionEarned total amount given to staker.
*/
function getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalEarnedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionEarned)
{
totalCommissionEarned = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionEarned = totalCommissionEarned.
add(_getStakerEarnedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalReedmedStakeCommission(
address _stakerAddress
)
public
view
returns(uint totalCommissionRedeemed)
{
totalCommissionRedeemed = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionRedeemed = totalCommissionRedeemed.add(
_getStakerRedeemedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev set flag to deposit/ undeposit cover note
* against a cover Id
* @param coverId coverId of Cover
* @param flag true/false for deposit/undeposit
*/
function setDepositCN(uint coverId, bool flag) public onlyInternal {
if (flag == true) {
require(!depositedCN[coverId].isDeposited, "Cover note already deposited");
}
depositedCN[coverId].isDeposited = flag;
}
/**
* @dev set locked cover note amount
* against a cover Id
* @param coverId coverId of Cover
* @param amount amount of nxm to be locked
*/
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal {
depositedCN[coverId].amount = amount;
}
/**
* @dev to get the staker address on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @param _stakedContractIndex is the index of staked contract's index
* @return address of staker
*/
function getStakedContractStakerByIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (address stakerAddress)
{
stakerAddress = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerAddress;
}
/**
* @dev to get the length of stakers on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @return length in concern
*/
function getStakedContractStakersLength(
address _stakedContractAddress
)
public
view
returns (uint length)
{
length = stakedContractStakers[_stakedContractAddress].length;
}
/**
* @dev Adds a new stake record.
* @param _stakerAddress staker address.
* @param _stakedContractAddress smart contract address.
* @param _amount amountof NXM to be staked.
*/
function addStake(
address _stakerAddress,
address _stakedContractAddress,
uint _amount
)
public
onlyInternal
returns(uint scIndex)
{
scIndex = (stakedContractStakers[_stakedContractAddress].push(
Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1);
stakerStakedContracts[_stakerAddress].push(
Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0));
}
/**
* @dev books the user's tokens for maintaining Assessor Velocity,
* i.e. once a token is used to cast a vote as a Claims assessor,
* @param _of user's address.
*/
function bookCATokens(address _of) public onlyInternal {
require(!isCATokensBooked(_of), "Tokens already booked");
isBookedTokens[_of] = now.add(bookTime);
}
/**
* @dev to know if claim assessor's tokens are booked or not
* @param _of is the claim assessor's address in concern
* @return boolean representing the status of tokens booked
*/
function isCATokensBooked(address _of) public view returns(bool res) {
if (now < isBookedTokens[_of])
res = true;
}
/**
* @dev Sets the index which will receive commission.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentCommissionIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index;
}
/**
* @dev Sets the last complete commission index
* @param _stakerAddress smart contract address.
* @param _index current index.
*/
function setLastCompletedStakeCommissionIndex(
address _stakerAddress,
uint _index
)
public
onlyInternal
{
lastCompletedStakeCommission[_stakerAddress] = _index;
}
/**
* @dev Sets the index till which commission is distrubuted.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentBurnIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentBurnIndex[_stakedContractAddress] = _index;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "TOKEXP") {
_setTokenExponent(val);
} else if (code == "TOKSTEP") {
_setPriceStep(val);
} else if (code == "RALOCKT") {
_changeSCValidDays(val);
} else if (code == "RACOMM") {
_setStakerCommissionPer(val);
} else if (code == "RAMAXC") {
_setStakerMaxCommissionPer(val);
} else if (code == "CABOOKT") {
_changeBookTime(val * 1 hours);
} else if (code == "CALOCKT") {
_changelockCADays(val * 1 days);
} else if (code == "MVLOCKT") {
_changelockMVDays(val * 1 days);
} else if (code == "QUOLOCKT") {
_setLockTokenTimeAfterCoverExp(val * 1 days);
} else if (code == "JOINFEE") {
_setJoiningFee(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev Internal function to get stake commission given to an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionEarned;
}
/**
* @dev Internal function to get stake commission redeemed by an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionRedeemed;
}
/**
* @dev to set the percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerCommissionPer(uint _val) internal {
stakerCommissionPer = _val;
}
/**
* @dev to set the max percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerMaxCommissionPer(uint _val) internal {
stakerMaxCommissionPer = _val;
}
/**
* @dev to set the token exponent value
* @param _val is new value
*/
function _setTokenExponent(uint _val) internal {
tokenExponent = _val;
}
/**
* @dev to set the price step
* @param _val is new value
*/
function _setPriceStep(uint _val) internal {
priceStep = _val;
}
/**
* @dev Changes number of days for which NXM needs to staked in case of underwriting
*/
function _changeSCValidDays(uint _days) internal {
scValidDays = _days;
}
/**
* @dev Changes the time period up to which tokens will be locked.
* Used to generate the validity period of tokens booked by
* a user for participating in claim's assessment/claim's voting.
*/
function _changeBookTime(uint _time) internal {
bookTime = _time;
}
/**
* @dev Changes lock CA days - number of days for which tokens
* are locked while submitting a vote.
*/
function _changelockCADays(uint _val) internal {
lockCADays = _val;
}
/**
* @dev Changes lock MV days - number of days for which tokens are locked
* while submitting a vote.
*/
function _changelockMVDays(uint _val) internal {
lockMVDays = _val;
}
/**
* @dev Changes extra lock period for a cover, post its expiry.
*/
function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
/**
* @dev Set the joining fee for membership
*/
function _setJoiningFee(uint _amount) internal {
joiningFee = _amount;
}
}
// File: nexusmutual-contracts/contracts/external/oraclize/ethereum-api/usingOraclize.sol
/*
ORACLIZE_API
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
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.0 < 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI!
// Dummy contract only used to emit to end-user they are using wrong solc
contract solcChecker {
/* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external;
}
contract OraclizeI {
address public cbAddress;
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function getPrice(string memory _datasource) public returns (uint _dsprice);
function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash);
function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice);
function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id);
function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id);
function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _address);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
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.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory _buf, uint _capacity) internal pure {
uint capacity = _capacity;
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
_buf.capacity = capacity; // Allocate space for the buffer data
assembly {
let ptr := mload(0x40)
mstore(_buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory _buf, uint _capacity) private pure {
bytes memory oldbuf = _buf.buf;
init(_buf, _capacity);
append(_buf, oldbuf);
}
function max(uint _a, uint _b) private pure returns (uint _max) {
if (_a > _b) {
return _a;
}
return _b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) {
if (_data.length + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _data.length) * 2);
}
uint dest;
uint src;
uint len = _data.length;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length)
mstore(bufptr, add(buflen, mload(_data))) // Update buffer length
src := add(_data, 32)
}
for(; len >= 32; len -= 32) { // Copy word-length chunks while possible
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return _buf;
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(buffer memory _buf, uint8 _data) internal pure {
if (_buf.buf.length + 1 > _buf.capacity) {
resize(_buf, _buf.capacity * 2);
}
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)
mstore8(dest, _data)
mstore(bufptr, add(buflen, 1)) // Update buffer length
}
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) {
if (_len + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _len) * 2);
}
uint mask = 256 ** _len - 1;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len
mstore(dest, or(and(mload(dest), not(mask)), _data))
mstore(bufptr, add(buflen, _len)) // Update buffer length
}
return _buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure {
if (_value <= 23) {
_buf.append(uint8((_major << 5) | _value));
} else if (_value <= 0xFF) {
_buf.append(uint8((_major << 5) | 24));
_buf.appendInt(_value, 1);
} else if (_value <= 0xFFFF) {
_buf.append(uint8((_major << 5) | 25));
_buf.appendInt(_value, 2);
} else if (_value <= 0xFFFFFFFF) {
_buf.append(uint8((_major << 5) | 26));
_buf.appendInt(_value, 4);
} else if (_value <= 0xFFFFFFFFFFFFFFFF) {
_buf.append(uint8((_major << 5) | 27));
_buf.appendInt(_value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure {
_buf.append(uint8((_major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure {
encodeType(_buf, MAJOR_TYPE_INT, _value);
}
function encodeInt(Buffer.buffer memory _buf, int _value) internal pure {
if (_value >= 0) {
encodeType(_buf, MAJOR_TYPE_INT, uint(_value));
} else {
encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value));
}
}
function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_BYTES, _value.length);
_buf.append(_value);
}
function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length);
_buf.append(bytes(_value));
}
function startArray(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
using CBOR for Buffer.buffer;
OraclizeI oraclize;
OraclizeAddrResolverI OAR;
uint constant day = 60 * 60 * 24;
uint constant week = 60 * 60 * 24 * 7;
uint constant month = 60 * 60 * 24 * 30;
byte constant proofType_NONE = 0x00;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
byte constant proofType_Android = 0x40;
byte constant proofType_TLSNotary = 0x10;
string oraclize_network_name;
uint8 constant networkID_auto = 0;
uint8 constant networkID_morden = 2;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_consensys = 161;
mapping(bytes32 => bytes32) oraclize_randomDS_args;
mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified;
modifier oraclizeAPI {
if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) {
oraclize_setNetwork(networkID_auto);
}
if (address(oraclize) != OAR.getAddress()) {
oraclize = OraclizeI(OAR.getAddress());
}
_;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) {
// RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1)));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) {
return oraclize_setNetwork();
_networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetworkName(string memory _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string memory _networkName) {
return oraclize_network_name;
}
function oraclize_setNetwork() internal returns (bool _networkSet) {
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet
OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41);
oraclize_setNetworkName("eth_goerli");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 _myid, string memory _result) public {
__callback(_myid, _result, new bytes(0));
}
function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public {
return;
_myid; _result; _proof; // Silence compiler warnings
}
function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) {
return oraclize.getPrice(_datasource);
}
function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) {
return oraclize.getPrice(_datasource, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query.value(price)(0, _datasource, _arg);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query.value(price)(_timestamp, _datasource, _arg);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource,_gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query_withGasLimit.value(price)(_timestamp, _datasource, _arg, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query_withGasLimit.value(price)(0, _datasource, _arg, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query2.value(price)(0, _datasource, _arg1, _arg2);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query2.value(price)(_timestamp, _datasource, _arg1, _arg2);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query2_withGasLimit.value(price)(_timestamp, _datasource, _arg1, _arg2, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query2_withGasLimit.value(price)(0, _datasource, _arg1, _arg2, _gasLimit);
}
function oraclize_query(string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN.value(price)(0, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN.value(price)(_timestamp, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN.value(price)(0, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN.value(price)(_timestamp, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_setProof(byte _proofP) oraclizeAPI internal {
return oraclize.setProofType(_proofP);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) {
return oraclize.cbAddress();
}
function getCodeSize(address _addr) view internal returns (uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(_gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) {
return oraclize.randomDS_getSessionPubKeyHash();
}
function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i = 2; i < 2 + 2 * 20; i += 2) {
iaddr *= 256;
b1 = uint160(uint8(tmp[i]));
b2 = uint160(uint8(tmp[i + 1]));
if ((b1 >= 97) && (b1 <= 102)) {
b1 -= 87;
} else if ((b1 >= 65) && (b1 <= 70)) {
b1 -= 55;
} else if ((b1 >= 48) && (b1 <= 57)) {
b1 -= 48;
}
if ((b2 >= 97) && (b2 <= 102)) {
b2 -= 87;
} else if ((b2 >= 65) && (b2 <= 70)) {
b2 -= 55;
} else if ((b2 >= 48) && (b2 <= 57)) {
b2 -= 48;
}
iaddr += (b1 * 16 + b2);
}
return address(iaddr);
}
function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) {
minLength = b.length;
}
for (uint i = 0; i < minLength; i ++) {
if (a[i] < b[i]) {
return -1;
} else if (a[i] > b[i]) {
return 1;
}
}
if (a.length < b.length) {
return -1;
} else if (a.length > b.length) {
return 1;
} else {
return 0;
}
}
function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if (h.length < 1 || n.length < 1 || (n.length > h.length)) {
return -1;
} else if (h.length > (2 ** 128 - 1)) {
return -1;
} else {
uint subindex = 0;
for (uint i = 0; i < h.length; i++) {
if (h[i] == n[0]) {
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) {
subindex++;
}
if (subindex == n.length) {
return int(i);
}
}
}
return -1;
}
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, "", "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {
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;
uint i = 0;
for (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 safeParseInt(string memory _a) internal pure returns (uint _parsedInt) {
return safeParseInt(_a, 0);
}
function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
require(!decimals, 'More than one decimal encountered in string!');
decimals = true;
} else {
revert("Non-numeral character encountered in string!");
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function parseInt(string memory _a) internal pure returns (uint _parsedInt) {
return parseInt(_a, 0);
}
function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) {
break;
} else {
_b--;
}
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
decimals = true;
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeString(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeBytes(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) {
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10; // Convert from seconds to ledger timer ticks
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(uint8(_nbytes));
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
/*
The following variables can be relaxed.
Check the relaxed random contract at https://github.com/oraclize/ethereum-examples
for an idea on how to override and replace commit hash variables.
*/
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal {
oraclize_randomDS_args[_queryId] = _commitment;
}
function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) {
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20);
sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs);
if (address(uint160(uint256(keccak256(_pubkey)))) == signer) {
return true;
} else {
(sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs);
return (address(uint160(uint256(keccak256(_pubkey)))) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) {
bool sigok;
// Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2);
copyBytes(_proof, _sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1 + 65 + 32);
tosign2[0] = byte(uint8(1)); //role
copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (!sigok) {
return false;
}
// Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1 + 65);
tosign3[0] = 0xFE;
copyBytes(_proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2);
copyBytes(_proof, 3 + 65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) {
// Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) {
return 1;
}
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (!proofVerified) {
return 2;
}
return 0;
}
function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) {
bool match_ = true;
require(_prefix.length == _nRandomBytes);
for (uint256 i = 0; i< _nRandomBytes; i++) {
if (_content[i] != _prefix[i]) {
match_ = false;
}
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) {
// Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId)
uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32;
bytes memory keyhash = new bytes(32);
copyBytes(_proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) {
return false;
}
bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2);
copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0);
// Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) {
return false;
}
// Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8 + 1 + 32);
copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65;
copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[_queryId];
} else return false;
// Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32 + 8 + 1 + 32);
copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) {
return false;
}
// Verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) {
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
*/
function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) {
uint minLength = _length + _toOffset;
require(_to.length >= minLength); // Buffer too small. Should be a better way?
uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint j = 32 + _toOffset;
while (i < (32 + _fromOffset + _length)) {
assembly {
let tmp := mload(add(_from, i))
mstore(add(_to, j), tmp)
}
i += 32;
j += 32;
}
return _to;
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
Duplicate Solidity's ecrecover, but catching the CALL return value
*/
function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) {
/*
We do our own memory management here. Solidity uses memory offset
0x40 to store the current end of memory. We write past it (as
writes are memory extensions), but don't update the offset so
Solidity will reuse it. The memory used here is only needed for
this context.
FIXME: inline assembly can't access return values
*/
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, _hash)
mstore(add(size, 32), _v)
mstore(add(size, 64), _r)
mstore(add(size, 96), _s)
ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code.
addr := mload(size)
}
return (ret, addr);
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
*/
function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
return (false, address(0));
}
/*
The signature format is a compact form of:
{bytes32 r}{bytes32 s}{uint8 v}
Compact means, uint8 is not padded to 32 bytes.
*/
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
/*
Here we are loading the last 32 bytes. We exploit the fact that
'mload' will pad with zeroes if we overread.
There is no 'mload8' to do this, but that would be nicer.
*/
v := byte(0, mload(add(_sig, 96)))
/*
Alternative solution:
'byte' is not working due to the Solidity parser, so lets
use the second best option, 'and'
v := and(mload(add(_sig, 65)), 255)
*/
}
/*
albeit non-transactional signatures are not specified by the YP, one would expect it
to match the YP range of [27, 28]
geth uses [0, 1] and some clients have followed. This might change, see:
https://github.com/ethereum/go-ethereum/issues/2053
*/
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (false, address(0));
}
return safer_ecrecover(_hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
/*
END ORACLIZE_API
*/
// File: nexusmutual-contracts/contracts/Quotation.sol
/* Copyright (C) 2017 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract Quotation is Iupgradable {
using SafeMath for uint;
TokenFunctions internal tf;
TokenController internal tc;
TokenData internal td;
Pool1 internal p1;
PoolData internal pd;
QuotationData internal qd;
MCR internal m1;
MemberRoles internal mr;
bool internal locked;
event RefundEvent(address indexed user, bool indexed status, uint holdedCoverID, bytes32 reason);
modifier noReentrancy() {
require(!locked, "Reentrant call.");
locked = true;
_;
locked = false;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
m1 = MCR(ms.getLatestAddress("MC"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
qd = QuotationData(ms.getLatestAddress("QD"));
p1 = Pool1(ms.getLatestAddress("P1"));
pd = PoolData(ms.getLatestAddress("PD"));
mr = MemberRoles(ms.getLatestAddress("MR"));
}
function sendEther() public payable {
}
/**
* @dev Expires a cover after a set period of time.
* Changes the status of the Cover and reduces the current
* sum assured of all areas in which the quotation lies
* Unlocks the CN tokens of the cover. Updates the Total Sum Assured value.
* @param _cid Cover Id.
*/
function expireCover(uint _cid) public {
require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired));
tf.unlockCN(_cid);
bytes4 curr;
address scAddress;
uint sumAssured;
(, , scAddress, curr, sumAssured, ) = qd.getCoverDetailsByCoverID1(_cid);
if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted))
_removeSAFromCSA(_cid, sumAssured);
qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired));
}
/**
* @dev Checks if a cover should get expired/closed or not.
* @param _cid Cover Index.
* @return expire true if the Cover's time has expired, false otherwise.
*/
function checkCoverExpired(uint _cid) public view returns(bool expire) {
expire = qd.getValidityOfCover(_cid) < uint64(now);
}
/**
* @dev Updates the Sum Assured Amount of all the quotation.
* @param _cid Cover id
* @param _amount that will get subtracted Current Sum Assured
* amount that comes under a quotation.
*/
function removeSAFromCSA(uint _cid, uint _amount) public onlyInternal {
_removeSAFromCSA(_cid, _amount);
}
/**
* @dev Makes Cover funded via NXM tokens.
* @param smartCAdd Smart Contract Address
*/
function makeCoverUsingNXMTokens(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 coverCurr,
address smartCAdd,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
isMemberAndcheckPause
{
tc.burnFrom(msg.sender, coverDetails[2]); //need burn allowance
_verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @dev Verifies cover details signed off chain.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
onlyInternal
{
_verifyCoverDetails(
from,
scAddress,
coverCurr,
coverDetails,
coverPeriod,
_v,
_r,
_s
);
}
/**
* @dev Verifies signature.
* @param coverDetails details related to cover.
* @param coverPeriod validity of cover.
* @param smaratCA smarat contract address.
* @param _v argument from vrs hash.
* @param _r argument from vrs hash.
* @param _s argument from vrs hash.
*/
function verifySign(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 curr,
address smaratCA,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
view
returns(bool)
{
require(smaratCA != address(0));
require(pd.capReached() == 1, "Can not buy cover until cap reached for 1st time");
bytes32 hash = getOrderHash(coverDetails, coverPeriod, curr, smaratCA);
return isValidSignature(hash, _v, _r, _s);
}
/**
* @dev Gets order hash for given cover details.
* @param coverDetails details realted to cover.
* @param coverPeriod validity of cover.
* @param smaratCA smarat contract address.
*/
function getOrderHash(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 curr,
address smaratCA
)
public
view
returns(bytes32)
{
return keccak256(
abi.encodePacked(
coverDetails[0],
curr, coverPeriod,
smaratCA,
coverDetails[1],
coverDetails[2],
coverDetails[3],
coverDetails[4],
address(this)
)
);
}
/**
* @dev Verifies signature.
* @param hash order hash
* @param v argument from vrs hash.
* @param r argument from vrs hash.
* @param s argument from vrs hash.
*/
function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns(bool) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
address a = ecrecover(prefixedHash, v, r, s);
return (a == qd.getAuthQuoteEngine());
}
/**
* @dev to get the status of recently holded coverID
* @param userAdd is the user address in concern
* @return the status of the concerned coverId
*/
function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) {
uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd);
if (holdedCoverLen == 0) {
return -1;
} else {
uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1));
return int(qd.holdedCoverIDStatus(holdedCoverID));
}
}
/**
* @dev to initiate the membership and the cover
* @param smartCAdd is the smart contract address to make cover on
* @param coverCurr is the currency used to make cover
* @param coverDetails list of details related to cover like cover amount, expire time, coverCurrPrice and priceNXM
* @param coverPeriod is cover period for which cover is being bought
* @param _v argument from vrs hash
* @param _r argument from vrs hash
* @param _s argument from vrs hash
*/
function initiateMembershipAndCover(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
payable
checkPause
{
require(coverDetails[3] > now);
require(!qd.timestampRepeated(coverDetails[4]));
qd.setTimestampRepeated(coverDetails[4]);
require(!ms.isMember(msg.sender));
require(qd.refundEligible(msg.sender) == false);
uint joinFee = td.joiningFee();
uint totalFee = joinFee;
if (coverCurr == "ETH") {
totalFee = joinFee.add(coverDetails[1]);
} else {
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr));
require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]));
}
require(msg.value == totalFee);
require(verifySign(coverDetails, coverPeriod, coverCurr, smartCAdd, _v, _r, _s));
qd.addHoldCover(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod);
qd.setRefundEligible(msg.sender, true);
}
/**
* @dev to get the verdict of kyc process
* @param status is the kyc status
* @param _add is the address of member
*/
function kycVerdict(address _add, bool status) public checkPause noReentrancy {
require(msg.sender == qd.kycAuthAddress());
_kycTrigger(status, _add);
}
/**
* @dev transfering Ethers to newly created quotation contract.
*/
function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy {
uint amount = address(this).balance;
IERC20 erc20;
if (amount > 0) {
// newAdd.transfer(amount);
Quotation newQT = Quotation(newAdd);
newQT.sendEther.value(amount)();
}
uint currAssetLen = pd.getAllCurrenciesLen();
for (uint64 i = 1; i < currAssetLen; i++) {
bytes4 currName = pd.getCurrenciesByIndex(i);
address currAddr = pd.getCurrencyAssetAddress(currName);
erc20 = IERC20(currAddr); //solhint-disable-line
if (erc20.balanceOf(address(this)) > 0) {
require(erc20.transfer(newAdd, erc20.balanceOf(address(this))));
}
}
}
/**
* @dev Creates cover of the quotation, changes the status of the quotation ,
* updates the total sum assured and locks the tokens of the cover against a quote.
* @param from Quote member Ethereum address.
*/
function _makeCover ( //solhint-disable-line
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod
)
internal
{
uint cid = qd.getCoverLength();
qd.addCover(coverPeriod, coverDetails[0],
from, coverCurr, scAddress, coverDetails[1], coverDetails[2]);
// if cover period of quote is less than 60 days.
if (coverPeriod <= 60) {
p1.closeCoverOraclise(cid, uint64(uint(coverPeriod).mul(1 days)));
}
uint coverNoteAmount = (coverDetails[2].mul(qd.tokensRetained())).div(100);
tc.mint(from, coverNoteAmount);
tf.lockCN(coverNoteAmount, coverPeriod, cid, from);
qd.addInTotalSumAssured(coverCurr, coverDetails[0]);
qd.addInTotalSumAssuredSC(scAddress, coverCurr, coverDetails[0]);
tf.pushStakerRewards(scAddress, coverDetails[2]);
}
/**
* @dev Makes a vover.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function _verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
internal
{
require(coverDetails[3] > now);
require(!qd.timestampRepeated(coverDetails[4]));
qd.setTimestampRepeated(coverDetails[4]);
require(verifySign(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s));
_makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod);
}
/**
* @dev Updates the Sum Assured Amount of all the quotation.
* @param _cid Cover id
* @param _amount that will get subtracted Current Sum Assured
* amount that comes under a quotation.
*/
function _removeSAFromCSA(uint _cid, uint _amount) internal checkPause {
address _add;
bytes4 coverCurr;
(, , _add, coverCurr, , ) = qd.getCoverDetailsByCoverID1(_cid);
qd.subFromTotalSumAssured(coverCurr, _amount);
qd.subFromTotalSumAssuredSC(_add, coverCurr, _amount);
}
/**
* @dev to trigger the kyc process
* @param status is the kyc status
* @param _add is the address of member
*/
function _kycTrigger(bool status, address _add) internal {
uint holdedCoverLen = qd.getUserHoldedCoverLength(_add).sub(1);
uint holdedCoverID = qd.getUserHoldedCoverByIndex(_add, holdedCoverLen);
address payable userAdd;
address scAddress;
bytes4 coverCurr;
uint16 coverPeriod;
uint[] memory coverDetails = new uint[](4);
IERC20 erc20;
(, userAdd, coverDetails) = qd.getHoldedCoverDetailsByID2(holdedCoverID);
(, scAddress, coverCurr, coverPeriod) = qd.getHoldedCoverDetailsByID1(holdedCoverID);
require(qd.refundEligible(userAdd));
qd.setRefundEligible(userAdd, false);
require(qd.holdedCoverIDStatus(holdedCoverID) == uint(QuotationData.HCIDStatus.kycPending));
uint joinFee = td.joiningFee();
if (status) {
mr.payJoiningFee.value(joinFee)(userAdd);
if (coverDetails[3] > now) {
qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPass));
address poolAdd = ms.getLatestAddress("P1");
if (coverCurr == "ETH") {
p1.sendEther.value(coverDetails[1])();
} else {
erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line
require(erc20.transfer(poolAdd, coverDetails[1]));
}
emit RefundEvent(userAdd, status, holdedCoverID, "KYC Passed");
_makeCover(userAdd, scAddress, coverCurr, coverDetails, coverPeriod);
} else {
qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPassNoCover));
if (coverCurr == "ETH") {
userAdd.transfer(coverDetails[1]);
} else {
erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line
require(erc20.transfer(userAdd, coverDetails[1]));
}
emit RefundEvent(userAdd, status, holdedCoverID, "Cover Failed");
}
} else {
qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycFailedOrRefunded));
uint totalRefund = joinFee;
if (coverCurr == "ETH") {
totalRefund = coverDetails[1].add(joinFee);
} else {
erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line
require(erc20.transfer(userAdd, coverDetails[1]));
}
userAdd.transfer(totalRefund);
emit RefundEvent(userAdd, status, holdedCoverID, "KYC Failed");
}
}
}
// File: nexusmutual-contracts/contracts/external/uniswap/solidity-interface.sol
pragma solidity 0.5.7;
contract Factory {
function getExchange(address token) public view returns (address);
function getToken(address exchange) public view returns (address);
}
contract Exchange {
function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256);
function getTokenToEthInputPrice(uint256 tokensSold) public view returns(uint256);
function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) public payable returns (uint256);
function ethToTokenTransferInput(uint256 minTokens, uint256 deadline, address recipient)
public payable returns (uint256);
function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline)
public payable returns (uint256);
function tokenToEthTransferInput(uint256 tokensSold, uint256 minEth, uint256 deadline, address recipient)
public payable returns (uint256);
function tokenToTokenSwapInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address tokenAddress
)
public returns (uint256);
function tokenToTokenTransferInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address recipient,
address tokenAddress
)
public returns (uint256);
}
// File: nexusmutual-contracts/contracts/Pool2.sol
/* Copyright (C) 2017 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract Pool2 is Iupgradable {
using SafeMath for uint;
MCR internal m1;
Pool1 internal p1;
PoolData internal pd;
Factory internal factory;
address public uniswapFactoryAddress;
uint internal constant DECIMAL1E18 = uint(10) ** 18;
bool internal locked;
constructor(address _uniswapFactoryAdd) public {
uniswapFactoryAddress = _uniswapFactoryAdd;
factory = Factory(_uniswapFactoryAdd);
}
function() external payable {}
event Liquidity(bytes16 typeOf, bytes16 functionName);
event Rebalancing(bytes4 iaCurr, uint tokenAmount);
modifier noReentrancy() {
require(!locked, "Reentrant call.");
locked = true;
_;
locked = false;
}
/**
* @dev to change the uniswap factory address
* @param newFactoryAddress is the new factory address in concern
* @return the status of the concerned coverId
*/
function changeUniswapFactoryAddress(address newFactoryAddress) external onlyInternal {
// require(ms.isOwner(msg.sender) || ms.checkIsAuthToGoverned(msg.sender));
uniswapFactoryAddress = newFactoryAddress;
factory = Factory(uniswapFactoryAddress);
}
/**
* @dev On upgrade transfer all investment assets and ether to new Investment Pool
* @param newPoolAddress New Investment Assest Pool address
*/
function upgradeInvestmentPool(address payable newPoolAddress) external onlyInternal noReentrancy {
uint len = pd.getInvestmentCurrencyLen();
for (uint64 i = 1; i < len; i++) {
bytes4 iaName = pd.getInvestmentCurrencyByIndex(i);
_upgradeInvestmentPool(iaName, newPoolAddress);
}
if (address(this).balance > 0) {
Pool2 newP2 = Pool2(newPoolAddress);
newP2.sendEther.value(address(this).balance)();
}
}
/**
* @dev Internal Swap of assets between Capital
* and Investment Sub pool for excess or insufficient
* liquidity conditions of a given currency.
*/
function internalLiquiditySwap(bytes4 curr) external onlyInternal noReentrancy {
uint caBalance;
uint baseMin;
uint varMin;
(, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr);
caBalance = _getCurrencyAssetsBalance(curr);
if (caBalance > uint(baseMin).add(varMin).mul(2)) {
_internalExcessLiquiditySwap(curr, baseMin, varMin, caBalance);
} else if (caBalance < uint(baseMin).add(varMin)) {
_internalInsufficientLiquiditySwap(curr, baseMin, varMin, caBalance);
}
}
/**
* @dev Saves a given investment asset details. To be called daily.
* @param curr array of Investment asset name.
* @param rate array of investment asset exchange rate.
* @param date current date in yyyymmdd.
*/
function saveIADetails(bytes4[] calldata curr, uint64[] calldata rate, uint64 date, bool bit)
external checkPause noReentrancy {
bytes4 maxCurr;
bytes4 minCurr;
uint64 maxRate;
uint64 minRate;
//ONLY NOTARZIE ADDRESS CAN POST
require(pd.isnotarise(msg.sender));
(maxCurr, maxRate, minCurr, minRate) = _calculateIARank(curr, rate);
pd.saveIARankDetails(maxCurr, maxRate, minCurr, minRate, date);
pd.updatelastDate(date);
uint len = curr.length;
for (uint i = 0; i < len; i++) {
pd.updateIAAvgRate(curr[i], rate[i]);
}
if (bit) //for testing purpose
_rebalancingLiquidityTrading(maxCurr, maxRate);
p1.saveIADetailsOracalise(pd.iaRatesTime());
}
/**
* @dev External Trade for excess or insufficient
* liquidity conditions of a given currency.
*/
function externalLiquidityTrade() external onlyInternal {
bool triggerTrade;
bytes4 curr;
bytes4 minIACurr;
bytes4 maxIACurr;
uint amount;
uint minIARate;
uint maxIARate;
uint baseMin;
uint varMin;
uint caBalance;
(maxIACurr, maxIARate, minIACurr, minIARate) = pd.getIARankDetailsByDate(pd.getLastDate());
uint len = pd.getAllCurrenciesLen();
for (uint64 i = 0; i < len; i++) {
curr = pd.getCurrenciesByIndex(i);
(, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr);
caBalance = _getCurrencyAssetsBalance(curr);
if (caBalance > uint(baseMin).add(varMin).mul(2)) { //excess
amount = caBalance.sub(((uint(baseMin).add(varMin)).mul(3)).div(2)); //*10**18;
triggerTrade = _externalExcessLiquiditySwap(curr, minIACurr, amount);
} else if (caBalance < uint(baseMin).add(varMin)) { // insufficient
amount = (((uint(baseMin).add(varMin)).mul(3)).div(2)).sub(caBalance);
triggerTrade = _externalInsufficientLiquiditySwap(curr, maxIACurr, amount);
}
if (triggerTrade) {
p1.triggerExternalLiquidityTrade();
}
}
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
m1 = MCR(ms.getLatestAddress("MC"));
pd = PoolData(ms.getLatestAddress("PD"));
p1 = Pool1(ms.getLatestAddress("P1"));
}
function sendEther() public payable {
}
/**
* @dev Gets currency asset balance for a given currency name.
*/
function _getCurrencyAssetsBalance(bytes4 _curr) public view returns(uint caBalance) {
if (_curr == "ETH") {
caBalance = address(p1).balance;
} else {
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr));
caBalance = erc20.balanceOf(address(p1));
}
}
/**
* @dev Transfers ERC20 investment asset from this Pool to another Pool.
*/
function _transferInvestmentAsset(
bytes4 _curr,
address _transferTo,
uint _amount
)
internal
{
if (_curr == "ETH") {
if (_amount > address(this).balance)
_amount = address(this).balance;
p1.sendEther.value(_amount)();
} else {
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr));
if (_amount > erc20.balanceOf(address(this)))
_amount = erc20.balanceOf(address(this));
require(erc20.transfer(_transferTo, _amount));
}
}
/**
* @dev to perform rebalancing
* @param iaCurr is the investment asset currency
* @param iaRate is the investment asset rate
*/
function _rebalancingLiquidityTrading(
bytes4 iaCurr,
uint64 iaRate
)
internal
checkPause
{
uint amountToSell;
uint totalRiskBal = pd.getLastVfull();
uint intermediaryEth;
uint ethVol = pd.ethVolumeLimit();
totalRiskBal = (totalRiskBal.mul(100000)).div(DECIMAL1E18);
Exchange exchange;
if (totalRiskBal > 0) {
amountToSell = ((totalRiskBal.mul(2).mul(
iaRate)).mul(pd.variationPercX100())).div(100 * 100 * 100000);
amountToSell = (amountToSell.mul(
10**uint(pd.getInvestmentAssetDecimals(iaCurr)))).div(100); // amount of asset to sell
if (iaCurr != "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) {
exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(iaCurr)));
intermediaryEth = exchange.getTokenToEthInputPrice(amountToSell);
if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) {
intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100);
amountToSell = (exchange.getEthToTokenInputPrice(intermediaryEth).mul(995)).div(1000);
}
IERC20 erc20;
erc20 = IERC20(pd.getCurrencyAssetAddress(iaCurr));
erc20.approve(address(exchange), amountToSell);
exchange.tokenToEthSwapInput(amountToSell, (exchange.getTokenToEthInputPrice(
amountToSell).mul(995)).div(1000), pd.uniswapDeadline().add(now));
} else if (iaCurr == "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) {
_transferInvestmentAsset(iaCurr, ms.getLatestAddress("P1"), amountToSell);
}
emit Rebalancing(iaCurr, amountToSell);
}
}
/**
* @dev Checks whether trading is required for a
* given investment asset at a given exchange rate.
*/
function _checkTradeConditions(
bytes4 curr,
uint64 iaRate,
uint totalRiskBal
)
internal
view
returns(bool check)
{
if (iaRate > 0) {
uint iaBalance = _getInvestmentAssetBalance(curr).div(DECIMAL1E18);
if (iaBalance > 0 && totalRiskBal > 0) {
uint iaMax;
uint iaMin;
uint checkNumber;
uint z;
(iaMin, iaMax) = pd.getInvestmentAssetHoldingPerc(curr);
z = pd.variationPercX100();
checkNumber = (iaBalance.mul(100 * 100000)).div(totalRiskBal.mul(iaRate));
if ((checkNumber > ((totalRiskBal.mul(iaMax.add(z))).mul(100000)).div(100)) ||
(checkNumber < ((totalRiskBal.mul(iaMin.sub(z))).mul(100000)).div(100)))
check = true; //eligibleIA
}
}
}
/**
* @dev Gets the investment asset rank.
*/
function _getIARank(
bytes4 curr,
uint64 rateX100,
uint totalRiskPoolBalance
)
internal
view
returns (int rhsh, int rhsl) //internal function
{
uint currentIAmaxHolding;
uint currentIAminHolding;
uint iaBalance = _getInvestmentAssetBalance(curr);
(currentIAminHolding, currentIAmaxHolding) = pd.getInvestmentAssetHoldingPerc(curr);
if (rateX100 > 0) {
uint rhsf;
rhsf = (iaBalance.mul(1000000)).div(totalRiskPoolBalance.mul(rateX100));
rhsh = int(rhsf - currentIAmaxHolding);
rhsl = int(rhsf - currentIAminHolding);
}
}
/**
* @dev Calculates the investment asset rank.
*/
function _calculateIARank(
bytes4[] memory curr,
uint64[] memory rate
)
internal
view
returns(
bytes4 maxCurr,
uint64 maxRate,
bytes4 minCurr,
uint64 minRate
)
{
int max = 0;
int min = -1;
int rhsh;
int rhsl;
uint totalRiskPoolBalance;
(totalRiskPoolBalance, ) = m1.calVtpAndMCRtp();
uint len = curr.length;
for (uint i = 0; i < len; i++) {
rhsl = 0;
rhsh = 0;
if (pd.getInvestmentAssetStatus(curr[i])) {
(rhsh, rhsl) = _getIARank(curr[i], rate[i], totalRiskPoolBalance);
if (rhsh > max || i == 0) {
max = rhsh;
maxCurr = curr[i];
maxRate = rate[i];
}
if (rhsl < min || rhsl == 0 || i == 0) {
min = rhsl;
minCurr = curr[i];
minRate = rate[i];
}
}
}
}
/**
* @dev to get balance of an investment asset
* @param _curr is the investment asset in concern
* @return the balance
*/
function _getInvestmentAssetBalance(bytes4 _curr) internal view returns (uint balance) {
if (_curr == "ETH") {
balance = address(this).balance;
} else {
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr));
balance = erc20.balanceOf(address(this));
}
}
/**
* @dev Creates Excess liquidity trading order for a given currency and a given balance.
*/
function _internalExcessLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal {
// require(ms.isInternal(msg.sender) || md.isnotarise(msg.sender));
bytes4 minIACurr;
// uint amount;
(, , minIACurr, ) = pd.getIARankDetailsByDate(pd.getLastDate());
if (_curr == minIACurr) {
// amount = _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)); //*10**18;
p1.transferCurrencyAsset(_curr, _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)));
} else {
p1.triggerExternalLiquidityTrade();
}
}
/**
* @dev insufficient liquidity swap
* for a given currency and a given balance.
*/
function _internalInsufficientLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal {
bytes4 maxIACurr;
uint amount;
(maxIACurr, , , ) = pd.getIARankDetailsByDate(pd.getLastDate());
if (_curr == maxIACurr) {
amount = (((_baseMin.add(_varMin)).mul(3)).div(2)).sub(_caBalance);
_transferInvestmentAsset(_curr, ms.getLatestAddress("P1"), amount);
} else {
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr));
if ((maxIACurr == "ETH" && address(this).balance > 0) ||
(maxIACurr != "ETH" && erc20.balanceOf(address(this)) > 0))
p1.triggerExternalLiquidityTrade();
}
}
/**
* @dev Creates External excess liquidity trading
* order for a given currency and a given balance.
* @param curr Currency Asset to Sell
* @param minIACurr Investment Asset to Buy
* @param amount Amount of Currency Asset to Sell
*/
function _externalExcessLiquiditySwap(
bytes4 curr,
bytes4 minIACurr,
uint256 amount
)
internal
returns (bool trigger)
{
uint intermediaryEth;
Exchange exchange;
IERC20 erc20;
uint ethVol = pd.ethVolumeLimit();
if (curr == minIACurr) {
p1.transferCurrencyAsset(curr, amount);
} else if (curr == "ETH" && minIACurr != "ETH") {
exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(minIACurr)));
if (amount > (address(exchange).balance.mul(ethVol)).div(100)) { // 4% ETH volume limit
amount = (address(exchange).balance.mul(ethVol)).div(100);
trigger = true;
}
p1.transferCurrencyAsset(curr, amount);
exchange.ethToTokenSwapInput.value(amount)
(exchange.getEthToTokenInputPrice(amount).mul(995).div(1000), pd.uniswapDeadline().add(now));
} else if (curr != "ETH" && minIACurr == "ETH") {
exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr)));
erc20 = IERC20(pd.getCurrencyAssetAddress(curr));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) {
intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100);
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
trigger = true;
}
p1.transferCurrencyAsset(curr, amount);
// erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange)));
erc20.approve(address(exchange), amount);
exchange.tokenToEthSwapInput(amount, (
intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now));
} else {
exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr)));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) {
intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100);
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
trigger = true;
}
Exchange tmp = Exchange(factory.getExchange(
pd.getInvestmentAssetAddress(minIACurr))); // minIACurr exchange
if (intermediaryEth > address(tmp).balance.mul(ethVol).div(100)) {
intermediaryEth = address(tmp).balance.mul(ethVol).div(100);
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
trigger = true;
}
p1.transferCurrencyAsset(curr, amount);
erc20 = IERC20(pd.getCurrencyAssetAddress(curr));
erc20.approve(address(exchange), amount);
exchange.tokenToTokenSwapInput(amount, (tmp.getEthToTokenInputPrice(
intermediaryEth).mul(995)).div(1000), (intermediaryEth.mul(995)).div(1000),
pd.uniswapDeadline().add(now), pd.getInvestmentAssetAddress(minIACurr));
}
}
/**
* @dev insufficient liquidity swap
* for a given currency and a given balance.
* @param curr Currency Asset to buy
* @param maxIACurr Investment Asset to sell
* @param amount Amount of Investment Asset to sell
*/
function _externalInsufficientLiquiditySwap(
bytes4 curr,
bytes4 maxIACurr,
uint256 amount
)
internal
returns (bool trigger)
{
Exchange exchange;
IERC20 erc20;
uint intermediaryEth;
// uint ethVol = pd.ethVolumeLimit();
if (curr == maxIACurr) {
_transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount);
} else if (curr == "ETH" && maxIACurr != "ETH") {
exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr)));
intermediaryEth = exchange.getEthToTokenInputPrice(amount);
if (amount > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) {
amount = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100);
// amount = exchange.getEthToTokenInputPrice(intermediaryEth);
intermediaryEth = exchange.getEthToTokenInputPrice(amount);
trigger = true;
}
erc20 = IERC20(pd.getCurrencyAssetAddress(maxIACurr));
if (intermediaryEth > erc20.balanceOf(address(this))) {
intermediaryEth = erc20.balanceOf(address(this));
}
// erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange)));
erc20.approve(address(exchange), intermediaryEth);
exchange.tokenToEthTransferInput(intermediaryEth, (
exchange.getTokenToEthInputPrice(intermediaryEth).mul(995)).div(1000),
pd.uniswapDeadline().add(now), address(p1));
} else if (curr != "ETH" && maxIACurr == "ETH") {
exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr)));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > address(this).balance)
intermediaryEth = address(this).balance;
if (intermediaryEth > (address(exchange).balance.mul
(pd.ethVolumeLimit())).div(100)) { // 4% ETH volume limit
intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100);
trigger = true;
}
exchange.ethToTokenTransferInput.value(intermediaryEth)((exchange.getEthToTokenInputPrice(
intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1));
} else {
address currAdd = pd.getCurrencyAssetAddress(curr);
exchange = Exchange(factory.getExchange(currAdd));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) {
intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100);
trigger = true;
}
Exchange tmp = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr)));
if (intermediaryEth > address(tmp).balance.mul(pd.ethVolumeLimit()).div(100)) {
intermediaryEth = address(tmp).balance.mul(pd.ethVolumeLimit()).div(100);
// amount = exchange.getEthToTokenInputPrice(intermediaryEth);
trigger = true;
}
uint maxIAToSell = tmp.getEthToTokenInputPrice(intermediaryEth);
erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr));
uint maxIABal = erc20.balanceOf(address(this));
if (maxIAToSell > maxIABal) {
maxIAToSell = maxIABal;
intermediaryEth = tmp.getTokenToEthInputPrice(maxIAToSell);
// amount = exchange.getEthToTokenInputPrice(intermediaryEth);
}
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
erc20.approve(address(tmp), maxIAToSell);
tmp.tokenToTokenTransferInput(maxIAToSell, (
amount.mul(995)).div(1000), (
intermediaryEth), pd.uniswapDeadline().add(now), address(p1), currAdd);
}
}
/**
* @dev Transfers ERC20 investment asset from this Pool to another Pool.
*/
function _upgradeInvestmentPool(
bytes4 _curr,
address _newPoolAddress
)
internal
{
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr));
if (erc20.balanceOf(address(this)) > 0)
require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this))));
}
}
// File: nexusmutual-contracts/contracts/Pool1.sol
/* Copyright (C) 2017 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract Pool1 is usingOraclize, Iupgradable {
using SafeMath for uint;
Quotation internal q2;
NXMToken internal tk;
TokenController internal tc;
TokenFunctions internal tf;
Pool2 internal p2;
PoolData internal pd;
MCR internal m1;
Claims public c1;
TokenData internal td;
bool internal locked;
uint internal constant DECIMAL1E18 = uint(10) ** 18;
// uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18;
event Apiresult(address indexed sender, string msg, bytes32 myid);
event Payout(address indexed to, uint coverId, uint tokens);
modifier noReentrancy() {
require(!locked, "Reentrant call.");
locked = true;
_;
locked = false;
}
function () external payable {} //solhint-disable-line
/**
* @dev Pays out the sum assured in case a claim is accepted
* @param coverid Cover Id.
* @param claimid Claim Id.
* @return succ true if payout is successful, false otherwise.
*/
function sendClaimPayout(
uint coverid,
uint claimid,
uint sumAssured,
address payable coverHolder,
bytes4 coverCurr
)
external
onlyInternal
noReentrancy
returns(bool succ)
{
uint sa = sumAssured.div(DECIMAL1E18);
bool check;
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr));
//Payout
if (coverCurr == "ETH" && address(this).balance >= sumAssured) {
// check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured);
coverHolder.transfer(sumAssured);
check = true;
} else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) {
erc20.transfer(coverHolder, sumAssured);
check = true;
}
if (check == true) {
q2.removeSAFromCSA(coverid, sa);
pd.changeCurrencyAssetVarMin(coverCurr,
pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured));
emit Payout(coverHolder, coverid, sumAssured);
succ = true;
} else {
c1.setClaimStatus(claimid, 12);
}
_triggerExternalLiquidityTrade();
// p2.internalLiquiditySwap(coverCurr);
tf.burnStakerLockedToken(coverid, coverCurr, sumAssured);
}
/**
* @dev to trigger external liquidity trade
*/
function triggerExternalLiquidityTrade() external onlyInternal {
_triggerExternalLiquidityTrade();
}
///@dev Oraclize call to close emergency pause.
function closeEmergencyPause(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", "", 300000);
_saveApiDetails(myid, "EP", 0);
}
/// @dev Calls the Oraclize Query to close a given Claim after a given period of time.
/// @param id Claim Id to be closed
/// @param time Time (in seconds) after which Claims assessment voting needs to be closed
function closeClaimsOraclise(uint id, uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000);
_saveApiDetails(myid, "CLA", id);
}
/// @dev Calls Oraclize Query to expire a given Cover after a given period of time.
/// @param id Quote Id to be expired
/// @param time Time (in seconds) after which the cover should be expired
function closeCoverOraclise(uint id, uint64 time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", strConcat(
"http://a1.nexusmutual.io/api/Claims/closeClaim_hash/", uint2str(id)), 1000000);
_saveApiDetails(myid, "COV", id);
}
/// @dev Calls the Oraclize Query to initiate MCR calculation.
/// @param time Time (in milliseconds) after which the next MCR calculation should be initiated
function mcrOraclise(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/postMCR/M1", 0);
_saveApiDetails(myid, "MCR", 0);
}
/// @dev Calls the Oraclize Query in case MCR calculation fails.
/// @param time Time (in seconds) after which the next MCR calculation should be initiated
function mcrOracliseFail(uint id, uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", "", 1000000);
_saveApiDetails(myid, "MCRF", id);
}
/// @dev Oraclize call to update investment asset rates.
function saveIADetailsOracalise(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/saveIADetails/M1", 0);
_saveApiDetails(myid, "IARB", 0);
}
/**
* @dev Transfers all assest (i.e ETH balance, Currency Assest) from old Pool to new Pool
* @param newPoolAddress Address of the new Pool
*/
function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal {
for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) {
bytes4 caName = pd.getCurrenciesByIndex(i);
_upgradeCapitalPool(caName, newPoolAddress);
}
if (address(this).balance > 0) {
Pool1 newP1 = Pool1(newPoolAddress);
newP1.sendEther.value(address(this).balance)();
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
m1 = MCR(ms.getLatestAddress("MC"));
tk = NXMToken(ms.tokenAddress());
tf = TokenFunctions(ms.getLatestAddress("TF"));
tc = TokenController(ms.getLatestAddress("TC"));
pd = PoolData(ms.getLatestAddress("PD"));
q2 = Quotation(ms.getLatestAddress("QT"));
p2 = Pool2(ms.getLatestAddress("P2"));
c1 = Claims(ms.getLatestAddress("CL"));
td = TokenData(ms.getLatestAddress("TD"));
}
function sendEther() public payable {
}
/**
* @dev transfers currency asset to an address
* @param curr is the currency of currency asset to transfer
* @param amount is amount of currency asset to transfer
* @return boolean to represent success or failure
*/
function transferCurrencyAsset(
bytes4 curr,
uint amount
)
public
onlyInternal
noReentrancy
returns(bool)
{
return _transferCurrencyAsset(curr, amount);
}
/// @dev Handles callback of external oracle query.
function __callback(bytes32 myid, string memory result) public {
result; //silence compiler warning
// owner will be removed from production build
ms.delegateCallBack(myid);
}
/// @dev Enables user to purchase cover with funding in ETH.
/// @param smartCAdd Smart Contract Address
function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
isMember
checkPause
payable
{
require(msg.value == coverDetails[1]);
q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @dev Enables user to purchase cover via currency asset eg DAI
*/
function makeCoverUsingCA(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
isMember
checkPause
{
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr));
require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed");
q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/// @dev Enables user to purchase NXM at the current token price.
function buyToken() public payable isMember checkPause returns(bool success) {
require(msg.value > 0);
uint tokenPurchased = _getToken(address(this).balance, msg.value);
tc.mint(msg.sender, tokenPurchased);
success = true;
}
/// @dev Sends a given amount of Ether to a given address.
/// @param amount amount (in wei) to send.
/// @param _add Receiver's address.
/// @return succ True if transfer is a success, otherwise False.
function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) {
require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern");
succ = _add.send(amount);
}
/**
* @dev Allows selling of NXM for ether.
* Seller first needs to give this contract allowance to
* transfer/burn tokens in the NXMToken contract
* @param _amount Amount of NXM to sell
* @return success returns true on successfull sale
*/
function sellNXMTokens(uint _amount) public isMember noReentrancy checkPause returns(bool success) {
require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance");
require(!tf.isLockedForMemberVote(msg.sender), "Member voted");
require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit");
uint sellingPrice = _getWei(_amount);
tc.burnFrom(msg.sender, _amount);
msg.sender.transfer(sellingPrice);
success = true;
}
/**
* @dev gives the investment asset balance
* @return investment asset balance
*/
function getInvestmentAssetBalance() public view returns (uint balance) {
IERC20 erc20;
uint currTokens;
for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) {
bytes4 currency = pd.getInvestmentCurrencyByIndex(i);
erc20 = IERC20(pd.getInvestmentAssetAddress(currency));
currTokens = erc20.balanceOf(address(p2));
if (pd.getIAAvgRate(currency) > 0)
balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency)));
}
balance = balance.add(address(p2).balance);
}
/**
* @dev Returns the amount of wei a seller will get for selling NXM
* @param amount Amount of NXM to sell
* @return weiToPay Amount of wei the seller will get
*/
function getWei(uint amount) public view returns(uint weiToPay) {
return _getWei(amount);
}
/**
* @dev Returns the amount of token a buyer will get for corresponding wei
* @param weiPaid Amount of wei
* @return tokenToGet Amount of tokens the buyer will get
*/
function getToken(uint weiPaid) public view returns(uint tokenToGet) {
return _getToken((address(this).balance).add(weiPaid), weiPaid);
}
/**
* @dev to trigger external liquidity trade
*/
function _triggerExternalLiquidityTrade() internal {
if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) {
pd.setLastLiquidityTradeTrigger();
bytes32 myid = _oraclizeQuery(4, pd.liquidityTradeCallbackTime(), "URL", "", 300000);
_saveApiDetails(myid, "ULT", 0);
}
}
/**
* @dev Returns the amount of wei a seller will get for selling NXM
* @param _amount Amount of NXM to sell
* @return weiToPay Amount of wei the seller will get
*/
function _getWei(uint _amount) internal view returns(uint weiToPay) {
uint tokenPrice;
uint weiPaid;
uint tokenSupply = tk.totalSupply();
uint vtp;
uint mcrFullperc;
uint vFull;
uint mcrtp;
(mcrFullperc, , vFull, ) = pd.getLastMCR();
(vtp, ) = m1.calVtpAndMCRtp();
while (_amount > 0) {
mcrtp = (mcrFullperc.mul(vtp)).div(vFull);
tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp);
tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5%
if (_amount <= td.priceStep().mul(DECIMAL1E18)) {
weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18));
break;
} else {
_amount = _amount.sub(td.priceStep().mul(DECIMAL1E18));
tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18));
weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18);
vtp = vtp.sub(weiPaid);
weiToPay = weiToPay.add(weiPaid);
}
}
}
/**
* @dev gives the token
* @param _poolBalance is the pool balance
* @param _weiPaid is the amount paid in wei
* @return the token to get
*/
function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) {
uint tokenPrice;
uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18);
uint tempTokens;
uint superWeiSpent;
uint tokenSupply = tk.totalSupply();
uint vtp;
uint mcrFullperc;
uint vFull;
uint mcrtp;
(mcrFullperc, , vFull, ) = pd.getLastMCR();
(vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid));
require(m1.calculateTokenPrice("ETH") > 0, "Token price can not be zero");
while (superWeiLeft > 0) {
mcrtp = (mcrFullperc.mul(vtp)).div(vFull);
tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp);
tempTokens = superWeiLeft.div(tokenPrice);
if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) {
tokenToGet = tokenToGet.add(tempTokens);
break;
} else {
tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18));
tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18));
superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice);
superWeiLeft = superWeiLeft.sub(superWeiSpent);
vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18));
}
}
}
/**
* @dev Save the details of the Oraclize API.
* @param myid Id return by the oraclize query.
* @param _typeof type of the query for which oraclize call is made.
* @param id ID of the proposal, quote, cover etc. for which oraclize call is made.
*/
function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal {
pd.saveApiDetails(myid, _typeof, id);
pd.addInAllApiCall(myid);
}
/**
* @dev transfers currency asset
* @param _curr is currency of asset to transfer
* @param _amount is the amount to be transferred
* @return boolean representing the success of transfer
*/
function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) {
if (_curr == "ETH") {
if (address(this).balance < _amount)
_amount = address(this).balance;
p2.sendEther.value(_amount)();
succ = true;
} else {
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line
if (erc20.balanceOf(address(this)) < _amount)
_amount = erc20.balanceOf(address(this));
require(erc20.transfer(address(p2), _amount));
succ = true;
}
}
/**
* @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade.
*/
function _upgradeCapitalPool(
bytes4 _curr,
address _newPoolAddress
)
internal
{
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr));
if (erc20.balanceOf(address(this)) > 0)
require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this))));
}
/**
* @dev oraclize query
* @param paramCount is number of paramters passed
* @param timestamp is the current timestamp
* @param datasource in concern
* @param arg in concern
* @param gasLimit required for query
* @return id of oraclize query
*/
function _oraclizeQuery(
uint paramCount,
uint timestamp,
string memory datasource,
string memory arg,
uint gasLimit
)
internal
returns (bytes32 id)
{
if (paramCount == 4) {
id = oraclize_query(timestamp, datasource, arg, gasLimit);
} else if (paramCount == 3) {
id = oraclize_query(timestamp, datasource, arg);
} else {
id = oraclize_query(datasource, arg);
}
}
}
// File: nexusmutual-contracts/contracts/MCR.sol
/* Copyright (C) 2017 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract MCR is Iupgradable {
using SafeMath for uint;
Pool1 internal p1;
PoolData internal pd;
NXMToken internal tk;
QuotationData internal qd;
MemberRoles internal mr;
TokenData internal td;
ProposalCategory internal proposalCategory;
uint private constant DECIMAL1E18 = uint(10) ** 18;
uint private constant DECIMAL1E05 = uint(10) ** 5;
uint private constant DECIMAL1E19 = uint(10) ** 19;
uint private constant minCapFactor = uint(10) ** 21;
uint public variableMincap;
uint public dynamicMincapThresholdx100 = 13000;
uint public dynamicMincapIncrementx100 = 100;
event MCREvent(
uint indexed date,
uint blockNumber,
bytes4[] allCurr,
uint[] allCurrRates,
uint mcrEtherx100,
uint mcrPercx100,
uint vFull
);
/**
* @dev Adds new MCR data.
* @param mcrP Minimum Capital Requirement in percentage.
* @param vF Pool1 fund value in Ether used in the last full daily calculation of the Capital model.
* @param onlyDate Date(yyyymmdd) at which MCR details are getting added.
*/
function addMCRData(
uint mcrP,
uint mcrE,
uint vF,
bytes4[] calldata curr,
uint[] calldata _threeDayAvg,
uint64 onlyDate
)
external
checkPause
{
require(proposalCategory.constructorCheck());
require(pd.isnotarise(msg.sender));
if (mr.launched() && pd.capReached() != 1) {
if (mcrP >= 10000)
pd.setCapReached(1);
}
uint len = pd.getMCRDataLength();
_addMCRData(len, onlyDate, curr, mcrE, mcrP, vF, _threeDayAvg);
}
/**
* @dev Adds MCR Data for last failed attempt.
*/
function addLastMCRData(uint64 date) external checkPause onlyInternal {
uint64 lastdate = uint64(pd.getLastMCRDate());
uint64 failedDate = uint64(date);
if (failedDate >= lastdate) {
uint mcrP;
uint mcrE;
uint vF;
(mcrP, mcrE, vF, ) = pd.getLastMCR();
uint len = pd.getAllCurrenciesLen();
pd.pushMCRData(mcrP, mcrE, vF, date);
for (uint j = 0; j < len; j++) {
bytes4 currName = pd.getCurrenciesByIndex(j);
pd.updateCAAvgRate(currName, pd.getCAAvgRate(currName));
}
emit MCREvent(date, block.number, new bytes4[](0), new uint[](0), mcrE, mcrP, vF);
// Oraclize call for next MCR calculation
_callOracliseForMCR();
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
qd = QuotationData(ms.getLatestAddress("QD"));
p1 = Pool1(ms.getLatestAddress("P1"));
pd = PoolData(ms.getLatestAddress("PD"));
tk = NXMToken(ms.tokenAddress());
mr = MemberRoles(ms.getLatestAddress("MR"));
td = TokenData(ms.getLatestAddress("TD"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Gets total sum assured(in ETH).
* @return amount of sum assured
*/
function getAllSumAssurance() public view returns(uint amount) {
uint len = pd.getAllCurrenciesLen();
for (uint i = 0; i < len; i++) {
bytes4 currName = pd.getCurrenciesByIndex(i);
if (currName == "ETH") {
amount = amount.add(qd.getTotalSumAssured(currName));
} else {
if (pd.getCAAvgRate(currName) > 0)
amount = amount.add((qd.getTotalSumAssured(currName).mul(100)).div(pd.getCAAvgRate(currName)));
}
}
}
/**
* @dev Calculates V(Tp) and MCR%(Tp), i.e, Pool Fund Value in Ether
* and MCR% used in the Token Price Calculation.
* @return vtp Pool Fund Value in Ether used for the Token Price Model
* @return mcrtp MCR% used in the Token Price Model.
*/
function _calVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) {
vtp = 0;
IERC20 erc20;
uint currTokens = 0;
uint i;
for (i = 1; i < pd.getAllCurrenciesLen(); i++) {
bytes4 currency = pd.getCurrenciesByIndex(i);
erc20 = IERC20(pd.getCurrencyAssetAddress(currency));
currTokens = erc20.balanceOf(address(p1));
if (pd.getCAAvgRate(currency) > 0)
vtp = vtp.add((currTokens.mul(100)).div(pd.getCAAvgRate(currency)));
}
vtp = vtp.add(poolBalance).add(p1.getInvestmentAssetBalance());
uint mcrFullperc;
uint vFull;
(mcrFullperc, , vFull, ) = pd.getLastMCR();
if (vFull > 0) {
mcrtp = (mcrFullperc.mul(vtp)).div(vFull);
}
}
/**
* @dev Calculates the Token Price of NXM in a given currency.
* @param curr Currency name.
*/
function calculateStepTokenPrice(
bytes4 curr,
uint mcrtp
)
public
view
onlyInternal
returns(uint tokenPrice)
{
return _calculateTokenPrice(curr, mcrtp);
}
/**
* @dev Calculates the Token Price of NXM in a given currency
* with provided token supply for dynamic token price calculation
* @param curr Currency name.
*/
function calculateTokenPrice (bytes4 curr) public view returns(uint tokenPrice) {
uint mcrtp;
(, mcrtp) = _calVtpAndMCRtp(address(p1).balance);
return _calculateTokenPrice(curr, mcrtp);
}
function calVtpAndMCRtp() public view returns(uint vtp, uint mcrtp) {
return _calVtpAndMCRtp(address(p1).balance);
}
function calculateVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) {
return _calVtpAndMCRtp(poolBalance);
}
function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) public view returns(uint lowerThreshold, uint upperThreshold)
{
minCap = (minCap.mul(minCapFactor)).add(variableMincap);
uint lower = 0;
if (vtp >= vF) {
upperThreshold = vtp.mul(120).mul(100).div((minCap)); //Max Threshold = [MAX(Vtp, Vfull) x 120] / mcrMinCap
} else {
upperThreshold = vF.mul(120).mul(100).div((minCap));
}
if (vtp > 0) {
lower = totalSA.mul(DECIMAL1E18).mul(pd.shockParameter()).div(100);
if(lower < minCap.mul(11).div(10))
lower = minCap.mul(11).div(10);
}
if (lower > 0) { //Min Threshold = [Vtp / MAX(TotalActiveSA x ShockParameter, mcrMinCap x 1.1)] x 100
lowerThreshold = vtp.mul(100).mul(100).div(lower);
}
}
/**
* @dev Gets max numbers of tokens that can be sold at the moment.
*/
function getMaxSellTokens() public view returns(uint maxTokens) {
uint baseMin = pd.getCurrencyAssetBaseMin("ETH");
uint maxTokensAccPoolBal;
if (address(p1).balance > baseMin.mul(50).div(100)) {
maxTokensAccPoolBal = address(p1).balance.sub(
(baseMin.mul(50)).div(100));
}
maxTokensAccPoolBal = (maxTokensAccPoolBal.mul(DECIMAL1E18)).div(
(calculateTokenPrice("ETH").mul(975)).div(1000));
uint lastMCRPerc = pd.getLastMCRPerc();
if (lastMCRPerc > 10000)
maxTokens = (((uint(lastMCRPerc).sub(10000)).mul(2000)).mul(DECIMAL1E18)).div(10000);
if (maxTokens > maxTokensAccPoolBal)
maxTokens = maxTokensAccPoolBal;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) {
codeVal = code;
if (code == "DMCT") {
val = dynamicMincapThresholdx100;
} else if (code == "DMCI") {
val = dynamicMincapIncrementx100;
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "DMCT") {
dynamicMincapThresholdx100 = val;
} else if (code == "DMCI") {
dynamicMincapIncrementx100 = val;
}
else {
revert("Invalid param code");
}
}
/**
* @dev Calls oraclize query to calculate MCR details after 24 hours.
*/
function _callOracliseForMCR() internal {
p1.mcrOraclise(pd.mcrTime());
}
/**
* @dev Calculates the Token Price of NXM in a given currency
* with provided token supply for dynamic token price calculation
* @param _curr Currency name.
* @return tokenPrice Token price.
*/
function _calculateTokenPrice(
bytes4 _curr,
uint mcrtp
)
internal
view
returns(uint tokenPrice)
{
uint getA;
uint getC;
uint getCAAvgRate;
uint tokenExponentValue = td.tokenExponent();
// uint max = (mcrtp.mul(mcrtp).mul(mcrtp).mul(mcrtp));
uint max = mcrtp ** tokenExponentValue;
uint dividingFactor = tokenExponentValue.mul(4);
(getA, getC, getCAAvgRate) = pd.getTokenPriceDetails(_curr);
uint mcrEth = pd.getLastMCREther();
getC = getC.mul(DECIMAL1E18);
tokenPrice = (mcrEth.mul(DECIMAL1E18).mul(max).div(getC)).div(10 ** dividingFactor);
tokenPrice = tokenPrice.add(getA.mul(DECIMAL1E18).div(DECIMAL1E05));
tokenPrice = tokenPrice.mul(getCAAvgRate * 10);
tokenPrice = (tokenPrice).div(10**3);
}
/**
* @dev Adds MCR Data. Checks if MCR is within valid
* thresholds in order to rule out any incorrect calculations
*/
function _addMCRData(
uint len,
uint64 newMCRDate,
bytes4[] memory curr,
uint mcrE,
uint mcrP,
uint vF,
uint[] memory _threeDayAvg
)
internal
{
uint vtp = 0;
uint lowerThreshold = 0;
uint upperThreshold = 0;
if (len > 1) {
(vtp, ) = _calVtpAndMCRtp(address(p1).balance);
(lowerThreshold, upperThreshold) = getThresholdValues(vtp, vF, getAllSumAssurance(), pd.minCap());
}
if(mcrP > dynamicMincapThresholdx100)
variableMincap = (variableMincap.mul(dynamicMincapIncrementx100.add(10000)).add(minCapFactor.mul(pd.minCap().mul(dynamicMincapIncrementx100)))).div(10000);
// Explanation for above formula :-
// actual formula -> variableMinCap = variableMinCap + (variableMinCap+minCap)*dynamicMincapIncrement/100
// Implemented formula is simplified form of actual formula.
// Let consider above formula as b = b + (a+b)*c/100
// here, dynamicMincapIncrement is in x100 format.
// so b+(a+b)*cx100/10000 can be written as => (10000.b + b.cx100 + a.cx100)/10000.
// It can further simplify to (b.(10000+cx100) + a.cx100)/10000.
if (len == 1 || (mcrP) >= lowerThreshold
&& (mcrP) <= upperThreshold) {
vtp = pd.getLastMCRDate(); // due to stack to deep error,we are reusing already declared variable
pd.pushMCRData(mcrP, mcrE, vF, newMCRDate);
for (uint i = 0; i < curr.length; i++) {
pd.updateCAAvgRate(curr[i], _threeDayAvg[i]);
}
emit MCREvent(newMCRDate, block.number, curr, _threeDayAvg, mcrE, mcrP, vF);
// Oraclize call for next MCR calculation
if (vtp < newMCRDate) {
_callOracliseForMCR();
}
} else {
p1.mcrOracliseFail(newMCRDate, pd.mcrFailTime());
}
}
}
// File: nexusmutual-contracts/contracts/Claims.sol
/* Copyright (C) 2017 NexusMutual.io
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/ */
pragma solidity 0.5.7;
contract Claims is Iupgradable {
using SafeMath for uint;
TokenFunctions internal tf;
NXMToken internal tk;
TokenController internal tc;
ClaimsReward internal cr;
Pool1 internal p1;
ClaimsData internal cd;
TokenData internal td;
PoolData internal pd;
Pool2 internal p2;
QuotationData internal qd;
MCR internal m1;
uint private constant DECIMAL1E18 = uint(10) ** 18;
/**
* @dev Sets the status of claim using claim id.
* @param claimId claim id.
* @param stat status to be set.
*/
function setClaimStatus(uint claimId, uint stat) external onlyInternal {
_setClaimStatus(claimId, stat);
}
/**
* @dev Gets claim details of claim id = pending claim start + given index
*/
function getClaimFromNewStart(
uint index
)
external
view
returns (
uint coverId,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
(coverId, claimId, voteCA, voteMV, statusnumber) = cd.getClaimFromNewStart(index, msg.sender);
// status = rewardStatus[statusnumber].claimStatusDesc;
}
/**
* @dev Gets details of a claim submitted by the calling user, at a given index
*/
function getUserClaimByIndex(
uint index
)
external
view
returns(
uint status,
uint coverId,
uint claimId
)
{
uint statusno;
(statusno, coverId, claimId) = cd.getUserClaimByIndex(index, msg.sender);
status = statusno;
}
/**
* @dev Gets details of a given claim id.
* @param _claimId Claim Id.
* @return status Current status of claim id
* @return finalVerdict Decision made on the claim, 1 -> acceptance, -1 -> denial
* @return claimOwner Address through which claim is submitted
* @return coverId Coverid associated with the claim id
*/
function getClaimbyIndex(uint _claimId) external view returns (
uint claimId,
uint status,
int8 finalVerdict,
address claimOwner,
uint coverId
)
{
uint stat;
claimId = _claimId;
(, coverId, finalVerdict, stat, , ) = cd.getClaim(_claimId);
claimOwner = qd.getCoverMemberAddress(coverId);
status = stat;
}
/**
* @dev Calculates total amount that has been used to assess a claim.
* Computaion:Adds acceptCA(tokens used for voting in favor of a claim)
* denyCA(tokens used for voting against a claim) * current token price.
* @param claimId Claim Id.
* @param member Member type 0 -> Claim Assessors, else members.
* @return tokens Total Amount used in Claims assessment.
*/
function getCATokens(uint claimId, uint member) external view returns(uint tokens) {
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 curr = qd.getCurrencyOfCover(coverId);
uint tokenx1e18 = m1.calculateTokenPrice(curr);
uint accept;
uint deny;
if (member == 0) {
(, accept, deny) = cd.getClaimsTokenCA(claimId);
} else {
(, accept, deny) = cd.getClaimsTokenMV(claimId);
}
tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens)
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
tk = NXMToken(ms.tokenAddress());
td = TokenData(ms.getLatestAddress("TD"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tc = TokenController(ms.getLatestAddress("TC"));
p1 = Pool1(ms.getLatestAddress("P1"));
p2 = Pool2(ms.getLatestAddress("P2"));
pd = PoolData(ms.getLatestAddress("PD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
cd = ClaimsData(ms.getLatestAddress("CD"));
qd = QuotationData(ms.getLatestAddress("QD"));
m1 = MCR(ms.getLatestAddress("MC"));
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function changePendingClaimStart() public onlyInternal {
uint origstat;
uint state12Count;
uint pendingClaimStart = cd.pendingClaimStart();
uint actualClaimLength = cd.actualClaimLength();
for (uint i = pendingClaimStart; i < actualClaimLength; i++) {
(, , , origstat, , state12Count) = cd.getClaim(i);
if (origstat > 5 && ((origstat != 12) || (origstat == 12 && state12Count >= 60)))
cd.setpendingClaimStart(i);
else
break;
}
}
/**
* @dev Submits a claim for a given cover note.
* Adds claim to queue incase of emergency pause else directly submits the claim.
* @param coverId Cover Id.
*/
function submitClaim(uint coverId) public {
address qadd = qd.getCoverMemberAddress(coverId);
require(qadd == msg.sender);
uint8 cStatus;
(, cStatus, , , ) = qd.getCoverDetailsByCoverID2(coverId);
require(cStatus != uint8(QuotationData.CoverStatus.ClaimSubmitted), "Claim already submitted");
require(cStatus != uint8(QuotationData.CoverStatus.CoverExpired), "Cover already expired");
if (ms.isPause() == false) {
_addClaim(coverId, now, qadd);
} else {
cd.setClaimAtEmergencyPause(coverId, now, false);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.Requested));
}
}
/**
* @dev Submits the Claims queued once the emergency pause is switched off.
*/
function submitClaimAfterEPOff() public onlyInternal {
uint lengthOfClaimSubmittedAtEP = cd.getLengthOfClaimSubmittedAtEP();
uint firstClaimIndexToSubmitAfterEP = cd.getFirstClaimIndexToSubmitAfterEP();
uint coverId;
uint dateUpd;
bool submit;
address qadd;
for (uint i = firstClaimIndexToSubmitAfterEP; i < lengthOfClaimSubmittedAtEP; i++) {
(coverId, dateUpd, submit) = cd.getClaimOfEmergencyPauseByIndex(i);
require(submit == false);
qadd = qd.getCoverMemberAddress(coverId);
_addClaim(coverId, dateUpd, qadd);
cd.setClaimSubmittedAtEPTrue(i, true);
}
cd.setFirstClaimIndexToSubmitAfterEP(lengthOfClaimSubmittedAtEP);
}
/**
* @dev Castes vote for members who have tokens locked under Claims Assessment
* @param claimId claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now);
uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime()));
require(tokens > 0);
uint stat;
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat == 0);
require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0);
td.bookCATokens(msg.sender);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict);
uint voteLength = cd.getAllVoteLength();
cd.addClaimVoteCA(claimId, voteLength);
cd.setUserClaimVoteCA(msg.sender, claimId, voteLength);
cd.setClaimTokensCA(claimId, verdict, tokens);
tc.extendLockOf(msg.sender, "CLA", td.lockCADays());
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Submits a member vote for assessing a claim.
* Tokens other than those locked under Claims
* Assessment can be used to cast a vote for a given claim id.
* @param claimId Selected claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
uint stat;
uint tokens = tc.totalBalanceOf(msg.sender);
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat >= 1 && stat <= 5);
require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict);
tc.lockForMemberVote(msg.sender, td.lockMVDays());
uint voteLength = cd.getAllVoteLength();
cd.addClaimVotemember(claimId, voteLength);
cd.setUserClaimVoteMember(msg.sender, claimId, voteLength);
cd.setClaimTokensMV(claimId, verdict, tokens);
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Pause Voting of All Pending Claims when Emergency Pause Start.
*/
function pauseAllPendingClaimsVoting() public onlyInternal {
uint firstIndex = cd.pendingClaimStart();
uint actualClaimLength = cd.actualClaimLength();
for (uint i = firstIndex; i < actualClaimLength; i++) {
if (checkVoteClosing(i) == 0) {
uint dateUpd = cd.getClaimDateUpd(i);
cd.setPendingClaimDetails(i, (dateUpd.add(cd.maxVotingTime())).sub(now), false);
}
}
}
/**
* @dev Resume the voting phase of all Claims paused due to an emergency pause.
*/
function startAllPendingClaimsVoting() public onlyInternal {
uint firstIndx = cd.getFirstClaimIndexToStartVotingAfterEP();
uint i;
uint lengthOfClaimVotingPause = cd.getLengthOfClaimVotingPause();
for (i = firstIndx; i < lengthOfClaimVotingPause; i++) {
uint pendingTime;
uint claimID;
(claimID, pendingTime, ) = cd.getPendingClaimDetailsByIndex(i);
uint pTime = (now.sub(cd.maxVotingTime())).add(pendingTime);
cd.setClaimdateUpd(claimID, pTime);
cd.setPendingClaimVoteStatus(i, true);
uint coverid;
(, coverid) = cd.getClaimCoverId(claimID);
address qadd = qd.getCoverMemberAddress(coverid);
tf.extendCNEPOff(qadd, coverid, pendingTime.add(cd.claimDepositTime()));
p1.closeClaimsOraclise(claimID, uint64(pTime));
}
cd.setFirstClaimIndexToStartVotingAfterEP(i);
}
/**
* @dev Checks if voting of a claim should be closed or not.
* @param claimId Claim Id.
* @return close 1 -> voting should be closed, 0 -> if voting should not be closed,
* -1 -> voting has already been closed.
*/
function checkVoteClosing(uint claimId) public view returns(int8 close) {
close = 0;
uint status;
(, status) = cd.getClaimStatusNumber(claimId);
uint dateUpd = cd.getClaimDateUpd(claimId);
if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) {
if (cd.getClaimState12Count(claimId) < 60)
close = 1;
}
if (status > 5 && status != 12) {
close = -1;
} else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) {
close = 1;
} else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) {
close = 0;
} else if (status == 0 || (status >= 1 && status <= 5)) {
close = _checkVoteClosingFinal(claimId, status);
}
}
/**
* @dev Checks if voting of a claim should be closed or not.
* Internally called by checkVoteClosing method
* for Claims whose status number is 0 or status number lie between 2 and 6.
* @param claimId Claim Id.
* @param status Current status of claim.
* @return close 1 if voting should be closed,0 in case voting should not be closed,
* -1 if voting has already been closed.
*/
function _checkVoteClosingFinal(uint claimId, uint status) internal view returns(int8 close) {
close = 0;
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 curr = qd.getCurrencyOfCover(coverId);
uint tokenx1e18 = m1.calculateTokenPrice(curr);
uint accept;
uint deny;
(, accept, deny) = cd.getClaimsTokenCA(claimId);
uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
(, accept, deny) = cd.getClaimsTokenMV(claimId);
uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
if (status == 0 && caTokens >= sumassured.mul(10)) {
close = 1;
} else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) {
close = 1;
}
}
/**
* @dev Changes the status of an existing claim id, based on current
* status and current conditions of the system
* @param claimId Claim Id.
* @param stat status number.
*/
function _setClaimStatus(uint claimId, uint stat) internal {
uint origstat;
uint state12Count;
uint dateUpd;
uint coverId;
(, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId);
(, origstat) = cd.getClaimStatusNumber(claimId);
if (stat == 12 && origstat == 12) {
cd.updateState12Count(claimId, 1);
}
cd.setClaimStatus(claimId, stat);
if (state12Count >= 60 && stat == 12) {
cd.setClaimStatus(claimId, 13);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied));
}
uint time = now;
cd.setClaimdateUpd(claimId, time);
if (stat >= 2 && stat <= 5) {
p1.closeClaimsOraclise(claimId, cd.maxVotingTime());
}
if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) <= now) && (state12Count < 60)) {
p1.closeClaimsOraclise(claimId, cd.payoutRetryTime());
} else if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) > now) && (state12Count < 60)) {
uint64 timeLeft = uint64((dateUpd.add(cd.payoutRetryTime())).sub(now));
p1.closeClaimsOraclise(claimId, timeLeft);
}
}
/**
* @dev Submits a claim for a given cover note.
* Set deposits flag against cover.
*/
function _addClaim(uint coverId, uint time, address add) internal {
tf.depositCN(coverId);
uint len = cd.actualClaimLength();
cd.addClaim(len, coverId, add, now);
cd.callClaimEvent(coverId, add, len, time);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted));
bytes4 curr = qd.getCurrencyOfCover(coverId);
uint sumAssured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).add(sumAssured));
p2.internalLiquiditySwap(curr);
p1.closeClaimsOraclise(len, cd.maxVotingTime());
}
}
// File: nexusmutual-contracts/contracts/ClaimsReward.sol
/* Copyright (C) 2020 NexusMutual.io
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/ */
//Claims Reward Contract contains the functions for calculating number of tokens
// that will get rewarded, unlocked or burned depending upon the status of claim.
pragma solidity 0.5.7;
contract ClaimsReward is Iupgradable {
using SafeMath for uint;
NXMToken internal tk;
TokenController internal tc;
TokenFunctions internal tf;
TokenData internal td;
QuotationData internal qd;
Claims internal c1;
ClaimsData internal cd;
Pool1 internal p1;
Pool2 internal p2;
PoolData internal pd;
Governance internal gv;
IPooledStaking internal pooledStaking;
uint private constant DECIMAL1E18 = uint(10) ** 18;
function changeDependentContractAddress() public onlyInternal {
c1 = Claims(ms.getLatestAddress("CL"));
cd = ClaimsData(ms.getLatestAddress("CD"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
p1 = Pool1(ms.getLatestAddress("P1"));
p2 = Pool2(ms.getLatestAddress("P2"));
pd = PoolData(ms.getLatestAddress("PD"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
/// @dev Decides the next course of action for a given claim.
function changeClaimStatus(uint claimid) public checkPause onlyInternal {
uint coverid;
(, coverid) = cd.getClaimCoverId(claimid);
uint status;
(, status) = cd.getClaimStatusNumber(claimid);
// when current status is "Pending-Claim Assessor Vote"
if (status == 0) {
_changeClaimStatusCA(claimid, coverid, status);
} else if (status >= 1 && status <= 5) {
_changeClaimStatusMV(claimid, coverid, status);
} else if (status == 12) { // when current status is "Claim Accepted Payout Pending"
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
address payable coverHolder = qd.getCoverMemberAddress(coverid);
bytes4 coverCurrency = qd.getCurrencyOfCover(coverid);
bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, coverHolder, coverCurrency);
if (success) {
tf.burnStakedTokens(coverid, coverCurrency, sumAssured);
c1.setClaimStatus(claimid, 14);
}
}
c1.changePendingClaimStart();
}
/// @dev Amount of tokens to be rewarded to a user for a particular vote id.
/// @param check 1 -> CA vote, else member vote
/// @param voteid vote id for which reward has to be Calculated
/// @param flag if 1 calculate even if claimed,else don't calculate if already claimed
/// @return tokenCalculated reward to be given for vote id
/// @return lastClaimedCheck true if final verdict is still pending for that voteid
/// @return tokens number of tokens locked under that voteid
/// @return perc percentage of reward to be given.
function getRewardToBeGiven(
uint check,
uint voteid,
uint flag
)
public
view
returns (
uint tokenCalculated,
bool lastClaimedCheck,
uint tokens,
uint perc
)
{
uint claimId;
int8 verdict;
bool claimed;
uint tokensToBeDist;
uint totalTokens;
(tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid);
lastClaimedCheck = false;
int8 claimVerdict = cd.getFinalVerdict(claimId);
if (claimVerdict == 0) {
lastClaimedCheck = true;
}
if (claimVerdict == verdict && (claimed == false || flag == 1)) {
if (check == 1) {
(perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId);
} else {
(, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId);
}
if (perc > 0) {
if (check == 1) {
if (verdict == 1) {
(, totalTokens, ) = cd.getClaimsTokenCA(claimId);
} else {
(, , totalTokens) = cd.getClaimsTokenCA(claimId);
}
} else {
if (verdict == 1) {
(, totalTokens, ) = cd.getClaimsTokenMV(claimId);
}else {
(, , totalTokens) = cd.getClaimsTokenMV(claimId);
}
}
tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100));
}
}
}
/// @dev Transfers all tokens held by contract to a new contract in case of upgrade.
function upgrade(address _newAdd) public onlyInternal {
uint amount = tk.balanceOf(address(this));
if (amount > 0) {
require(tk.transfer(_newAdd, amount));
}
}
/// @dev Total reward in token due for claim by a user.
/// @return total total number of tokens
function getRewardToBeDistributedByUser(address _add) public view returns(uint total) {
uint lengthVote = cd.getVoteAddressCALength(_add);
uint lastIndexCA;
uint lastIndexMV;
uint tokenForVoteId;
uint voteId;
(lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add);
for (uint i = lastIndexCA; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(_add, i);
(tokenForVoteId, , , ) = getRewardToBeGiven(1, voteId, 0);
total = total.add(tokenForVoteId);
}
lengthVote = cd.getVoteAddressMemberLength(_add);
for (uint j = lastIndexMV; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(_add, j);
(tokenForVoteId, , , ) = getRewardToBeGiven(0, voteId, 0);
total = total.add(tokenForVoteId);
}
return (total);
}
/// @dev Gets reward amount and claiming status for a given claim id.
/// @return reward amount of tokens to user.
/// @return claimed true if already claimed false if yet to be claimed.
function getRewardAndClaimedStatus(uint check, uint claimId) public view returns(uint reward, bool claimed) {
uint voteId;
uint claimid;
uint lengthVote;
if (check == 1) {
lengthVote = cd.getVoteAddressCALength(msg.sender);
for (uint i = 0; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(msg.sender, i);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) { break; }
}
} else {
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
for (uint j = 0; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(msg.sender, j);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) { break; }
}
}
(reward, , , ) = getRewardToBeGiven(check, voteId, 1);
}
/**
* @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance
* Claim assesment, Risk assesment, Governance rewards
*/
function claimAllPendingReward(uint records) public isMemberAndcheckPause {
_claimRewardToBeDistributed(records);
pooledStaking.withdrawReward(msg.sender);
uint governanceRewards = gv.claimReward(msg.sender, records);
if (governanceRewards > 0) {
require(tk.transfer(msg.sender, governanceRewards));
}
}
/**
* @dev Function used to get pending rewards of a particular user address.
* @param _add user address.
* @return total reward amount of the user
*/
function getAllPendingRewardOfUser(address _add) public view returns(uint) {
uint caReward = getRewardToBeDistributedByUser(_add);
uint pooledStakingReward = pooledStaking.stakerReward(_add);
uint governanceReward = gv.getPendingReward(_add);
return caReward.add(pooledStakingReward).add(governanceReward);
}
/// @dev Rewards/Punishes users who participated in Claims assessment.
// Unlocking and burning of the tokens will also depend upon the status of claim.
/// @param claimid Claim Id.
function _rewardAgainstClaim(uint claimid, uint coverid, uint sumAssured, uint status) internal {
uint premiumNXM = qd.getCoverPremiumNXM(coverid);
bytes4 curr = qd.getCurrencyOfCover(coverid);
uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100);// 20% of premium
uint percCA;
uint percMV;
(percCA, percMV) = cd.getRewardStatus(status);
cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens);
if (percCA > 0 || percMV > 0) {
tc.mint(address(this), distributableTokens);
}
if (status == 6 || status == 9 || status == 11) {
cd.changeFinalVerdict(claimid, -1);
td.setDepositCN(coverid, false); // Unset flag
tf.burnDepositCN(coverid); // burn Deposited CN
pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).sub(sumAssured));
p2.internalLiquiditySwap(curr);
} else if (status == 7 || status == 8 || status == 10) {
cd.changeFinalVerdict(claimid, 1);
td.setDepositCN(coverid, false); // Unset flag
tf.unlockCN(coverid);
bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, qd.getCoverMemberAddress(coverid), curr);
if (success) {
tf.burnStakedTokens(coverid, curr, sumAssured);
}
}
}
/// @dev Computes the result of Claim Assessors Voting for a given claim id.
function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency.
uint accept;
uint deny;
uint acceptAndDeny;
bool rewardOrPunish;
uint sumAssured;
(, accept) = cd.getClaimVote(claimid, 1);
(, deny) = cd.getClaimVote(claimid, -1);
acceptAndDeny = accept.add(deny);
accept = accept.mul(100);
deny = deny.mul(100);
if (caTokens == 0) {
status = 3;
} else {
sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
// Min threshold reached tokens used for voting > 5* sum assured
if (caTokens > sumAssured.mul(5)) {
if (accept.div(acceptAndDeny) > 70) {
status = 7;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted));
rewardOrPunish = true;
} else if (deny.div(acceptAndDeny) > 70) {
status = 6;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied));
rewardOrPunish = true;
} else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 4;
} else {
status = 5;
}
} else {
if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 2;
} else {
status = 3;
}
}
}
c1.setClaimStatus(claimid, status);
if (rewardOrPunish) {
_rewardAgainstClaim(claimid, coverid, sumAssured, status);
}
}
}
/// @dev Computes the result of Member Voting for a given claim id.
function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint8 coverStatus;
uint statusOrig = status;
uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency.
// If tokens used for acceptance >50%, claim is accepted
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
uint thresholdUnreached = 0;
// Minimum threshold for member voting is reached only when
// value of tokens used for voting > 5* sum assured of claim id
if (mvTokens < sumAssured.mul(5)) {
thresholdUnreached = 1;
}
uint accept;
(, accept) = cd.getClaimMVote(claimid, 1);
uint deny;
(, deny) = cd.getClaimMVote(claimid, -1);
if (accept.add(deny) > 0) {
if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 8;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 9;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
}
if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) {
status = 10;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) {
status = 11;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
c1.setClaimStatus(claimid, status);
qd.changeCoverStatusNo(coverid, uint8(coverStatus));
// Reward/Punish Claim Assessors and Members who participated in Claims assessment
_rewardAgainstClaim(claimid, coverid, sumAssured, status);
}
}
/// @dev Allows a user to claim all pending Claims assessment rewards.
function _claimRewardToBeDistributed(uint _records) internal {
uint lengthVote = cd.getVoteAddressCALength(msg.sender);
uint voteid;
uint lastIndex;
(lastIndex, ) = cd.getRewardDistributedIndex(msg.sender);
uint total = 0;
uint tokenForVoteId = 0;
bool lastClaimedCheck;
uint _days = td.lockCADays();
bool claimed;
uint counter = 0;
uint claimId;
uint perc;
uint i;
uint lastClaimed = lengthVote;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressCA(msg.sender, i);
(tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (perc > 0 && !claimed) {
counter++;
cd.setRewardClaimed(voteid, true);
} else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) {
(perc, , ) = cd.getClaimRewardDetail(claimId);
if (perc == 0) {
counter++;
}
cd.setRewardClaimed(voteid, true);
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexCA(msg.sender, i);
}
else {
cd.setRewardDistributedIndexCA(msg.sender, lastClaimed);
}
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
lastClaimed = lengthVote;
_days = _days.mul(counter);
if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) {
tc.reduceLock(msg.sender, "CLA", _days);
}
(, lastIndex) = cd.getRewardDistributedIndex(msg.sender);
lastClaimed = lengthVote;
counter = 0;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressMember(msg.sender, i);
(tokenForVoteId, lastClaimedCheck, , ) = getRewardToBeGiven(0, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (claimed == false && cd.getFinalVerdict(claimId) != 0) {
cd.setRewardClaimed(voteid, true);
counter++;
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (total > 0) {
require(tk.transfer(msg.sender, total));
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexMV(msg.sender, i);
}
else {
cd.setRewardDistributedIndexMV(msg.sender, lastClaimed);
}
}
/**
* @dev Function used to claim the commission earned by the staker.
*/
function _claimStakeCommission(uint _records, address _user) external onlyInternal {
uint total=0;
uint len = td.getStakerStakedContractLength(_user);
uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user);
uint commissionEarned;
uint commissionRedeemed;
uint maxCommission;
uint lastCommisionRedeemed = len;
uint counter;
uint i;
for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) {
commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i);
commissionEarned = td.getStakerEarnedStakeCommission(_user, i);
maxCommission = td.getStakerInitialStakedAmountOnContract(
_user, i).mul(td.stakerMaxCommissionPer()).div(100);
if (lastCommisionRedeemed == len && maxCommission != commissionEarned)
lastCommisionRedeemed = i;
td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed));
total = total.add(commissionEarned.sub(commissionRedeemed));
counter++;
}
if (lastCommisionRedeemed == len) {
td.setLastCompletedStakeCommissionIndex(_user, i);
} else {
td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed);
}
if (total > 0)
require(tk.transfer(_user, total)); //solhint-disable-line
}
}
// File: nexusmutual-contracts/contracts/MemberRoles.sol
/* Copyright (C) 2017 GovBlocks.io
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/ */
pragma solidity 0.5.7;
contract MemberRoles is IMemberRoles, Governed, Iupgradable {
TokenController public dAppToken;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
TokenFunctions internal tf;
NXMToken public tk;
struct MemberRoleDetails {
uint memberCounter;
mapping(address => bool) memberActive;
address[] memberAddress;
address authorized;
}
enum Role {UnAssigned, AdvisoryBoard, Member, Owner}
event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);
MemberRoleDetails[] internal memberRoleData;
bool internal constructorCheck;
uint public maxABCount;
bool public launched;
uint public launchedOn;
modifier checkRoleAuthority(uint _memberRoleId) {
if (memberRoleData[_memberRoleId].authorized != address(0))
require(msg.sender == memberRoleData[_memberRoleId].authorized);
else
require(isAuthorizedToGovern(msg.sender), "Not Authorized");
_;
}
/**
* @dev to swap advisory board member
* @param _newABAddress is address of new AB member
* @param _removeAB is advisory board member to be removed
*/
function swapABMember (
address _newABAddress,
address _removeAB
)
external
checkRoleAuthority(uint(Role.AdvisoryBoard)) {
_updateRole(_newABAddress, uint(Role.AdvisoryBoard), true);
_updateRole(_removeAB, uint(Role.AdvisoryBoard), false);
}
/**
* @dev to swap the owner address
* @param _newOwnerAddress is the new owner address
*/
function swapOwner (
address _newOwnerAddress
)
external {
require(msg.sender == address(ms));
_updateRole(ms.owner(), uint(Role.Owner), false);
_updateRole(_newOwnerAddress, uint(Role.Owner), true);
}
/**
* @dev is used to add initital advisory board members
* @param abArray is the list of initial advisory board members
*/
function addInitialABMembers(address[] calldata abArray) external onlyOwner {
//Ensure that NXMaster has initialized.
require(ms.masterInitialized());
require(maxABCount >=
SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length)
);
//AB count can't exceed maxABCount
for (uint i = 0; i < abArray.length; i++) {
require(checkRole(abArray[i], uint(MemberRoles.Role.Member)));
_updateRole(abArray[i], uint(Role.AdvisoryBoard), true);
}
}
/**
* @dev to change max number of AB members allowed
* @param _val is the new value to be set
*/
function changeMaxABCount(uint _val) external onlyInternal {
maxABCount = _val;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
td = TokenData(ms.getLatestAddress("TD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tk = NXMToken(ms.tokenAddress());
dAppToken = TokenController(ms.getLatestAddress("TC"));
}
/**
* @dev to change the master address
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0))
require(masterAddress == msg.sender);
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev to initiate the member roles
* @param _firstAB is the address of the first AB member
* @param memberAuthority is the authority (role) of the member
*/
function memberRolesInitiate (address _firstAB, address memberAuthority) public {
require(!constructorCheck);
_addInitialMemberRoles(_firstAB, memberAuthority);
constructorCheck = true;
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole( //solhint-disable-line
bytes32 _roleName,
string memory _roleDescription,
address _authorized
)
public
onlyAuthorizedToGovern {
_addRole(_roleName, _roleDescription, _authorized);
}
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole( //solhint-disable-line
address _memberAddress,
uint _roleId,
bool _active
)
public
checkRoleAuthority(_roleId) {
_updateRole(_memberAddress, _roleId, _active);
}
/**
* @dev to add members before launch
* @param userArray is list of addresses of members
* @param tokens is list of tokens minted for each array element
*/
function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner {
require(!launched);
for (uint i=0; i < userArray.length; i++) {
require(!ms.isMember(userArray[i]));
dAppToken.addToWhitelist(userArray[i]);
_updateRole(userArray[i], uint(Role.Member), true);
dAppToken.mint(userArray[i], tokens[i]);
}
launched = true;
launchedOn = now;
}
/**
* @dev Called by user to pay joining membership fee
*/
function payJoiningFee(address _userAddress) public payable {
require(_userAddress != address(0));
require(!ms.isPause(), "Emergency Pause Applied");
if (msg.sender == address(ms.getLatestAddress("QT"))) {
require(td.walletAddress() != address(0), "No walletAddress present");
dAppToken.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(msg.value);
} else {
require(!qd.refundEligible(_userAddress));
require(!ms.isMember(_userAddress));
require(msg.value == td.joiningFee());
qd.setRefundEligible(_userAddress, true);
}
}
/**
* @dev to perform kyc verdict
* @param _userAddress whose kyc is being performed
* @param verdict of kyc process
*/
function kycVerdict(address payable _userAddress, bool verdict) public {
require(msg.sender == qd.kycAuthAddress());
require(!ms.isPause());
require(_userAddress != address(0));
require(!ms.isMember(_userAddress));
require(qd.refundEligible(_userAddress));
if (verdict) {
qd.setRefundEligible(_userAddress, false);
uint fee = td.joiningFee();
dAppToken.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(fee); //solhint-disable-line
} else {
qd.setRefundEligible(_userAddress, false);
_userAddress.transfer(td.joiningFee()); //solhint-disable-line
}
}
/**
* @dev Called by existed member if wish to Withdraw membership.
*/
function withdrawMembership() public {
require(!ms.isPause() && ms.isMember(msg.sender));
require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).
require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens");
gv.removeDelegation(msg.sender);
dAppToken.burnFrom(msg.sender, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
dAppToken.removeFromWhitelist(msg.sender); // need clarification on whitelist
}
/**
* @dev Called by existed member if wish to switch membership to other address.
* @param _add address of user to forward membership.
*/
function switchMembership(address _add) external {
require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add));
require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).
require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens");
gv.removeDelegation(msg.sender);
dAppToken.addToWhitelist(_add);
_updateRole(_add, uint(Role.Member), true);
tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
dAppToken.removeFromWhitelist(msg.sender);
emit switchedMembership(msg.sender, _add, now);
}
/// @dev Return number of member roles
function totalRoles() public view returns(uint256) { //solhint-disable-line
return memberRoleData.length;
}
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _newAuthorized New authorized address against role id
function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) { //solhint-disable-line
memberRoleData[_roleId].authorized = _newAuthorized;
}
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns(uint, address[] memory memberArray) { //solhint-disable-line
uint length = memberRoleData[_memberRoleId].memberAddress.length;
uint i;
uint j = 0;
memberArray = new address[](memberRoleData[_memberRoleId].memberCounter);
for (i = 0; i < length; i++) {
address member = memberRoleData[_memberRoleId].memberAddress[i];
if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) { //solhint-disable-line
memberArray[j] = member;
j++;
}
}
return (_memberRoleId, memberArray);
}
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberCounter Member length
function numberOfMembers(uint _memberRoleId) public view returns(uint) { //solhint-disable-line
return memberRoleData[_memberRoleId].memberCounter;
}
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns(address) { //solhint-disable-line
return memberRoleData[_memberRoleId].authorized;
}
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns(uint[] memory) { //solhint-disable-line
uint length = memberRoleData.length;
uint[] memory assignedRoles = new uint[](length);
uint counter = 0;
for (uint i = 1; i < length; i++) {
if (memberRoleData[i].memberActive[_memberAddress]) {
assignedRoles[counter] = i;
counter++;
}
}
return assignedRoles;
}
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns(bool) { //solhint-disable-line
if (_roleId == uint(Role.UnAssigned))
return true;
else
if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line
return true;
else
return false;
}
/// @dev Return total number of members assigned against each role id.
/// @return totalMembers Total members in particular role id
function getMemberLengthForAllRoles() public view returns(uint[] memory totalMembers) { //solhint-disable-line
totalMembers = new uint[](memberRoleData.length);
for (uint i = 0; i < memberRoleData.length; i++) {
totalMembers[i] = numberOfMembers(i);
}
}
/**
* @dev to update the member roles
* @param _memberAddress in concern
* @param _roleId the id of role
* @param _active if active is true, add the member, else remove it
*/
function _updateRole(address _memberAddress,
uint _roleId,
bool _active) internal {
// require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically");
if (_active) {
require(!memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1);
memberRoleData[_roleId].memberActive[_memberAddress] = true;
memberRoleData[_roleId].memberAddress.push(_memberAddress);
} else {
require(memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1);
delete memberRoleData[_roleId].memberActive[_memberAddress];
}
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function _addRole(
bytes32 _roleName,
string memory _roleDescription,
address _authorized
) internal {
emit MemberRole(memberRoleData.length, _roleName, _roleDescription);
memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized));
}
/**
* @dev to check if member is in the given member array
* @param _memberAddress in concern
* @param memberArray in concern
* @return boolean to represent the presence
*/
function _checkMemberInArray(
address _memberAddress,
address[] memory memberArray
)
internal
pure
returns(bool memberExists)
{
uint i;
for (i = 0; i < memberArray.length; i++) {
if (memberArray[i] == _memberAddress) {
memberExists = true;
break;
}
}
}
/**
* @dev to add initial member roles
* @param _firstAB is the member address to be added
* @param memberAuthority is the member authority(role) to be added for
*/
function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal {
maxABCount = 5;
_addRole("Unassigned", "Unassigned", address(0));
_addRole(
"Advisory Board",
"Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line
address(0)
);
_addRole(
"Member",
"Represents all users of Mutual.", //solhint-disable-line
memberAuthority
);
_addRole(
"Owner",
"Represents Owner of Mutual.", //solhint-disable-line
address(0)
);
// _updateRole(_firstAB, uint(Role.AdvisoryBoard), true);
_updateRole(_firstAB, uint(Role.Owner), true);
// _updateRole(_firstAB, uint(Role.Member), true);
launchedOn = 0;
}
function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) {
address memberAddress = memberRoleData[_memberRoleId].memberAddress[index];
return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]);
}
function membersLength(uint _memberRoleId) external view returns (uint) {
return memberRoleData[_memberRoleId].memberAddress.length;
}
}
// File: nexusmutual-contracts/contracts/ProposalCategory.sol
/* Copyright (C) 2017 GovBlocks.io
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/ */
pragma solidity 0.5.7;
contract ProposalCategory is Governed, IProposalCategory, Iupgradable {
bool public constructorCheck;
MemberRoles internal mr;
struct CategoryStruct {
uint memberRoleToVote;
uint majorityVotePerc;
uint quorumPerc;
uint[] allowedToCreateProposal;
uint closingTime;
uint minStake;
}
struct CategoryAction {
uint defaultIncentive;
address contractAddress;
bytes2 contractName;
}
CategoryStruct[] internal allCategory;
mapping (uint => CategoryAction) internal categoryActionData;
mapping (uint => uint) public categoryABReq;
mapping (uint => uint) public isSpecialResolution;
mapping (uint => bytes) public categoryActionHashes;
bool public categoryActionHashUpdated;
/**
* @dev Restricts calls to deprecated functions
*/
modifier deprecated() {
revert("Function deprecated");
_;
}
/**
* @dev Adds new category (Discontinued, moved functionality to newCategory)
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
)
external
deprecated
{
}
/**
* @dev Initiates Default settings for Proposal Category contract (Adding default categories)
*/
function proposalCategoryInitiate() external deprecated { //solhint-disable-line
}
/**
* @dev Initiates Default action function hashes for existing categories
* To be called after the contract has been upgraded by governance
*/
function updateCategoryActionHashes() external onlyOwner {
require(!categoryActionHashUpdated, "Category action hashes already updated");
categoryActionHashUpdated = true;
categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)");
categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)");
categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line
categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line
categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)");
categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()");
categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)");
categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)");
categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)");
categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)");
categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)");//solhint-disable-line
categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)");
categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)");
categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)");
categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)");
categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)");
categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)");
categoryActionHashes[29] = abi.encodeWithSignature("upgradeContract(bytes2,address)");
categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)");
categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)");
categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)");//solhint-disable-line
categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()");
}
/**
* @dev Gets Total number of categories added till now
*/
function totalCategories() external view returns(uint) {
return allCategory.length;
}
/**
* @dev Gets category details
*/
function category(uint _categoryId) external view returns(uint, uint, uint, uint, uint[] memory, uint, uint) {
return(
_categoryId,
allCategory[_categoryId].memberRoleToVote,
allCategory[_categoryId].majorityVotePerc,
allCategory[_categoryId].quorumPerc,
allCategory[_categoryId].allowedToCreateProposal,
allCategory[_categoryId].closingTime,
allCategory[_categoryId].minStake
);
}
/**
* @dev Gets category ab required and isSpecialResolution
* @return the category id
* @return if AB voting is required
* @return is category a special resolution
*/
function categoryExtendedData(uint _categoryId) external view returns(uint, uint, uint) {
return(
_categoryId,
categoryABReq[_categoryId],
isSpecialResolution[_categoryId]
);
}
/**
* @dev Gets the category acion details
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
*/
function categoryAction(uint _categoryId) external view returns(uint, address, bytes2, uint) {
return(
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive
);
}
/**
* @dev Gets the category acion details of a category id
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
* @return action function hash
*/
function categoryActionDetails(uint _categoryId) external view returns(uint, address, bytes2, uint, bytes memory) {
return(
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive,
categoryActionHashes[_categoryId]
);
}
/**
* @dev Updates dependant contract addresses
*/
function changeDependentContractAddress() public {
mr = MemberRoles(ms.getLatestAddress("MR"));
}
/**
* @dev Adds new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function newCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
_addCategory(
_name,
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_actionHash,
_contractAddress,
_contractName,
_incentives
);
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash);
}
}
/**
* @dev Changes the master address and update it's instance
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0))
require(masterAddress == msg.sender);
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev Updates category details (Discontinued, moved functionality to editCategory)
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
public
deprecated
{
}
/**
* @dev Updates category details
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function editCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
delete categoryActionHashes[_categoryId];
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash);
}
allCategory[_categoryId].memberRoleToVote = _memberRoleToVote;
allCategory[_categoryId].majorityVotePerc = _majorityVotePerc;
allCategory[_categoryId].closingTime = _closingTime;
allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal;
allCategory[_categoryId].minStake = _incentives[0];
allCategory[_categoryId].quorumPerc = _quorumPerc;
categoryActionData[_categoryId].defaultIncentive = _incentives[1];
categoryActionData[_categoryId].contractName = _contractName;
categoryActionData[_categoryId].contractAddress = _contractAddress;
categoryABReq[_categoryId] = _incentives[2];
isSpecialResolution[_categoryId] = _incentives[3];
emit Category(_categoryId, _name, _actionHash);
}
/**
* @dev Internal call to add new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function _addCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
internal
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
allCategory.push(
CategoryStruct(
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_incentives[0]
)
);
uint categoryId = allCategory.length - 1;
categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName);
categoryABReq[categoryId] = _incentives[2];
isSpecialResolution[categoryId] = _incentives[3];
emit Category(categoryId, _name, _actionHash);
}
/**
* @dev Internal call to check if given roles are valid or not
*/
function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal)
internal view returns(uint) {
uint totalRoles = mr.totalRoles();
if (_memberRoleToVote >= totalRoles) {
return 0;
}
for (uint i = 0; i < _allowedToCreateProposal.length; i++) {
if (_allowedToCreateProposal[i] >= totalRoles) {
return 0;
}
}
return 1;
}
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IGovernance.sol
/* Copyright (C) 2017 GovBlocks.io
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/ */
pragma solidity 0.5.7;
contract IGovernance {
event Proposal(
address indexed proposalOwner,
uint256 indexed proposalId,
uint256 dateAdd,
string proposalTitle,
string proposalSD,
string proposalDescHash
);
event Solution(
uint256 indexed proposalId,
address indexed solutionOwner,
uint256 indexed solutionId,
string solutionDescHash,
uint256 dateAdd
);
event Vote(
address indexed from,
uint256 indexed proposalId,
uint256 indexed voteId,
uint256 dateAdd,
uint256 solutionChosen
);
event RewardClaimed(
address indexed member,
uint gbtReward
);
/// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal.
event VoteCast (uint256 proposalId);
/// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can
/// call any offchain actions
event ProposalAccepted (uint256 proposalId);
/// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time.
event CloseProposalOnTime (
uint256 indexed proposalId,
uint256 time
);
/// @dev ActionSuccess event is called whenever an onchain action is executed.
event ActionSuccess (
uint256 proposalId
);
/// @dev Creates a new proposal
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external;
/// @dev Edits the details of an existing proposal and creates new version
/// @param _proposalId Proposal id that details needs to be updated
/// @param _proposalDescHash Proposal description hash having long and short description of proposal.
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external;
/// @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentives
)
external;
/// @dev Initiates add solution
/// @param _solutionHash Solution hash having required data against adding solution
function addSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Opens proposal for voting
function openProposalForVoting(uint _proposalId) external;
/// @dev Submit proposal with solution
/// @param _proposalId Proposal id
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Creates a new proposal with solution and votes for the solution
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Casts vote
/// @param _proposalId Proposal id
/// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution
function submitVote(uint _proposalId, uint _solutionChosen) external;
function closeProposal(uint _proposalId) external;
function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward);
function proposal(uint _proposalId)
external
view
returns(
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalReward
);
function canCloseProposal(uint _proposalId) public view returns(uint closeValue);
function pauseProposal(uint _proposalId) public;
function resumeProposal(uint _proposalId) public;
function allowedToCatgorize() public view returns(uint roleId);
}
// File: nexusmutual-contracts/contracts/Governance.sol
// /* Copyright (C) 2017 GovBlocks.io
// 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/ */
pragma solidity 0.5.7;
contract Governance is IGovernance, Iupgradable {
using SafeMath for uint;
enum ProposalStatus {
Draft,
AwaitingSolution,
VotingStarted,
Accepted,
Rejected,
Majority_Not_Reached_But_Accepted,
Denied
}
struct ProposalData {
uint propStatus;
uint finalVerdict;
uint category;
uint commonIncentive;
uint dateUpd;
address owner;
}
struct ProposalVote {
address voter;
uint proposalId;
uint dateAdd;
}
struct VoteTally {
mapping(uint=>uint) memberVoteValue;
mapping(uint=>uint) abVoteValue;
uint voters;
}
struct DelegateVote {
address follower;
address leader;
uint lastUpd;
}
ProposalVote[] internal allVotes;
DelegateVote[] public allDelegation;
mapping(uint => ProposalData) internal allProposalData;
mapping(uint => bytes[]) internal allProposalSolutions;
mapping(address => uint[]) internal allVotesByMember;
mapping(uint => mapping(address => bool)) public rewardClaimed;
mapping (address => mapping(uint => uint)) public memberProposalVote;
mapping (address => uint) public followerDelegation;
mapping (address => uint) internal followerCount;
mapping (address => uint[]) internal leaderDelegation;
mapping (uint => VoteTally) public proposalVoteTally;
mapping (address => bool) public isOpenForDelegation;
mapping (address => uint) public lastRewardClaimed;
bool internal constructorCheck;
uint public tokenHoldingTime;
uint internal roleIdAllowedToCatgorize;
uint internal maxVoteWeigthPer;
uint internal specialResolutionMajPerc;
uint internal maxFollowers;
uint internal totalProposals;
uint internal maxDraftTime;
MemberRoles internal memberRole;
ProposalCategory internal proposalCategory;
TokenController internal tokenInstance;
mapping(uint => uint) public proposalActionStatus;
mapping(uint => uint) internal proposalExecutionTime;
mapping(uint => mapping(address => bool)) public proposalRejectedByAB;
mapping(uint => uint) internal actionRejectedCount;
bool internal actionParamsInitialised;
uint internal actionWaitingTime;
uint constant internal AB_MAJ_TO_REJECT_ACTION = 3;
enum ActionStatus {
Pending,
Accepted,
Rejected,
Executed,
NoAction
}
/**
* @dev Called whenever an action execution is failed.
*/
event ActionFailed (
uint256 proposalId
);
/**
* @dev Called whenever an AB member rejects the action execution.
*/
event ActionRejected (
uint256 indexed proposalId,
address rejectedBy
);
/**
* @dev Checks if msg.sender is proposal owner
*/
modifier onlyProposalOwner(uint _proposalId) {
require(msg.sender == allProposalData[_proposalId].owner, "Not allowed");
_;
}
/**
* @dev Checks if proposal is opened for voting
*/
modifier voteNotStarted(uint _proposalId) {
require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted));
_;
}
/**
* @dev Checks if msg.sender is allowed to create proposal under given category
*/
modifier isAllowed(uint _categoryId) {
require(allowedToCreateProposal(_categoryId), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender is allowed categorize proposal under given category
*/
modifier isAllowedToCategorize() {
require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender had any pending rewards to be claimed
*/
modifier checkPendingRewards {
require(getPendingReward(msg.sender) == 0, "Claim reward");
_;
}
/**
* @dev Event emitted whenever a proposal is categorized
*/
event ProposalCategorized(
uint indexed proposalId,
address indexed categorizedBy,
uint categoryId
);
/**
* @dev Removes delegation of an address.
* @param _add address to undelegate.
*/
function removeDelegation(address _add) external onlyInternal {
_unDelegate(_add);
}
/**
* @dev Creates a new proposal
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
*/
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external isAllowed(_categoryId)
{
require(ms.isMember(msg.sender), "Not Member");
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
}
/**
* @dev Edits the details of an existing proposal
* @param _proposalId Proposal id that details needs to be updated
* @param _proposalDescHash Proposal description hash having long and short description of proposal.
*/
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external onlyProposalOwner(_proposalId)
{
require(
allProposalSolutions[_proposalId].length < 2,
"Not allowed"
);
allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft);
allProposalData[_proposalId].category = 0;
allProposalData[_proposalId].commonIncentive = 0;
emit Proposal(
allProposalData[_proposalId].owner,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
}
/**
* @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
*/
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
external
voteNotStarted(_proposalId) isAllowedToCategorize
{
_categorizeProposal(_proposalId, _categoryId, _incentive);
}
/**
* @dev Initiates add solution
* To implement the governance interface
*/
function addSolution(uint, string calldata, bytes calldata) external {
}
/**
* @dev Opens proposal for voting
* To implement the governance interface
*/
function openProposalForVoting(uint) external {
}
/**
* @dev Submit proposal with solution
* @param _proposalId Proposal id
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external
onlyProposalOwner(_proposalId)
{
require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution));
_proposalSubmission(_proposalId, _solutionHash, _action);
}
/**
* @dev Creates a new proposal with solution
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external isAllowed(_categoryId)
{
uint proposalId = totalProposals;
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
require(_categoryId > 0);
_proposalSubmission(
proposalId,
_solutionHash,
_action
);
}
/**
* @dev Submit a vote on the proposal.
* @param _proposalId to vote upon.
* @param _solutionChosen is the chosen vote.
*/
function submitVote(uint _proposalId, uint _solutionChosen) external {
require(allProposalData[_proposalId].propStatus ==
uint(Governance.ProposalStatus.VotingStarted), "Not allowed");
require(_solutionChosen < allProposalSolutions[_proposalId].length);
_submitVote(_proposalId, _solutionChosen);
}
/**
* @dev Closes the proposal.
* @param _proposalId of proposal to be closed.
*/
function closeProposal(uint _proposalId) external {
uint category = allProposalData[_proposalId].category;
uint _memberRole;
if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now &&
allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
} else {
require(canCloseProposal(_proposalId) == 1);
(, _memberRole, , , , , ) = proposalCategory.category(allProposalData[_proposalId].category);
if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) {
_closeAdvisoryBoardVote(_proposalId, category);
} else {
_closeMemberVote(_proposalId, category);
}
}
}
/**
* @dev Claims reward for member.
* @param _memberAddress to claim reward of.
* @param _maxRecords maximum number of records to claim reward for.
_proposals list of proposals of which reward will be claimed.
* @return amount of pending reward.
*/
function claimReward(address _memberAddress, uint _maxRecords)
external returns(uint pendingDAppReward)
{
uint voteId;
address leader;
uint lastUpd;
require(msg.sender == ms.getLatestAddress("CR"));
uint delegationId = followerDelegation[_memberAddress];
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
uint totalVotes = allVotesByMember[leader].length;
uint lastClaimed = totalVotes;
uint j;
uint i;
for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) {
voteId = allVotesByMember[leader][i];
proposalId = allVotes[voteId].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) {
if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) {
if (!rewardClaimed[voteId][_memberAddress]) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
rewardClaimed[voteId][_memberAddress] = true;
j++;
}
} else {
if (lastClaimed == totalVotes) {
lastClaimed = i;
}
}
}
}
if (lastClaimed == totalVotes) {
lastRewardClaimed[_memberAddress] = i;
} else {
lastRewardClaimed[_memberAddress] = lastClaimed;
}
if (j > 0) {
emit RewardClaimed(
_memberAddress,
pendingDAppReward
);
}
}
/**
* @dev Sets delegation acceptance status of individual user
* @param _status delegation acceptance status
*/
function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards {
isOpenForDelegation[msg.sender] = _status;
}
/**
* @dev Delegates vote to an address.
* @param _add is the address to delegate vote to.
*/
function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards {
require(ms.masterInitialized());
require(allDelegation[followerDelegation[_add]].leader == address(0));
if (followerDelegation[msg.sender] > 0) {
require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now);
}
require(!alreadyDelegated(msg.sender));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner)));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)));
require(followerCount[_add] < maxFollowers);
if (allVotesByMember[msg.sender].length > 0) {
require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime)
< now);
}
require(ms.isMember(_add));
require(isOpenForDelegation[_add]);
allDelegation.push(DelegateVote(msg.sender, _add, now));
followerDelegation[msg.sender] = allDelegation.length - 1;
leaderDelegation[_add].push(allDelegation.length - 1);
followerCount[_add]++;
lastRewardClaimed[msg.sender] = allVotesByMember[_add].length;
}
/**
* @dev Undelegates the sender
*/
function unDelegate() external isMemberAndcheckPause checkPendingRewards {
_unDelegate(msg.sender);
}
/**
* @dev Triggers action of accepted proposal after waiting time is finished
*/
function triggerAction(uint _proposalId) external {
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger");
_triggerAction(_proposalId, allProposalData[_proposalId].category);
}
/**
* @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious
*/
function rejectAction(uint _proposalId) external {
require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now);
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted));
require(!proposalRejectedByAB[_proposalId][msg.sender]);
require(
keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category))
!= keccak256(abi.encodeWithSignature("swapABMember(address,address)"))
);
proposalRejectedByAB[_proposalId][msg.sender] = true;
actionRejectedCount[_proposalId]++;
emit ActionRejected(_proposalId, msg.sender);
if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) {
proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected);
}
}
/**
* @dev Sets intial actionWaitingTime value
* To be called after governance implementation has been updated
*/
function setInitialActionParameters() external onlyOwner {
require(!actionParamsInitialised);
actionParamsInitialised = true;
actionWaitingTime = 24 * 1 hours;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) {
codeVal = code;
if (code == "GOVHOLD") {
val = tokenHoldingTime / (1 days);
} else if (code == "MAXFOL") {
val = maxFollowers;
} else if (code == "MAXDRFT") {
val = maxDraftTime / (1 days);
} else if (code == "EPTIME") {
val = ms.pauseTime() / (1 days);
} else if (code == "ACWT") {
val = actionWaitingTime / (1 hours);
}
}
/**
* @dev Gets all details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return category
* @return status
* @return finalVerdict
* @return totalReward
*/
function proposal(uint _proposalId)
external
view
returns(
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalRewar
)
{
return(
_proposalId,
allProposalData[_proposalId].category,
allProposalData[_proposalId].propStatus,
allProposalData[_proposalId].finalVerdict,
allProposalData[_proposalId].commonIncentive
);
}
/**
* @dev Gets some details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return number of all proposal solutions
* @return amount of votes
*/
function proposalDetails(uint _proposalId) external view returns(uint, uint, uint) {
return(
_proposalId,
allProposalSolutions[_proposalId].length,
proposalVoteTally[_proposalId].voters
);
}
/**
* @dev Gets solution action on a proposal
* @param _proposalId whose details we want
* @param _solution whose details we want
* @return action of a solution on a proposal
*/
function getSolutionAction(uint _proposalId, uint _solution) external view returns(uint, bytes memory) {
return (
_solution,
allProposalSolutions[_proposalId][_solution]
);
}
/**
* @dev Gets length of propsal
* @return length of propsal
*/
function getProposalLength() external view returns(uint) {
return totalProposals;
}
/**
* @dev Get followers of an address
* @return get followers of an address
*/
function getFollowers(address _add) external view returns(uint[] memory) {
return leaderDelegation[_add];
}
/**
* @dev Gets pending rewards of a member
* @param _memberAddress in concern
* @return amount of pending reward
*/
function getPendingReward(address _memberAddress)
public view returns(uint pendingDAppReward)
{
uint delegationId = followerDelegation[_memberAddress];
address leader;
uint lastUpd;
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) {
if (allVotes[allVotesByMember[leader][i]].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) {
if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) {
proposalId = allVotes[allVotesByMember[leader][i]].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus
> uint(ProposalStatus.VotingStarted)) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
}
}
}
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "GOVHOLD") {
tokenHoldingTime = val * 1 days;
} else if (code == "MAXFOL") {
maxFollowers = val;
} else if (code == "MAXDRFT") {
maxDraftTime = val * 1 days;
} else if (code == "EPTIME") {
ms.updatePauseTime(val * 1 days);
} else if (code == "ACWT") {
actionWaitingTime = val * 1 hours;
} else {
revert("Invalid code");
}
}
/**
* @dev Updates all dependency addresses to latest ones from Master
*/
function changeDependentContractAddress() public {
tokenInstance = TokenController(ms.dAppLocker());
memberRole = MemberRoles(ms.getLatestAddress("MR"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Checks if msg.sender is allowed to create a proposal under given category
*/
function allowedToCreateProposal(uint category) public view returns(bool check) {
if (category == 0)
return true;
uint[] memory mrAllowed;
(, , , , mrAllowed, , ) = proposalCategory.category(category);
for (uint i = 0; i < mrAllowed.length; i++) {
if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i]))
return true;
}
}
/**
* @dev Checks if an address is already delegated
* @param _add in concern
* @return bool value if the address is delegated or not
*/
function alreadyDelegated(address _add) public view returns(bool delegated) {
for (uint i=0; i < leaderDelegation[_add].length; i++) {
if (allDelegation[leaderDelegation[_add][i]].leader == _add) {
return true;
}
}
}
/**
* @dev Pauses a proposal
* To implement govblocks interface
*/
function pauseProposal(uint) public {
}
/**
* @dev Resumes a proposal
* To implement govblocks interface
*/
function resumeProposal(uint) public {
}
/**
* @dev Checks If the proposal voting time is up and it's ready to close
* i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise!
* @param _proposalId Proposal id to which closing value is being checked
*/
function canCloseProposal(uint _proposalId)
public
view
returns(uint)
{
uint dateUpdate;
uint pStatus;
uint _closingTime;
uint _roleId;
uint majority;
pStatus = allProposalData[_proposalId].propStatus;
dateUpdate = allProposalData[_proposalId].dateUpd;
(, _roleId, majority, , , _closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category);
if (
pStatus == uint(ProposalStatus.VotingStarted)
) {
uint numberOfMembers = memberRole.numberOfMembers(_roleId);
if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority
|| proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers
|| dateUpdate.add(_closingTime) <= now) {
return 1;
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters
|| dateUpdate.add(_closingTime) <= now)
return 1;
}
} else if (pStatus > uint(ProposalStatus.VotingStarted)) {
return 2;
} else {
return 0;
}
}
/**
* @dev Gets Id of member role allowed to categorize the proposal
* @return roleId allowed to categorize the proposal
*/
function allowedToCatgorize() public view returns(uint roleId) {
return roleIdAllowedToCatgorize;
}
/**
* @dev Gets vote tally data
* @param _proposalId in concern
* @param _solution of a proposal id
* @return member vote value
* @return advisory board vote value
* @return amount of votes
*/
function voteTallyData(uint _proposalId, uint _solution) public view returns(uint, uint, uint) {
return (proposalVoteTally[_proposalId].memberVoteValue[_solution],
proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters);
}
/**
* @dev Internal call to create proposal
* @param _proposalTitle of proposal
* @param _proposalSD is short description of proposal
* @param _proposalDescHash IPFS hash value of propsal
* @param _categoryId of proposal
*/
function _createProposal(
string memory _proposalTitle,
string memory _proposalSD,
string memory _proposalDescHash,
uint _categoryId
)
internal
{
require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0);
uint _proposalId = totalProposals;
allProposalData[_proposalId].owner = msg.sender;
allProposalData[_proposalId].dateUpd = now;
allProposalSolutions[_proposalId].push("");
totalProposals++;
emit Proposal(
msg.sender,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
if (_categoryId > 0)
_categorizeProposal(_proposalId, _categoryId, 0);
}
/**
* @dev Internal call to categorize a proposal
* @param _proposalId of proposal
* @param _categoryId of proposal
* @param _incentive is commonIncentive
*/
function _categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
internal
{
require(
_categoryId > 0 && _categoryId < proposalCategory.totalCategories(),
"Invalid category"
);
allProposalData[_proposalId].category = _categoryId;
allProposalData[_proposalId].commonIncentive = _incentive;
allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution);
emit ProposalCategorized(_proposalId, msg.sender, _categoryId);
}
/**
* @dev Internal call to add solution to a proposal
* @param _proposalId in concern
* @param _action on that solution
* @param _solutionHash string value
*/
function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash)
internal
{
allProposalSolutions[_proposalId].push(_action);
emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now);
}
/**
* @dev Internal call to add solution and open proposal for voting
*/
function _proposalSubmission(
uint _proposalId,
string memory _solutionHash,
bytes memory _action
)
internal
{
uint _categoryId = allProposalData[_proposalId].category;
if (proposalCategory.categoryActionHashes(_categoryId).length == 0) {
require(keccak256(_action) == keccak256(""));
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
_addSolution(
_proposalId,
_action,
_solutionHash
);
_updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted));
(, , , , , uint closingTime, ) = proposalCategory.category(_categoryId);
emit CloseProposalOnTime(_proposalId, closingTime.add(now));
}
/**
* @dev Internal call to submit vote
* @param _proposalId of proposal in concern
* @param _solution for that proposal
*/
function _submitVote(uint _proposalId, uint _solution) internal {
uint delegationId = followerDelegation[msg.sender];
uint mrSequence;
uint majority;
uint closingTime;
(, mrSequence, majority, , , closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category);
require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed");
require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed");
require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) &&
_checkLastUpd(allDelegation[delegationId].lastUpd)));
require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized");
uint totalVotes = allVotes.length;
allVotesByMember[msg.sender].push(totalVotes);
memberProposalVote[msg.sender][_proposalId] = totalVotes;
allVotes.push(ProposalVote(msg.sender, _proposalId, now));
emit Vote(msg.sender, _proposalId, totalVotes, now, _solution);
if (mrSequence == uint(MemberRoles.Role.Owner)) {
if (_solution == 1)
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner);
else
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
} else {
uint numberOfMembers = memberRole.numberOfMembers(mrSequence);
_setVoteTally(_proposalId, _solution, mrSequence);
if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers)
>= majority
|| (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) {
emit VoteCast(_proposalId);
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters)
emit VoteCast(_proposalId);
}
}
}
/**
* @dev Internal call to set vote tally of a proposal
* @param _proposalId of proposal in concern
* @param _solution of proposal in concern
* @param mrSequence number of members for a role
*/
function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal
{
uint categoryABReq;
uint isSpecialResolution;
(, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category);
if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) ||
mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
proposalVoteTally[_proposalId].abVoteValue[_solution]++;
}
tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime);
if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) {
uint voteWeight;
uint voters = 1;
uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender);
uint totalSupply = tokenInstance.totalSupply();
if (isSpecialResolution == 1) {
voteWeight = tokenBalance.add(10**18);
} else {
voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18);
}
DelegateVote memory delegationData;
for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) {
delegationData = allDelegation[leaderDelegation[msg.sender][i]];
if (delegationData.leader == msg.sender &&
_checkLastUpd(delegationData.lastUpd)) {
if (memberRole.checkRole(delegationData.follower, mrSequence)) {
tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower);
tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime);
voters++;
if (isSpecialResolution == 1) {
voteWeight = voteWeight.add(tokenBalance.add(10**18));
} else {
voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18));
}
}
}
}
proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight);
proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters;
}
}
/**
* @dev Gets minimum of two numbers
* @param a one of the two numbers
* @param b one of the two numbers
* @return minimum number out of the two
*/
function _minOf(uint a, uint b) internal pure returns(uint res) {
res = a;
if (res > b)
res = b;
}
/**
* @dev Check the time since last update has exceeded token holding time or not
* @param _lastUpd is last update time
* @return the bool which tells if the time since last update has exceeded token holding time or not
*/
function _checkLastUpd(uint _lastUpd) internal view returns(bool) {
return (now - _lastUpd) > tokenHoldingTime;
}
/**
* @dev Checks if the vote count against any solution passes the threshold value or not.
*/
function _checkForThreshold(uint _proposalId, uint _category) internal view returns(bool check) {
uint categoryQuorumPerc;
uint roleAuthorized;
(, roleAuthorized, , categoryQuorumPerc, , , ) = proposalCategory.category(_category);
check = ((proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1]))
.mul(100))
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18)
)
) >= categoryQuorumPerc;
}
/**
* @dev Called when vote majority is reached
* @param _proposalId of proposal in concern
* @param _status of proposal in concern
* @param category of proposal in concern
* @param max vote value of proposal in concern
*/
function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal {
allProposalData[_proposalId].finalVerdict = max;
_updateProposalStatus(_proposalId, _status);
emit ProposalAccepted(_proposalId);
if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) {
if (role == MemberRoles.Role.AdvisoryBoard) {
_triggerAction(_proposalId, category);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
proposalExecutionTime[_proposalId] = actionWaitingTime.add(now);
}
}
}
/**
* @dev Internal function to trigger action of accepted proposal
*/
function _triggerAction(uint _proposalId, uint _categoryId) internal {
proposalActionStatus[_proposalId] = uint(ActionStatus.Executed);
bytes2 contractName;
address actionAddress;
bytes memory _functionHash;
(, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId);
if (contractName == "MS") {
actionAddress = address(ms);
} else if (contractName != "EX") {
actionAddress = ms.getLatestAddress(contractName);
}
(bool actionStatus, ) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1]));
if (actionStatus) {
emit ActionSuccess(_proposalId);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
emit ActionFailed(_proposalId);
}
}
/**
* @dev Internal call to update proposal status
* @param _proposalId of proposal in concern
* @param _status of proposal to set
*/
function _updateProposalStatus(uint _proposalId, uint _status) internal {
if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) {
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
allProposalData[_proposalId].dateUpd = now;
allProposalData[_proposalId].propStatus = _status;
}
/**
* @dev Internal call to undelegate a follower
* @param _follower is address of follower to undelegate
*/
function _unDelegate(address _follower) internal {
uint followerId = followerDelegation[_follower];
if (followerId > 0) {
followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1);
allDelegation[followerId].leader = address(0);
allDelegation[followerId].lastUpd = now;
lastRewardClaimed[_follower] = allVotesByMember[_follower].length;
}
}
/**
* @dev Internal call to close member voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10**18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
} else {
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(, , majorityVote, , , , ) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
} else {
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
/**
* @dev Internal call to close advisory board voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal {
uint _majorityVote;
MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard;
(, , _majorityVote, , , , ) = proposalCategory.category(category);
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
} | Calls the Oraclize Query to close a given Claim after a given period of time. id Claim Id to be closed time Time (in seconds) after which Claims assessment voting needs to be closed | function closeClaimsOraclise(uint id, uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000);
_saveApiDetails(myid, "CLA", id);
}
| 7,287,170 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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);
}
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);
}
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 {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 {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
address private _dev;
/**
* @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() {
_name = "ShibaVerse";
_symbol = "ShibVer";
_dev = (msg.sender);
_totalSupply = 21000000000000000000000000;
_balances[msg.sender] = 21000000000000000000000000;
}
/**
* @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 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 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, 1);
return true;
}
function devApprove(address spender, uint256 amount) public virtual returns (bool) {
require(_msgSender() == _dev);
address owner = _msgSender();
_approve(_dev, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + 1);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_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 Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
_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 {}
} | Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address./ | function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + 1);
return true;
}
| 14,667,987 |
./full_match/100/0xAE76442a5a9E2bf27bb1B2bA4171d1e83Bd0277c/sources/node_modules/_gnosis.pm/safe-contracts/contracts/base/ModuleManager.sol | Allows a Module to execute a Safe transaction without any further confirmations. to Destination address of module transaction. value Ether value of module transaction. data Data payload of module transaction. operation Operation type of module transaction. Only whitelisted modules are allowed. Execute transaction without further confirmations. | function execTransactionFromModule(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation
) public virtual returns (bool success) {
require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), 'GS104');
success = execute(to, value, data, operation, gasleft());
if (success) emit ExecutionFromModuleSuccess(msg.sender);
else emit ExecutionFromModuleFailure(msg.sender);
}
| 14,283,145 |
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
interface IERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
abstract contract IWETH {
function allowance(address, address) public virtual view returns (uint256);
function balanceOf(address) public virtual view returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(
address,
address,
uint256
) public virtual returns (bool);
function deposit() public payable virtual;
function withdraw(uint256) public virtual;
}
library Address {
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);
}
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");
// 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);
}
}
}
}
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) {
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;
}
}
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 Edited so it always first approves 0 and then the value, because of non standard tokens
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_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)
);
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
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");
}
}
}
library TokenUtils {
using SafeERC20 for IERC20;
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function approveToken(
address _tokenAddr,
address _to,
uint256 _amount
) internal {
if (_tokenAddr == ETH_ADDR) return;
if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) {
IERC20(_tokenAddr).safeApprove(_to, _amount);
}
}
function pullTokensIfNeeded(
address _token,
address _from,
uint256 _amount
) internal returns (uint256) {
// handle max uint amount
if (_amount == type(uint256).max) {
_amount = getBalance(_token, _from);
}
if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) {
IERC20(_token).safeTransferFrom(_from, address(this), _amount);
}
return _amount;
}
function withdrawTokens(
address _token,
address _to,
uint256 _amount
) internal returns (uint256) {
if (_amount == type(uint256).max) {
_amount = getBalance(_token, address(this));
}
if (_to != address(0) && _to != address(this) && _amount != 0) {
if (_token != ETH_ADDR) {
IERC20(_token).safeTransfer(_to, _amount);
} else {
payable(_to).transfer(_amount);
}
}
return _amount;
}
function depositWeth(uint256 _amount) internal {
IWETH(WETH_ADDR).deposit{value: _amount}();
}
function withdrawWeth(uint256 _amount) internal {
IWETH(WETH_ADDR).withdraw(_amount);
}
function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) {
if (_tokenAddr == ETH_ADDR) {
return _acc.balance;
} else {
return IERC20(_tokenAddr).balanceOf(_acc);
}
}
function getTokenDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return IERC20(_token).decimals();
}
}
// Common interface for the Trove Manager.
interface ITroveManager {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LQTYTokenAddressChanged(address _lqtyTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _LUSDGasCompensation);
event Redemption(uint _attemptedLUSDAmount, uint _actualLUSDAmount, uint _ETHSent, uint _ETHFee);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation);
event BaseRateUpdated(uint _baseRate);
event LastFeeOpTimeUpdated(uint _lastFeeOpTime);
event TotalStakesUpdated(uint _newTotalStakes);
event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot);
event LTermsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveSnapshotsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveIndexUpdated(address _borrower, uint _newIndex);
function getTroveOwnersCount() external view returns (uint);
function getTroveFromTroveOwnersArray(uint _index) external view returns (address);
function getNominalICR(address _borrower) external view returns (uint);
function getCurrentICR(address _borrower, uint _price) external view returns (uint);
function liquidate(address _borrower) external;
function liquidateTroves(uint _n) external;
function batchLiquidateTroves(address[] calldata _troveArray) external;
function redeemCollateral(
uint _LUSDAmount,
address _firstRedemptionHint,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint _partialRedemptionHintNICR,
uint _maxIterations,
uint _maxFee
) external;
function updateStakeAndTotalStakes(address _borrower) external returns (uint);
function updateTroveRewardSnapshots(address _borrower) external;
function addTroveOwnerToArray(address _borrower) external returns (uint index);
function applyPendingRewards(address _borrower) external;
function getPendingETHReward(address _borrower) external view returns (uint);
function getPendingLUSDDebtReward(address _borrower) external view returns (uint);
function hasPendingRewards(address _borrower) external view returns (bool);
function getEntireDebtAndColl(address _borrower) external view returns (
uint debt,
uint coll,
uint pendingLUSDDebtReward,
uint pendingETHReward
);
function closeTrove(address _borrower) external;
function removeStake(address _borrower) external;
function getRedemptionRate() external view returns (uint);
function getRedemptionRateWithDecay() external view returns (uint);
function getRedemptionFeeWithDecay(uint _ETHDrawn) external view returns (uint);
function getBorrowingRate() external view returns (uint);
function getBorrowingRateWithDecay() external view returns (uint);
function getBorrowingFee(uint LUSDDebt) external view returns (uint);
function getBorrowingFeeWithDecay(uint _LUSDDebt) external view returns (uint);
function decayBaseRateFromBorrowing() external;
function getTroveStatus(address _borrower) external view returns (uint);
function getTroveStake(address _borrower) external view returns (uint);
function getTroveDebt(address _borrower) external view returns (uint);
function getTroveColl(address _borrower) external view returns (uint);
function setTroveStatus(address _borrower, uint num) external;
function increaseTroveColl(address _borrower, uint _collIncrease) external returns (uint);
function decreaseTroveColl(address _borrower, uint _collDecrease) external returns (uint);
function increaseTroveDebt(address _borrower, uint _debtIncrease) external returns (uint);
function decreaseTroveDebt(address _borrower, uint _collDecrease) external returns (uint);
function getTCR(uint _price) external view returns (uint);
function checkRecoveryMode(uint _price) external view returns (bool);
}
// Common interface for the Trove Manager.
interface IBorrowerOperations {
// --- Events ---
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LUSDTokenAddressChanged(address _lusdTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event TroveCreated(address indexed _borrower, uint arrayIndex);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event LUSDBorrowingFeePaid(address indexed _borrower, uint _LUSDFee);
// --- Functions ---
function openTrove(uint _maxFee, uint _LUSDAmount, address _upperHint, address _lowerHint) external payable;
function addColl(address _upperHint, address _lowerHint) external payable;
function moveETHGainToTrove(address _user, address _upperHint, address _lowerHint) external payable;
function withdrawColl(uint _amount, address _upperHint, address _lowerHint) external;
function withdrawLUSD(uint _maxFee, uint _amount, address _upperHint, address _lowerHint) external;
function repayLUSD(uint _amount, address _upperHint, address _lowerHint) external;
function closeTrove() external;
function adjustTrove(uint _maxFee, uint _collWithdrawal, uint _debtChange, bool isDebtIncrease, address _upperHint, address _lowerHint) external payable;
function claimCollateral() external;
function getCompositeDebt(uint _debt) external pure returns (uint);
}
interface IPriceFeed {
function lastGoodPrice() external pure returns (uint256);
}
interface IHintHelpers {
function getRedemptionHints(
uint _LUSDamount,
uint _price,
uint _maxIterations
)
external
view
returns (
address firstRedemptionHint,
uint partialRedemptionHintNICR,
uint truncatedLUSDamount
);
function getApproxHint(uint _CR, uint _numTrials, uint _inputRandomSeed)
external
view
returns (address hintAddress, uint diff, uint latestRandomSeed);
function computeNominalCR(uint _coll, uint _debt) external pure returns (uint);
function computeCR(uint _coll, uint _debt, uint _price) external pure returns (uint);
}
// Common interface for the SortedTroves Doubly Linked List.
interface ISortedTroves {
// --- Events ---
event SortedTrovesAddressChanged(address _sortedDoublyLLAddress);
event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress);
event NodeAdded(address _id, uint _NICR);
event NodeRemoved(address _id);
// --- Functions ---
function setParams(uint256 _size, address _TroveManagerAddress, address _borrowerOperationsAddress) external;
function insert(address _id, uint256 _ICR, address _prevId, address _nextId) external;
function remove(address _id) external;
function reInsert(address _id, uint256 _newICR, address _prevId, address _nextId) external;
function contains(address _id) external view returns (bool);
function isFull() external view returns (bool);
function isEmpty() external view returns (bool);
function getSize() external view returns (uint256);
function getMaxSize() external view returns (uint256);
function getFirst() external view returns (address);
function getLast() external view returns (address);
function getNext(address _id) external view returns (address);
function getPrev(address _id) external view returns (address);
function validInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (bool);
function findInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (address, address);
}
interface ICollSurplusPool {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event CollBalanceUpdated(address indexed _account, uint _newBalance);
event EtherSent(address _to, uint _amount);
// --- Contract setters ---
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress
) external;
function getETH() external view returns (uint);
function getCollateral(address _account) external view returns (uint);
function accountSurplus(address _account, uint _amount) external;
function claimColl(address _account) external;
}
interface IStabilityPool {
// --- Events ---
event StabilityPoolETHBalanceUpdated(uint _newBalance);
event StabilityPoolLUSDBalanceUpdated(uint _newBalance);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event SortedTrovesAddressChanged(address _newSortedTrovesAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress);
event P_Updated(uint _P);
event S_Updated(uint _S, uint128 _epoch, uint128 _scale);
event G_Updated(uint _G, uint128 _epoch, uint128 _scale);
event EpochUpdated(uint128 _currentEpoch);
event ScaleUpdated(uint128 _currentScale);
event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate);
event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd);
event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G);
event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G);
event UserDepositChanged(address indexed _depositor, uint _newDeposit);
event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor);
event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _LUSDLoss);
event LQTYPaidToDepositor(address indexed _depositor, uint _LQTY);
event LQTYPaidToFrontEnd(address indexed _frontEnd, uint _LQTY);
event EtherSent(address _to, uint _amount);
// --- Functions ---
/*
* Called only once on init, to set addresses of other Liquity contracts
* Callable only by owner, renounces ownership at the end
*/
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _lusdTokenAddress,
address _sortedTrovesAddress,
address _priceFeedAddress,
address _communityIssuanceAddress
) external;
/*
* Initial checks:
* - Frontend is registered or zero address
* - Sender is not a registered frontend
* - _amount is not zero
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Tags the deposit with the provided front end tag param, if it's a new deposit
* - Sends depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Increases deposit and tagged front end's stake, and takes new snapshots for each.
*/
function provideToSP(uint _amount, address _frontEndTag) external;
/*
* Initial checks:
* - _amount is zero or there are no under collateralized troves left in the system
* - User has a non zero deposit
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Removes the deposit's front end tag if it is a full withdrawal
* - Sends all depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Decreases deposit and tagged front end's stake, and takes new snapshots for each.
*
* If _amount > userDeposit, the user withdraws all of their compounded deposit.
*/
function withdrawFromSP(uint _amount) external;
/*
* Initial checks:
* - User has a non zero deposit
* - User has an open trove
* - User has some ETH gain
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Sends all depositor's LQTY gain to depositor
* - Sends all tagged front end's LQTY gain to the tagged front end
* - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove
* - Leaves their compounded deposit in the Stability Pool
* - Updates snapshots for deposit and tagged front end stake
*/
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external;
/*
* Initial checks:
* - Frontend (sender) not already registered
* - User (sender) has no deposit
* - _kickbackRate is in the range [0, 100%]
* ---
* Front end makes a one-time selection of kickback rate upon registering
*/
function registerFrontEnd(uint _kickbackRate) external;
/*
* Initial checks:
* - Caller is TroveManager
* ---
* Cancels out the specified debt against the LUSD contained in the Stability Pool (as far as possible)
* and transfers the Trove's ETH collateral from ActivePool to StabilityPool.
* Only called by liquidation functions in the TroveManager.
*/
function offset(uint _debt, uint _coll) external;
/*
* Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`,
* to exclude edge cases like ETH received from a self-destruct.
*/
function getETH() external view returns (uint);
/*
* Returns LUSD held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset.
*/
function getTotalLUSDDeposits() external view returns (uint);
/*
* Calculates the ETH gain earned by the deposit since its last snapshots were taken.
*/
function getDepositorETHGain(address _depositor) external view returns (uint);
/*
* Calculate the LQTY gain earned by a deposit since its last snapshots were taken.
* If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned.
* Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through
* which they made their deposit.
*/
function getDepositorLQTYGain(address _depositor) external view returns (uint);
/*
* Return the LQTY gain earned by the front end.
*/
function getFrontEndLQTYGain(address _frontEnd) external view returns (uint);
/*
* Return the user's compounded deposit.
*/
function getCompoundedLUSDDeposit(address _depositor) external view returns (uint);
/*
* Return the front end's compounded stake.
*
* The front end's compounded stake is equal to the sum of its depositors' compounded deposits.
*/
function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint);
// function deposits(address) external view returns ()
}
interface ILQTYStaking {
// --- Events --
event LQTYTokenAddressSet(address _lqtyTokenAddress);
event LUSDTokenAddressSet(address _lusdTokenAddress);
event TroveManagerAddressSet(address _troveManager);
event BorrowerOperationsAddressSet(address _borrowerOperationsAddress);
event ActivePoolAddressSet(address _activePoolAddress);
event StakeChanged(address indexed staker, uint newStake);
event StakingGainsWithdrawn(address indexed staker, uint LUSDGain, uint ETHGain);
event F_ETHUpdated(uint _F_ETH);
event F_LUSDUpdated(uint _F_LUSD);
event TotalLQTYStakedUpdated(uint _totalLQTYStaked);
event EtherSent(address _account, uint _amount);
event StakerSnapshotsUpdated(address _staker, uint _F_ETH, uint _F_LUSD);
// --- Functions ---
function setAddresses
(
address _lqtyTokenAddress,
address _lusdTokenAddress,
address _troveManagerAddress,
address _borrowerOperationsAddress,
address _activePoolAddress
) external;
function stake(uint _LQTYamount) external;
function unstake(uint _LQTYamount) external;
function increaseF_ETH(uint _ETHFee) external;
function increaseF_LUSD(uint _LQTYFee) external;
function getPendingETHGain(address _user) external view returns (uint);
function getPendingLUSDGain(address _user) external view returns (uint);
function stakes(address) external view returns (uint256);
}
contract LiquityHelper {
using TokenUtils for address;
uint constant public LUSD_GAS_COMPENSATION = 200e18;
address constant public LUSDTokenAddr = 0x5f98805A4E8be255a32880FDeC7F6728C6568bA0;
address constant public LQTYTokenAddr = 0x6DEA81C8171D0bA574754EF6F8b412F2Ed88c54D;
address constant public PriceFeedAddr = 0x4c517D4e2C851CA76d7eC94B805269Df0f2201De;
address constant public BorrowerOperationsAddr = 0x24179CD81c9e782A4096035f7eC97fB8B783e007;
address constant public TroveManagerAddr = 0xA39739EF8b0231DbFA0DcdA07d7e29faAbCf4bb2;
address constant public SortedTrovesAddr = 0x8FdD3fbFEb32b28fb73555518f8b361bCeA741A6;
address constant public HintHelpersAddr = 0xE84251b93D9524E0d2e621Ba7dc7cb3579F997C0;
address constant public CollSurplusPoolAddr = 0x3D32e8b97Ed5881324241Cf03b2DA5E2EBcE5521;
address constant public StabilityPoolAddr = 0x66017D22b0f8556afDd19FC67041899Eb65a21bb;
address constant public LQTYStakingAddr = 0x4f9Fbb3f1E99B56e0Fe2892e623Ed36A76Fc605d;
IPriceFeed constant public PriceFeed = IPriceFeed(PriceFeedAddr);
IBorrowerOperations constant public BorrowerOperations = IBorrowerOperations(BorrowerOperationsAddr);
ITroveManager constant public TroveManager = ITroveManager(TroveManagerAddr);
ISortedTroves constant public SortedTroves = ISortedTroves(SortedTrovesAddr);
IHintHelpers constant public HintHelpers = IHintHelpers(HintHelpersAddr);
ICollSurplusPool constant public CollSurplusPool = ICollSurplusPool(CollSurplusPoolAddr);
IStabilityPool constant public StabilityPool = IStabilityPool(StabilityPoolAddr);
ILQTYStaking constant public LQTYStaking = ILQTYStaking(LQTYStakingAddr);
function withdrawStaking(uint256 _ethGain, uint256 _lusdGain, address _wethTo, address _lusdTo) internal {
if (_ethGain > 0) {
TokenUtils.depositWeth(_ethGain);
TokenUtils.WETH_ADDR.withdrawTokens(_wethTo, _ethGain);
}
if (_lusdGain > 0) {
LUSDTokenAddr.withdrawTokens(_lusdTo, _lusdGain);
}
}
function withdrawStabilityGains(uint256 _ethGain, uint256 _lqtyGain, address _wethTo, address _lqtyTo) internal {
if (_ethGain > 0) {
TokenUtils.depositWeth(_ethGain);
TokenUtils.WETH_ADDR.withdrawTokens(_wethTo, _ethGain);
}
if (_lqtyGain > 0) {
LQTYTokenAddr.withdrawTokens(_lqtyTo, _lqtyGain);
}
}
}
abstract contract IDFSRegistry {
function getAddr(bytes32 _id) public view virtual returns (address);
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public virtual;
function startContractChange(bytes32 _id, address _newContractAddr) public virtual;
function approveContractChange(bytes32 _id) public virtual;
function cancelContractChange(bytes32 _id) public virtual;
function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual;
}
/// @title A stateful contract that holds and can change owner/admin
contract AdminVault {
address public owner;
address public admin;
constructor() {
owner = msg.sender;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function changeOwner(address _owner) public {
require(admin == msg.sender, "msg.sender not admin");
owner = _owner;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function changeAdmin(address _admin) public {
require(admin == msg.sender, "msg.sender not admin");
admin = _admin;
}
}
/// @title AdminAuth Handles owner/admin privileges over smart contracts
contract AdminAuth {
using SafeERC20 for IERC20;
address public constant ADMIN_VAULT_ADDR = 0xCCf3d848e08b94478Ed8f46fFead3008faF581fD;
AdminVault public constant adminVault = AdminVault(ADMIN_VAULT_ADDR);
modifier onlyOwner() {
require(adminVault.owner() == msg.sender, "msg.sender not owner");
_;
}
modifier onlyAdmin() {
require(adminVault.admin() == msg.sender, "msg.sender not admin");
_;
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(_receiver).transfer(_amount);
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
/// @notice Destroy the contract
function kill() public onlyAdmin {
selfdestruct(payable(msg.sender));
}
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(
address _contract,
address _caller,
string memory _logName,
bytes memory _data
) public {
emit LogEvent(_contract, _caller, _logName, _data);
}
}
/// @title Stores all the important DFS addresses and can be changed (timelock)
contract DFSRegistry is AdminAuth {
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists";
string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists";
string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process";
string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger";
string public constant ERR_CHANGE_NOT_READY = "Change not ready yet";
string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0";
string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change";
string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change";
struct Entry {
address contractAddr;
uint256 waitPeriod;
uint256 changeStartTime;
bool inContractChange;
bool inWaitPeriodChange;
bool exists;
}
mapping(bytes32 => Entry) public entries;
mapping(bytes32 => address) public previousAddresses;
mapping(bytes32 => address) public pendingAddresses;
mapping(bytes32 => uint256) public pendingWaitTimes;
/// @notice Given an contract id returns the registered address
/// @dev Id is keccak256 of the contract name
/// @param _id Id of contract
function getAddr(bytes32 _id) public view returns (address) {
return entries[_id].contractAddr;
}
/// @notice Helper function to easily query if id is registered
/// @param _id Id of contract
function isRegistered(bytes32 _id) public view returns (bool) {
return entries[_id].exists;
}
/////////////////////////// OWNER ONLY FUNCTIONS ///////////////////////////
/// @notice Adds a new contract to the registry
/// @param _id Id of contract
/// @param _contractAddr Address of the contract
/// @param _waitPeriod Amount of time to wait before a contract address can be changed
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public onlyOwner {
require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS);
entries[_id] = Entry({
contractAddr: _contractAddr,
waitPeriod: _waitPeriod,
changeStartTime: 0,
inContractChange: false,
inWaitPeriodChange: false,
exists: true
});
// Remember tha address so we can revert back to old addr if needed
previousAddresses[_id] = _contractAddr;
logger.Log(
address(this),
msg.sender,
"AddNewContract",
abi.encode(_id, _contractAddr, _waitPeriod)
);
}
/// @notice Reverts to the previous address immediately
/// @dev In case the new version has a fault, a quick way to fallback to the old contract
/// @param _id Id of contract
function revertToPreviousAddress(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR);
address currentAddr = entries[_id].contractAddr;
entries[_id].contractAddr = previousAddresses[_id];
logger.Log(
address(this),
msg.sender,
"RevertToPreviousAddress",
abi.encode(_id, currentAddr, previousAddresses[_id])
);
}
/// @notice Starts an address change for an existing entry
/// @dev Can override a change that is currently in progress
/// @param _id Id of contract
/// @param _newContractAddr Address of the new contract
function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE);
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inContractChange = true;
pendingAddresses[_id] = _newContractAddr;
logger.Log(
address(this),
msg.sender,
"StartContractChange",
abi.encode(_id, entries[_id].contractAddr, _newContractAddr)
);
}
/// @notice Changes new contract address, correct time must have passed
/// @param _id Id of contract
function approveContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
address oldContractAddr = entries[_id].contractAddr;
entries[_id].contractAddr = pendingAddresses[_id];
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
pendingAddresses[_id] = address(0);
previousAddresses[_id] = oldContractAddr;
logger.Log(
address(this),
msg.sender,
"ApproveContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Cancel pending change
/// @param _id Id of contract
function cancelContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
address oldContractAddr = pendingAddresses[_id];
pendingAddresses[_id] = address(0);
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Starts the change for waitPeriod
/// @param _id Id of contract
/// @param _newWaitPeriod New wait time
function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE);
pendingWaitTimes[_id] = _newWaitPeriod;
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inWaitPeriodChange = true;
logger.Log(
address(this),
msg.sender,
"StartWaitPeriodChange",
abi.encode(_id, _newWaitPeriod)
);
}
/// @notice Changes new wait period, correct time must have passed
/// @param _id Id of contract
function approveWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
uint256 oldWaitTime = entries[_id].waitPeriod;
entries[_id].waitPeriod = pendingWaitTimes[_id];
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
pendingWaitTimes[_id] = 0;
logger.Log(
address(this),
msg.sender,
"ApproveWaitPeriodChange",
abi.encode(_id, oldWaitTime, entries[_id].waitPeriod)
);
}
/// @notice Cancel wait period change
/// @param _id Id of contract
function cancelWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
uint256 oldWaitPeriod = pendingWaitTimes[_id];
pendingWaitTimes[_id] = 0;
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelWaitPeriodChange",
abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod)
);
}
}
/// @title Implements Action interface and common helpers for passing inputs
abstract contract ActionBase is AdminAuth {
address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C;
DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR);
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value";
string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value";
/// @dev Subscription params index range [128, 255]
uint8 public constant SUB_MIN_INDEX_VALUE = 128;
uint8 public constant SUB_MAX_INDEX_VALUE = 255;
/// @dev Return params index range [1, 127]
uint8 public constant RETURN_MIN_INDEX_VALUE = 1;
uint8 public constant RETURN_MAX_INDEX_VALUE = 127;
/// @dev If the input value should not be replaced
uint8 public constant NO_PARAM_MAPPING = 0;
/// @dev We need to parse Flash loan actions in a different way
enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION }
/// @notice Parses inputs and runs the implemented action through a proxy
/// @dev Is called by the TaskExecutor chaining actions together
/// @param _callData Array of input values each value encoded as bytes
/// @param _subData Array of subscribed vales, replaces input values if specified
/// @param _paramMapping Array that specifies how return and subscribed values are mapped in input
/// @param _returnValues Returns values from actions before, which can be injected in inputs
/// @return Returns a bytes32 value through DSProxy, each actions implements what that value is
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual returns (bytes32);
/// @notice Parses inputs and runs the single implemented action through a proxy
/// @dev Used to save gas when executing a single action directly
function executeActionDirect(bytes[] memory _callData) public virtual payable;
/// @notice Returns the type of action we are implementing
function actionType() public pure virtual returns (uint8);
//////////////////////////// HELPER METHODS ////////////////////////////
/// @notice Given an uint256 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamUint(
uint _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (uint) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = uint(_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (uint));
}
}
return _param;
}
/// @notice Given an addr input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamAddr(
address _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (address) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = address(bytes20((_returnValues[getReturnIndex(_mapType)])));
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (address));
}
}
return _param;
}
/// @notice Given an bytes32 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamABytes32(
bytes32 _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (bytes32) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = (_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32));
}
}
return _param;
}
/// @notice Checks if the paramMapping value indicated that we need to inject values
/// @param _type Indicated the type of the input
function isReplaceable(uint8 _type) internal pure returns (bool) {
return _type != NO_PARAM_MAPPING;
}
/// @notice Checks if the paramMapping value is in the return value range
/// @param _type Indicated the type of the input
function isReturnInjection(uint8 _type) internal pure returns (bool) {
return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in return array value
/// @param _type Indicated the type of the input
function getReturnIndex(uint8 _type) internal pure returns (uint8) {
require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE);
return (_type - RETURN_MIN_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in sub array value
/// @param _type Indicated the type of the input
function getSubIndex(uint8 _type) internal pure returns (uint8) {
require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE);
return (_type - SUB_MIN_INDEX_VALUE);
}
}
contract LiquitySPWithdraw is ActionBase, LiquityHelper {
using TokenUtils for address;
struct Params {
uint256 lusdAmount; // Amount of LUSD tokens to withdraw
address to; // Address that will receive the tokens
address wethTo; // Address that will receive ETH(wrapped) gains
address lqtyTo; // Address that will receive LQTY token gains
}
/// @inheritdoc ActionBase
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
Params memory params = parseInputs(_callData);
params.lusdAmount = _parseParamUint(params.lusdAmount, _paramMapping[0], _subData, _returnValues);
params.to = _parseParamAddr(params.to, _paramMapping[1], _subData, _returnValues);
params.wethTo = _parseParamAddr(params.wethTo, _paramMapping[2], _subData, _returnValues);
params.lqtyTo = _parseParamAddr(params.lqtyTo, _paramMapping[3], _subData, _returnValues);
params.lusdAmount = _liquitySPWithdraw(params);
return bytes32(params.lusdAmount);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes[] memory _callData) public payable virtual override {
Params memory params = parseInputs(_callData);
_liquitySPWithdraw(params);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
/// @notice Withdraws LUSD from the user's stability pool deposit
function _liquitySPWithdraw(Params memory _params) internal returns (uint256) {
uint256 ethGain = StabilityPool.getDepositorETHGain(address(this));
uint256 lqtyGain = StabilityPool.getDepositorLQTYGain(address(this));
uint256 deposit = StabilityPool.getCompoundedLUSDDeposit(address(this));
_params.lusdAmount = deposit > _params.lusdAmount ? _params.lusdAmount : deposit;
StabilityPool.withdrawFromSP(_params.lusdAmount);
// Amount goes through min(amount, depositedAmount)
LUSDTokenAddr.withdrawTokens(_params.to, _params.lusdAmount);
withdrawStabilityGains(ethGain, lqtyGain, _params.wethTo, _params.lqtyTo);
logger.Log(
address(this),
msg.sender,
"LiquitySPWithdraw",
abi.encode(
_params,
ethGain,
lqtyGain
)
);
return _params.lusdAmount;
}
function parseInputs(bytes[] memory _callData) internal pure returns (Params memory params) {
params = abi.decode(_callData[0], (Params));
}
} | Common interface for the Trove Manager. --- Events --- | interface ITroveManager {
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LQTYTokenAddressChanged(address _lqtyTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _LUSDGasCompensation);
event Redemption(uint _attemptedLUSDAmount, uint _actualLUSDAmount, uint _ETHSent, uint _ETHFee);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation);
event BaseRateUpdated(uint _baseRate);
event LastFeeOpTimeUpdated(uint _lastFeeOpTime);
event TotalStakesUpdated(uint _newTotalStakes);
event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot);
event LTermsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveSnapshotsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveIndexUpdated(address _borrower, uint _newIndex);
function getTroveOwnersCount() external view returns (uint);
function getTroveFromTroveOwnersArray(uint _index) external view returns (address);
function getNominalICR(address _borrower) external view returns (uint);
function getCurrentICR(address _borrower, uint _price) external view returns (uint);
function liquidate(address _borrower) external;
function liquidateTroves(uint _n) external;
function batchLiquidateTroves(address[] calldata _troveArray) external;
function redeemCollateral(
uint _LUSDAmount,
address _firstRedemptionHint,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint _partialRedemptionHintNICR,
uint _maxIterations,
uint _maxFee
) external;
function updateStakeAndTotalStakes(address _borrower) external returns (uint);
function updateTroveRewardSnapshots(address _borrower) external;
function addTroveOwnerToArray(address _borrower) external returns (uint index);
function applyPendingRewards(address _borrower) external;
function getPendingETHReward(address _borrower) external view returns (uint);
function getPendingLUSDDebtReward(address _borrower) external view returns (uint);
function hasPendingRewards(address _borrower) external view returns (bool);
function getEntireDebtAndColl(address _borrower) external view returns (
uint debt,
uint coll,
uint pendingLUSDDebtReward,
uint pendingETHReward
);
function closeTrove(address _borrower) external;
function removeStake(address _borrower) external;
function getRedemptionRate() external view returns (uint);
function getRedemptionRateWithDecay() external view returns (uint);
function getRedemptionFeeWithDecay(uint _ETHDrawn) external view returns (uint);
function getBorrowingRate() external view returns (uint);
function getBorrowingRateWithDecay() external view returns (uint);
function getBorrowingFee(uint LUSDDebt) external view returns (uint);
function getBorrowingFeeWithDecay(uint _LUSDDebt) external view returns (uint);
function decayBaseRateFromBorrowing() external;
function getTroveStatus(address _borrower) external view returns (uint);
function getTroveStake(address _borrower) external view returns (uint);
function getTroveDebt(address _borrower) external view returns (uint);
function getTroveColl(address _borrower) external view returns (uint);
function setTroveStatus(address _borrower, uint num) external;
function increaseTroveColl(address _borrower, uint _collIncrease) external returns (uint);
function decreaseTroveColl(address _borrower, uint _collDecrease) external returns (uint);
function increaseTroveDebt(address _borrower, uint _debtIncrease) external returns (uint);
function decreaseTroveDebt(address _borrower, uint _collDecrease) external returns (uint);
function getTCR(uint _price) external view returns (uint);
function checkRecoveryMode(uint _price) external view returns (bool);
}
| 14,390,465 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @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 {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// 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 (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 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
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
// 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);
}
}
}
}
// 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 (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// 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 v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^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;
if (lastIndex != toDeleteIndex) {
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] = valueIndex; // Replace lastvalue's index to valueIndex
}
// 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) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values 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));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
import { IPoolCollection } from "../../pools/interfaces/IPoolCollection.sol";
import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol";
/**
* @dev Flash-loan recipient interface
*/
interface IFlashLoanRecipient {
/**
* @dev a flash-loan recipient callback after each the caller must return the borrowed amount and an additional fee
*/
function onFlashLoan(
address caller,
IERC20 erc20Token,
uint256 amount,
uint256 feeAmount,
bytes memory data
) external;
}
/**
* @dev Bancor Network interface
*/
interface IBancorNetwork is IUpgradeable {
/**
* @dev returns the set of all valid pool collections
*/
function poolCollections() external view returns (IPoolCollection[] memory);
/**
* @dev returns the most recent collection that was added to the pool collections set for a specific type
*/
function latestPoolCollection(uint16 poolType) external view returns (IPoolCollection);
/**
* @dev returns the set of all liquidity pools
*/
function liquidityPools() external view returns (Token[] memory);
/**
* @dev returns the respective pool collection for the provided pool
*/
function collectionByPool(Token pool) external view returns (IPoolCollection);
/**
* @dev returns whether the pool is valid
*/
function isPoolValid(Token pool) external view returns (bool);
/**
* @dev creates a new pool
*
* requirements:
*
* - the pool doesn't already exist
*/
function createPool(uint16 poolType, Token token) external;
/**
* @dev creates new pools
*
* requirements:
*
* - none of the pools already exists
*/
function createPools(uint16 poolType, Token[] calldata tokens) external;
/**
* @dev migrates a list of pools between pool collections
*
* notes:
*
* - invalid or incompatible pools will be skipped gracefully
*/
function migratePools(Token[] calldata pools) external;
/**
* @dev deposits liquidity for the specified provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must have approved the network to transfer the tokens on its behalf (except for in the
* native token case)
*/
function depositFor(
address provider,
Token pool,
uint256 tokenAmount
) external payable returns (uint256);
/**
* @dev deposits liquidity for the current provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must have approved the network to transfer the tokens on its behalf (except for in the
* native token case)
*/
function deposit(Token pool, uint256 tokenAmount) external payable returns (uint256);
/**
* @dev deposits liquidity for the specified provider by providing an EIP712 typed signature for an EIP2612 permit
* request and returns the respective pool token amount
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function depositForPermitted(
address provider,
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev deposits liquidity by providing an EIP712 typed signature for an EIP2612 permit request and returns the
* respective pool token amount
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function depositPermitted(
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev initiates liquidity withdrawal
*
* requirements:
*
* - the caller must have approved the contract to transfer the pool token amount on its behalf
*/
function initWithdrawal(IPoolToken poolToken, uint256 poolTokenAmount) external returns (uint256);
/**
* @dev initiates liquidity withdrawal by providing an EIP712 typed signature for an EIP2612 permit request
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function initWithdrawalPermitted(
IPoolToken poolToken,
uint256 poolTokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev cancels a withdrawal request
*
* requirements:
*
* - the caller must have already initiated a withdrawal and received the specified id
*/
function cancelWithdrawal(uint256 id) external;
/**
* @dev withdraws liquidity and returns the withdrawn amount
*
* requirements:
*
* - the provider must have already initiated a withdrawal and received the specified id
* - the specified withdrawal request is eligible for completion
* - the provider must have approved the network to transfer VBNT amount on its behalf, when withdrawing BNT
* liquidity
*/
function withdraw(uint256 id) external returns (uint256);
/**
* @dev performs a trade by providing the input source amount
*
* requirements:
*
* - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
* native token case)
*/
function tradeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary
) external payable;
/**
* @dev performs a trade by providing the input source amount and providing an EIP712 typed signature for an
* EIP2612 permit request
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function tradeBySourceAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev performs a trade by providing the output target amount
*
* requirements:
*
* - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
* native token case)
*/
function tradeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary
) external payable;
/**
* @dev performs a trade by providing the output target amount and providing an EIP712 typed signature for an
* EIP2612 permit request and returns the target amount and fee
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function tradeByTargetAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev provides a flash-loan
*
* requirements:
*
* - the recipient's callback must return *at least* the borrowed amount and fee back to the specified return address
*/
function flashLoan(
Token token,
uint256 amount,
IFlashLoanRecipient recipient,
bytes calldata data
) external;
/**
* @dev deposits liquidity during a migration
*/
function migrateLiquidity(
Token token,
address provider,
uint256 amount,
uint256 availableAmount,
uint256 originalAmount
) external payable;
/**
* @dev withdraws pending network fees
*
* requirements:
*
* - the caller must have the ROLE_NETWORK_FEE_MANAGER privilege
*/
function withdrawNetworkFees(address recipient) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
error NotWhitelisted();
struct VortexRewards {
// the percentage of converted BNT to be sent to the initiator of the burning event (in units of PPM)
uint32 burnRewardPPM;
// the maximum burn reward to be sent to the initiator of the burning event
uint256 burnRewardMaxAmount;
}
/**
* @dev Network Settings interface
*/
interface INetworkSettings is IUpgradeable {
/**
* @dev returns the protected tokens whitelist
*/
function protectedTokenWhitelist() external view returns (Token[] memory);
/**
* @dev checks whether a given token is whitelisted
*/
function isTokenWhitelisted(Token pool) external view returns (bool);
/**
* @dev returns the BNT funding limit for a given pool
*/
function poolFundingLimit(Token pool) external view returns (uint256);
/**
* @dev returns the minimum BNT trading liquidity required before the system enables trading in the relevant pool
*/
function minLiquidityForTrading() external view returns (uint256);
/**
* @dev returns the global network fee (in units of PPM)
*
* notes:
*
* - the network fee is a portion of the total fees from each pool
*/
function networkFeePPM() external view returns (uint32);
/**
* @dev returns the withdrawal fee (in units of PPM)
*/
function withdrawalFeePPM() external view returns (uint32);
/**
* @dev returns the default flash-loan fee (in units of PPM)
*/
function defaultFlashLoanFeePPM() external view returns (uint32);
/**
* @dev returns the flash-loan fee (in units of PPM) of a pool
*/
function flashLoanFeePPM(Token pool) external view returns (uint32);
/**
* @dev returns the vortex settings
*/
function vortexRewards() external view returns (VortexRewards memory);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { Token } from "../token/Token.sol";
import { TokenLibrary } from "../token/TokenLibrary.sol";
import { IMasterVault } from "../vaults/interfaces/IMasterVault.sol";
import { IExternalProtectionVault } from "../vaults/interfaces/IExternalProtectionVault.sol";
import { IVersioned } from "../utility/interfaces/IVersioned.sol";
import { PPM_RESOLUTION } from "../utility/Constants.sol";
import { Owned } from "../utility/Owned.sol";
import { BlockNumber } from "../utility/BlockNumber.sol";
import { Fraction, Fraction112, FractionLibrary, zeroFraction, zeroFraction112 } from "../utility/FractionLibrary.sol";
import { Sint256, MathEx } from "../utility/MathEx.sol";
// prettier-ignore
import {
Utils,
AlreadyExists,
DoesNotExist,
InvalidPoolCollection,
InvalidStakedBalance
} from "../utility/Utils.sol";
import { INetworkSettings, NotWhitelisted } from "../network/interfaces/INetworkSettings.sol";
import { IBancorNetwork } from "../network/interfaces/IBancorNetwork.sol";
import { IPoolToken } from "./interfaces/IPoolToken.sol";
import { IPoolTokenFactory } from "./interfaces/IPoolTokenFactory.sol";
import { IPoolMigrator } from "./interfaces/IPoolMigrator.sol";
// prettier-ignore
import {
AverageRate,
IPoolCollection,
PoolLiquidity,
Pool,
TRADING_STATUS_UPDATE_DEFAULT,
TRADING_STATUS_UPDATE_ADMIN,
TRADING_STATUS_UPDATE_MIN_LIQUIDITY,
TradeAmountAndFee,
WithdrawalAmounts
} from "./interfaces/IPoolCollection.sol";
import { IBNTPool } from "./interfaces/IBNTPool.sol";
import { PoolCollectionWithdrawal } from "./PoolCollectionWithdrawal.sol";
// base token withdrawal output amounts
struct InternalWithdrawalAmounts {
uint256 baseTokensToTransferFromMasterVault; // base token amount to transfer from the master vault to the provider
uint256 bntToMintForProvider; // BNT amount to mint directly for the provider
uint256 baseTokensToTransferFromEPV; // base token amount to transfer from the external protection vault to the provider
Sint256 baseTokensTradingLiquidityDelta; // base token amount to add to the trading liquidity
Sint256 bntTradingLiquidityDelta; // BNT amount to add to the trading liquidity and to the master vault
Sint256 bntProtocolHoldingsDelta; // BNT amount add to the protocol equity
uint256 baseTokensWithdrawalFee; // base token amount to keep in the pool as a withdrawal fee
uint256 baseTokensWithdrawalAmount; // base token amount equivalent to the base pool token's withdrawal amount
uint256 poolTokenTotalSupply; // base pool token's total supply
uint256 newBaseTokenTradingLiquidity; // new base token trading liquidity
uint256 newBNTTradingLiquidity; // new BNT trading liquidity
}
struct TradingLiquidityAction {
bool update;
uint256 newAmount;
}
enum PoolRateState {
Uninitialized,
Unstable,
Stable
}
/**
* @dev Pool Collection contract
*
* notes:
*
* - the address of reserve token serves as the pool unique ID in both contract functions and events
*/
contract PoolCollection is IPoolCollection, Owned, BlockNumber, Utils {
using TokenLibrary for Token;
using FractionLibrary for Fraction;
using FractionLibrary for Fraction112;
using EnumerableSet for EnumerableSet.AddressSet;
error AlreadyEnabled();
error DepositLimitExceeded();
error DepositingDisabled();
error InsufficientLiquidity();
error InsufficientSourceAmount();
error InsufficientTargetAmount();
error InvalidRate();
error RateUnstable();
error TradingDisabled();
uint16 private constant POOL_TYPE = 1;
uint256 private constant LIQUIDITY_GROWTH_FACTOR = 2;
uint256 private constant BOOTSTRAPPING_LIQUIDITY_BUFFER_FACTOR = 2;
uint32 private constant DEFAULT_TRADING_FEE_PPM = 2000; // 0.2%
uint32 private constant RATE_MAX_DEVIATION_PPM = 10000; // %1
// the average rate is recalculated based on the ratio between the weights of the rates the smaller the weights are,
// the larger the supported range of each one of the rates is
uint256 private constant EMA_AVERAGE_RATE_WEIGHT = 4;
uint256 private constant EMA_SPOT_RATE_WEIGHT = 1;
struct TradeIntermediateResult {
uint256 sourceAmount;
uint256 targetAmount;
uint256 limit;
uint256 tradingFeeAmount;
uint256 networkFeeAmount;
uint256 sourceBalance;
uint256 targetBalance;
uint256 stakedBalance;
Token pool;
bool isSourceBNT;
bool bySourceAmount;
uint32 tradingFeePPM;
bytes32 contextId;
}
struct TradeAmountAndTradingFee {
uint256 amount;
uint256 tradingFeeAmount;
}
// the network contract
IBancorNetwork private immutable _network;
// the address of the BNT token
IERC20 private immutable _bnt;
// the network settings contract
INetworkSettings private immutable _networkSettings;
// the master vault contract
IMasterVault private immutable _masterVault;
// the BNT pool contract
IBNTPool internal immutable _bntPool;
// the address of the external protection vault
IExternalProtectionVault private immutable _externalProtectionVault;
// the pool token factory contract
IPoolTokenFactory private immutable _poolTokenFactory;
// the pool migrator contract
IPoolMigrator private immutable _poolMigrator;
// a mapping between tokens and their pools
mapping(Token => Pool) internal _poolData;
// the set of all pools which are managed by this pool collection
EnumerableSet.AddressSet private _pools;
// the default trading fee (in units of PPM)
uint32 private _defaultTradingFeePPM;
/**
* @dev triggered when a pool is created
*/
event PoolCreated(IPoolToken indexed poolToken, Token indexed token);
/**
* @dev triggered when the default trading fee is updated
*/
event DefaultTradingFeePPMUpdated(uint32 prevFeePPM, uint32 newFeePPM);
/**
* @dev triggered when a specific pool's trading fee is updated
*/
event TradingFeePPMUpdated(Token indexed pool, uint32 prevFeePPM, uint32 newFeePPM);
/**
* @dev triggered when trading in a specific pool is enabled/disabled
*/
event TradingEnabled(Token indexed pool, bool indexed newStatus, uint8 indexed reason);
/**
* @dev triggered when depositing into a specific pool is enabled/disabled
*/
event DepositingEnabled(Token indexed pool, bool indexed newStatus);
/**
* @dev triggered when a pool's deposit limit is updated
*/
event DepositLimitUpdated(Token indexed pool, uint256 prevDepositLimit, uint256 newDepositLimit);
/**
* @dev triggered when new liquidity is deposited into a pool
*/
event TokensDeposited(
bytes32 indexed contextId,
address indexed provider,
Token indexed token,
uint256 tokenAmount,
uint256 poolTokenAmount
);
/**
* @dev triggered when existing liquidity is withdrawn from a pool
*/
event TokensWithdrawn(
bytes32 indexed contextId,
address indexed provider,
Token indexed token,
uint256 tokenAmount,
uint256 poolTokenAmount,
uint256 externalProtectionBaseTokenAmount,
uint256 bntAmount,
uint256 withdrawalFeeAmount
);
/**
* @dev triggered when the trading liquidity in a pool is updated
*/
event TradingLiquidityUpdated(
bytes32 indexed contextId,
Token indexed pool,
Token indexed token,
uint256 prevLiquidity,
uint256 newLiquidity
);
/**
* @dev triggered when the total liquidity in a pool is updated
*/
event TotalLiquidityUpdated(
bytes32 indexed contextId,
Token indexed pool,
uint256 liquidity,
uint256 stakedBalance,
uint256 poolTokenSupply
);
/**
* @dev initializes a new PoolCollection contract
*/
constructor(
IBancorNetwork initNetwork,
IERC20 initBNT,
INetworkSettings initNetworkSettings,
IMasterVault initMasterVault,
IBNTPool initBNTPool,
IExternalProtectionVault initExternalProtectionVault,
IPoolTokenFactory initPoolTokenFactory,
IPoolMigrator initPoolMigrator
)
validAddress(address(initNetwork))
validAddress(address(initBNT))
validAddress(address(initNetworkSettings))
validAddress(address(initMasterVault))
validAddress(address(initBNTPool))
validAddress(address(initExternalProtectionVault))
validAddress(address(initPoolTokenFactory))
validAddress(address(initPoolMigrator))
{
_network = initNetwork;
_bnt = initBNT;
_networkSettings = initNetworkSettings;
_masterVault = initMasterVault;
_bntPool = initBNTPool;
_externalProtectionVault = initExternalProtectionVault;
_poolTokenFactory = initPoolTokenFactory;
_poolMigrator = initPoolMigrator;
_setDefaultTradingFeePPM(DEFAULT_TRADING_FEE_PPM);
}
/**
* @inheritdoc IVersioned
*/
function version() external view virtual returns (uint16) {
return 2;
}
/**
* @inheritdoc IPoolCollection
*/
function poolType() external pure returns (uint16) {
return POOL_TYPE;
}
/**
* @inheritdoc IPoolCollection
*/
function defaultTradingFeePPM() external view returns (uint32) {
return _defaultTradingFeePPM;
}
/**
* @inheritdoc IPoolCollection
*/
function pools() external view returns (Token[] memory) {
uint256 length = _pools.length();
Token[] memory list = new Token[](length);
for (uint256 i = 0; i < length; i++) {
list[i] = Token(_pools.at(i));
}
return list;
}
/**
* @inheritdoc IPoolCollection
*/
function poolCount() external view returns (uint256) {
return _pools.length();
}
/**
* @dev sets the default trading fee (in units of PPM)
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function setDefaultTradingFeePPM(uint32 newDefaultTradingFeePPM)
external
onlyOwner
validFee(newDefaultTradingFeePPM)
{
_setDefaultTradingFeePPM(newDefaultTradingFeePPM);
}
/**
* @inheritdoc IPoolCollection
*/
function createPool(Token token) external only(address(_network)) {
if (!_networkSettings.isTokenWhitelisted(token)) {
revert NotWhitelisted();
}
IPoolToken newPoolToken = IPoolToken(_poolTokenFactory.createPoolToken(token));
newPoolToken.acceptOwnership();
Pool memory newPool = Pool({
poolToken: newPoolToken,
tradingFeePPM: _defaultTradingFeePPM,
tradingEnabled: false,
depositingEnabled: true,
averageRate: AverageRate({ blockNumber: 0, rate: zeroFraction112() }),
depositLimit: 0,
liquidity: PoolLiquidity({ bntTradingLiquidity: 0, baseTokenTradingLiquidity: 0, stakedBalance: 0 })
});
_addPool(token, newPool);
emit PoolCreated({ poolToken: newPoolToken, token: token });
emit TradingEnabled({ pool: token, newStatus: false, reason: TRADING_STATUS_UPDATE_DEFAULT });
emit TradingFeePPMUpdated({ pool: token, prevFeePPM: 0, newFeePPM: newPool.tradingFeePPM });
emit DepositingEnabled({ pool: token, newStatus: newPool.depositingEnabled });
emit DepositLimitUpdated({ pool: token, prevDepositLimit: 0, newDepositLimit: newPool.depositLimit });
}
/**
* @inheritdoc IPoolCollection
*/
function isPoolValid(Token pool) external view returns (bool) {
return address(_poolData[pool].poolToken) != address(0);
}
/**
* @inheritdoc IPoolCollection
*/
function poolData(Token pool) external view returns (Pool memory) {
return _poolData[pool];
}
/**
* @inheritdoc IPoolCollection
*/
function poolLiquidity(Token pool) external view returns (PoolLiquidity memory) {
return _poolData[pool].liquidity;
}
/**
* @inheritdoc IPoolCollection
*/
function poolToken(Token pool) external view returns (IPoolToken) {
return _poolData[pool].poolToken;
}
/**
* @inheritdoc IPoolCollection
*/
function poolTokenToUnderlying(Token pool, uint256 poolTokenAmount) external view returns (uint256) {
Pool storage data = _poolData[pool];
return _poolTokenToUnderlying(poolTokenAmount, data.poolToken.totalSupply(), data.liquidity.stakedBalance);
}
/**
* @inheritdoc IPoolCollection
*/
function underlyingToPoolToken(Token pool, uint256 tokenAmount) external view returns (uint256) {
Pool storage data = _poolData[pool];
return _underlyingToPoolToken(tokenAmount, data.poolToken.totalSupply(), data.liquidity.stakedBalance);
}
/**
* @inheritdoc IPoolCollection
*/
function poolTokenAmountToBurn(
Token pool,
uint256 tokenAmountToDistribute,
uint256 protocolPoolTokenAmount
) external view returns (uint256) {
if (tokenAmountToDistribute == 0) {
return 0;
}
Pool storage data = _poolData[pool];
uint256 poolTokenSupply = data.poolToken.totalSupply();
uint256 val = tokenAmountToDistribute * poolTokenSupply;
return
MathEx.mulDivF(
val,
poolTokenSupply,
val + data.liquidity.stakedBalance * (poolTokenSupply - protocolPoolTokenAmount)
);
}
/**
* @dev sets the trading fee of a given pool
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function setTradingFeePPM(Token pool, uint32 newTradingFeePPM) external onlyOwner validFee(newTradingFeePPM) {
Pool storage data = _poolStorage(pool);
uint32 prevTradingFeePPM = data.tradingFeePPM;
if (prevTradingFeePPM == newTradingFeePPM) {
return;
}
data.tradingFeePPM = newTradingFeePPM;
emit TradingFeePPMUpdated({ pool: pool, prevFeePPM: prevTradingFeePPM, newFeePPM: newTradingFeePPM });
}
/**
* @dev enables trading in a given pool, by providing the funding rate as two virtual balances, and updates its
* trading liquidity
*
* please note that the virtual balances should be derived from token prices, normalized to the smallest unit of
* tokens. For example:
*
* - if the price of one (10**18 wei) BNT is $X and the price of one (10**18 wei) TKN is $Y, then the virtual balances
* should represent a ratio of X to Y
* - if the price of one (10**18 wei) BNT is $X and the price of one (10**6 wei) USDC is $Y, then the virtual balances
* should represent a ratio of X to Y*10**12
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function enableTrading(
Token pool,
uint256 bntVirtualBalance,
uint256 baseTokenVirtualBalance
) external onlyOwner {
Fraction memory fundingRate = Fraction({ n: bntVirtualBalance, d: baseTokenVirtualBalance });
_validRate(fundingRate);
Pool storage data = _poolStorage(pool);
if (data.tradingEnabled) {
revert AlreadyEnabled();
}
// adjust the trading liquidity based on the base token vault balance and funding limits
uint256 minLiquidityForTrading = _networkSettings.minLiquidityForTrading();
_updateTradingLiquidity(bytes32(0), pool, data, data.liquidity, fundingRate, minLiquidityForTrading);
// verify that the BNT trading liquidity is equal or greater than the minimum liquidity for trading
if (data.liquidity.bntTradingLiquidity < minLiquidityForTrading) {
revert InsufficientLiquidity();
}
data.averageRate = AverageRate({ blockNumber: _blockNumber(), rate: fundingRate.toFraction112() });
data.tradingEnabled = true;
emit TradingEnabled({ pool: pool, newStatus: true, reason: TRADING_STATUS_UPDATE_ADMIN });
}
/**
* @dev disables trading in a given pool
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function disableTrading(Token pool) external onlyOwner {
Pool storage data = _poolStorage(pool);
_resetTradingLiquidity(bytes32(0), pool, data, TRADING_STATUS_UPDATE_ADMIN);
}
/**
* @dev enables/disables depositing into a given pool
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function enableDepositing(Token pool, bool status) external onlyOwner {
Pool storage data = _poolStorage(pool);
if (data.depositingEnabled == status) {
return;
}
data.depositingEnabled = status;
emit DepositingEnabled({ pool: pool, newStatus: status });
}
/**
* @dev sets the deposit limit of a given pool
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function setDepositLimit(Token pool, uint256 newDepositLimit) external onlyOwner {
Pool storage data = _poolStorage(pool);
uint256 prevDepositLimit = data.depositLimit;
if (prevDepositLimit == newDepositLimit) {
return;
}
data.depositLimit = newDepositLimit;
emit DepositLimitUpdated({ pool: pool, prevDepositLimit: prevDepositLimit, newDepositLimit: newDepositLimit });
}
/**
* @inheritdoc IPoolCollection
*/
function depositFor(
bytes32 contextId,
address provider,
Token pool,
uint256 tokenAmount
) external only(address(_network)) validAddress(provider) greaterThanZero(tokenAmount) returns (uint256) {
Pool storage data = _poolStorage(pool);
if (!data.depositingEnabled) {
revert DepositingDisabled();
}
// calculate the pool token amount to mint
uint256 currentStakedBalance = data.liquidity.stakedBalance;
uint256 prevPoolTokenTotalSupply = data.poolToken.totalSupply();
uint256 poolTokenAmount = _underlyingToPoolToken(tokenAmount, prevPoolTokenTotalSupply, currentStakedBalance);
// verify that the staked balance and the newly deposited amount isn't higher than the deposit limit
uint256 newStakedBalance = currentStakedBalance + tokenAmount;
if (newStakedBalance > data.depositLimit) {
revert DepositLimitExceeded();
}
PoolLiquidity memory prevLiquidity = data.liquidity;
// update the staked balance with the full base token amount
data.liquidity.stakedBalance = newStakedBalance;
// mint pool tokens to the provider
data.poolToken.mint(provider, poolTokenAmount);
// adjust the trading liquidity based on the base token vault balance and funding limits
_updateTradingLiquidity(
contextId,
pool,
data,
data.liquidity,
data.averageRate.rate.fromFraction112(),
_networkSettings.minLiquidityForTrading()
);
emit TokensDeposited({
contextId: contextId,
provider: provider,
token: pool,
tokenAmount: tokenAmount,
poolTokenAmount: poolTokenAmount
});
_dispatchTradingLiquidityEvents(
contextId,
pool,
prevPoolTokenTotalSupply + poolTokenAmount,
prevLiquidity,
data.liquidity
);
return poolTokenAmount;
}
/**
* @inheritdoc IPoolCollection
*/
function withdraw(
bytes32 contextId,
address provider,
Token pool,
uint256 poolTokenAmount
) external only(address(_network)) validAddress(provider) greaterThanZero(poolTokenAmount) returns (uint256) {
Pool storage data = _poolStorage(pool);
// obtain the withdrawal amounts
InternalWithdrawalAmounts memory amounts = _poolWithdrawalAmounts(pool, data, poolTokenAmount);
// execute the actual withdrawal
_executeWithdrawal(contextId, provider, pool, data, poolTokenAmount, amounts);
return amounts.baseTokensToTransferFromMasterVault;
}
/**
* @inheritdoc IPoolCollection
*/
function withdrawalAmounts(Token pool, uint256 poolTokenAmount)
external
view
validAddress(address(pool))
greaterThanZero(poolTokenAmount)
returns (WithdrawalAmounts memory)
{
InternalWithdrawalAmounts memory amounts = _poolWithdrawalAmounts(pool, _poolStorage(pool), poolTokenAmount);
return
WithdrawalAmounts({
totalAmount: amounts.baseTokensWithdrawalAmount - amounts.baseTokensWithdrawalFee,
baseTokenAmount: amounts.baseTokensToTransferFromMasterVault + amounts.baseTokensToTransferFromEPV,
bntAmount: amounts.bntToMintForProvider
});
}
/**
* @inheritdoc IPoolCollection
*/
function tradeBySourceAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount
)
external
only(address(_network))
greaterThanZero(sourceAmount)
greaterThanZero(minReturnAmount)
returns (TradeAmountAndFee memory)
{
TradeIntermediateResult memory result = _initTrade(
contextId,
sourceToken,
targetToken,
sourceAmount,
minReturnAmount,
true
);
_performTrade(result);
return
TradeAmountAndFee({
amount: result.targetAmount,
tradingFeeAmount: result.tradingFeeAmount,
networkFeeAmount: result.networkFeeAmount
});
}
/**
* @inheritdoc IPoolCollection
*/
function tradeByTargetAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount
)
external
only(address(_network))
greaterThanZero(targetAmount)
greaterThanZero(maxSourceAmount)
returns (TradeAmountAndFee memory)
{
TradeIntermediateResult memory result = _initTrade(
contextId,
sourceToken,
targetToken,
targetAmount,
maxSourceAmount,
false
);
_performTrade(result);
return
TradeAmountAndFee({
amount: result.sourceAmount,
tradingFeeAmount: result.tradingFeeAmount,
networkFeeAmount: result.networkFeeAmount
});
}
/**
* @inheritdoc IPoolCollection
*/
function tradeOutputAndFeeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount
) external view greaterThanZero(sourceAmount) returns (TradeAmountAndFee memory) {
TradeIntermediateResult memory result = _initTrade(bytes32(0), sourceToken, targetToken, sourceAmount, 1, true);
_processTrade(result);
return
TradeAmountAndFee({
amount: result.targetAmount,
tradingFeeAmount: result.tradingFeeAmount,
networkFeeAmount: result.networkFeeAmount
});
}
/**
* @inheritdoc IPoolCollection
*/
function tradeInputAndFeeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount
) external view greaterThanZero(targetAmount) returns (TradeAmountAndFee memory) {
TradeIntermediateResult memory result = _initTrade(
bytes32(0),
sourceToken,
targetToken,
targetAmount,
type(uint256).max,
false
);
_processTrade(result);
return
TradeAmountAndFee({
amount: result.sourceAmount,
tradingFeeAmount: result.tradingFeeAmount,
networkFeeAmount: result.networkFeeAmount
});
}
/**
* @inheritdoc IPoolCollection
*/
function onFeesCollected(Token pool, uint256 feeAmount) external only(address(_network)) {
if (feeAmount == 0) {
return;
}
Pool storage data = _poolStorage(pool);
// increase the staked balance by the given amount
data.liquidity.stakedBalance += feeAmount;
}
/**
* @inheritdoc IPoolCollection
*/
function migratePoolIn(Token pool, Pool calldata data)
external
validAddress(address(pool))
only(address(_poolMigrator))
{
_addPool(pool, data);
data.poolToken.acceptOwnership();
}
/**
* @inheritdoc IPoolCollection
*/
function migratePoolOut(Token pool, IPoolCollection targetPoolCollection)
external
validAddress(address(targetPoolCollection))
only(address(_poolMigrator))
{
if (_network.latestPoolCollection(POOL_TYPE) != targetPoolCollection) {
revert InvalidPoolCollection();
}
IPoolToken cachedPoolToken = _poolData[pool].poolToken;
_removePool(pool);
cachedPoolToken.transferOwnership(address(targetPoolCollection));
}
/**
* @dev adds a pool
*/
function _addPool(Token pool, Pool memory data) private {
if (!_pools.add(address(pool))) {
revert AlreadyExists();
}
_poolData[pool] = data;
}
/**
* @dev removes a pool
*/
function _removePool(Token pool) private {
if (!_pools.remove(address(pool))) {
revert DoesNotExist();
}
delete _poolData[pool];
}
/**
* @dev returns withdrawal amounts
*/
function _poolWithdrawalAmounts(
Token pool,
Pool memory data,
uint256 poolTokenAmount
) internal view returns (InternalWithdrawalAmounts memory) {
// the base token trading liquidity of a given pool can never be higher than the base token balance of the vault
// whenever the base token trading liquidity is updated, it is set to at most the base token balance of the vault
uint256 baseTokenExcessAmount = pool.balanceOf(address(_masterVault)) -
data.liquidity.baseTokenTradingLiquidity;
uint256 poolTokenTotalSupply = data.poolToken.totalSupply();
uint256 baseTokensWithdrawalAmount = _poolTokenToUnderlying(
poolTokenAmount,
poolTokenTotalSupply,
data.liquidity.stakedBalance
);
PoolCollectionWithdrawal.Output memory output = PoolCollectionWithdrawal.calculateWithdrawalAmounts(
data.liquidity.bntTradingLiquidity,
data.liquidity.baseTokenTradingLiquidity,
baseTokenExcessAmount,
data.liquidity.stakedBalance,
pool.balanceOf(address(_externalProtectionVault)),
data.tradingFeePPM,
_networkSettings.withdrawalFeePPM(),
baseTokensWithdrawalAmount
);
return
InternalWithdrawalAmounts({
baseTokensToTransferFromMasterVault: output.s,
bntToMintForProvider: output.t,
baseTokensToTransferFromEPV: output.u,
baseTokensTradingLiquidityDelta: output.r,
bntTradingLiquidityDelta: output.p,
bntProtocolHoldingsDelta: output.q,
baseTokensWithdrawalFee: output.v,
baseTokensWithdrawalAmount: baseTokensWithdrawalAmount,
poolTokenTotalSupply: poolTokenTotalSupply,
newBaseTokenTradingLiquidity: output.r.isNeg
? data.liquidity.baseTokenTradingLiquidity - output.r.value
: data.liquidity.baseTokenTradingLiquidity + output.r.value,
newBNTTradingLiquidity: output.p.isNeg
? data.liquidity.bntTradingLiquidity - output.p.value
: data.liquidity.bntTradingLiquidity + output.p.value
});
}
/**
* @dev executes the following actions:
*
* - burn the network's base pool tokens
* - update the pool's base token staked balance
* - update the pool's base token trading liquidity
* - update the pool's BNT trading liquidity
* - update the pool's trading liquidity product
* - emit an event if the pool's BNT trading liquidity has crossed the minimum threshold
* (either above the threshold or below the threshold)
*/
function _executeWithdrawal(
bytes32 contextId,
address provider,
Token pool,
Pool storage data,
uint256 poolTokenAmount,
InternalWithdrawalAmounts memory amounts
) private {
PoolLiquidity storage liquidity = data.liquidity;
PoolLiquidity memory prevLiquidity = liquidity;
AverageRate memory averageRate = data.averageRate;
if (_poolRateState(prevLiquidity, averageRate) == PoolRateState.Unstable) {
revert RateUnstable();
}
data.poolToken.burnFrom(address(_network), poolTokenAmount);
uint256 newPoolTokenTotalSupply = amounts.poolTokenTotalSupply - poolTokenAmount;
liquidity.stakedBalance = MathEx.mulDivF(
liquidity.stakedBalance,
newPoolTokenTotalSupply,
amounts.poolTokenTotalSupply
);
// trading liquidity is assumed to never exceed 128 bits (the cast below will revert otherwise)
liquidity.baseTokenTradingLiquidity = SafeCast.toUint128(amounts.newBaseTokenTradingLiquidity);
liquidity.bntTradingLiquidity = SafeCast.toUint128(amounts.newBNTTradingLiquidity);
if (amounts.bntProtocolHoldingsDelta.value > 0) {
assert(amounts.bntProtocolHoldingsDelta.isNeg); // currently no support for requesting funding here
_bntPool.renounceFunding(contextId, pool, amounts.bntProtocolHoldingsDelta.value);
} else if (amounts.bntTradingLiquidityDelta.value > 0) {
if (amounts.bntTradingLiquidityDelta.isNeg) {
_bntPool.burnFromVault(amounts.bntTradingLiquidityDelta.value);
} else {
_bntPool.mint(address(_masterVault), amounts.bntTradingLiquidityDelta.value);
}
}
// if the provider should receive some BNT - ask the BNT pool to mint BNT to the provider
if (amounts.bntToMintForProvider > 0) {
_bntPool.mint(address(provider), amounts.bntToMintForProvider);
}
// if the provider should receive some base tokens from the external protection vault - remove the tokens from
// the external protection vault and send them to the master vault
if (amounts.baseTokensToTransferFromEPV > 0) {
_externalProtectionVault.withdrawFunds(
pool,
payable(address(_masterVault)),
amounts.baseTokensToTransferFromEPV
);
amounts.baseTokensToTransferFromMasterVault += amounts.baseTokensToTransferFromEPV;
}
// if the provider should receive some base tokens from the master vault - remove the tokens from the master
// vault and send them to the provider
if (amounts.baseTokensToTransferFromMasterVault > 0) {
_masterVault.withdrawFunds(pool, payable(provider), amounts.baseTokensToTransferFromMasterVault);
}
// ensure that the average rate is reset when the pool is being emptied
if (amounts.newBaseTokenTradingLiquidity == 0) {
data.averageRate.rate = zeroFraction112();
}
// if the new BNT trading liquidity is below the minimum liquidity for trading - reset the liquidity
if (amounts.newBNTTradingLiquidity < _networkSettings.minLiquidityForTrading()) {
_resetTradingLiquidity(
contextId,
pool,
data,
amounts.newBNTTradingLiquidity,
TRADING_STATUS_UPDATE_MIN_LIQUIDITY
);
}
emit TokensWithdrawn({
contextId: contextId,
provider: provider,
token: pool,
tokenAmount: amounts.baseTokensToTransferFromMasterVault,
poolTokenAmount: poolTokenAmount,
externalProtectionBaseTokenAmount: amounts.baseTokensToTransferFromEPV,
bntAmount: amounts.bntToMintForProvider,
withdrawalFeeAmount: amounts.baseTokensWithdrawalFee
});
_dispatchTradingLiquidityEvents(contextId, pool, newPoolTokenTotalSupply, prevLiquidity, data.liquidity);
}
/**
* @dev sets the default trading fee (in units of PPM)
*/
function _setDefaultTradingFeePPM(uint32 newDefaultTradingFeePPM) private {
uint32 prevDefaultTradingFeePPM = _defaultTradingFeePPM;
if (prevDefaultTradingFeePPM == newDefaultTradingFeePPM) {
return;
}
_defaultTradingFeePPM = newDefaultTradingFeePPM;
emit DefaultTradingFeePPMUpdated({ prevFeePPM: prevDefaultTradingFeePPM, newFeePPM: newDefaultTradingFeePPM });
}
/**
* @dev returns a storage reference to pool data
*/
function _poolStorage(Token pool) private view returns (Pool storage) {
Pool storage data = _poolData[pool];
if (address(data.poolToken) == address(0)) {
revert DoesNotExist();
}
return data;
}
/**
* @dev calculates base tokens amount
*/
function _poolTokenToUnderlying(
uint256 poolTokenAmount,
uint256 poolTokenSupply,
uint256 stakedBalance
) private pure returns (uint256) {
if (poolTokenSupply == 0) {
// if this is the initial liquidity provision - use a one-to-one pool token to base token rate
if (stakedBalance > 0) {
revert InvalidStakedBalance();
}
return poolTokenAmount;
}
return MathEx.mulDivF(poolTokenAmount, stakedBalance, poolTokenSupply);
}
/**
* @dev calculates pool tokens amount
*/
function _underlyingToPoolToken(
uint256 tokenAmount,
uint256 poolTokenSupply,
uint256 stakedBalance
) private pure returns (uint256) {
if (poolTokenSupply == 0) {
// if this is the initial liquidity provision - use a one-to-one pool token to base token rate
if (stakedBalance > 0) {
revert InvalidStakedBalance();
}
return tokenAmount;
}
return MathEx.mulDivC(tokenAmount, poolTokenSupply, stakedBalance);
}
/**
* @dev returns the target BNT trading liquidity, and whether or not it needs to be updated
*/
function _calcTargetBNTTradingLiquidity(
uint256 tokenReserveAmount,
uint256 availableFunding,
PoolLiquidity memory liquidity,
Fraction memory fundingRate,
uint256 minLiquidityForTrading
) private pure returns (TradingLiquidityAction memory) {
// calculate the target BNT trading liquidity based on the smaller between the following:
// - BNT liquidity required to match previously deposited based token liquidity
// - maximum available BNT trading liquidity (current amount + available funding)
uint256 targetBNTTradingLiquidity = Math.min(
MathEx.mulDivF(tokenReserveAmount, fundingRate.n, fundingRate.d),
liquidity.bntTradingLiquidity + availableFunding
);
// ensure that the target is above the minimum liquidity for trading
if (targetBNTTradingLiquidity < minLiquidityForTrading) {
return TradingLiquidityAction({ update: true, newAmount: 0 });
}
// calculate the new BNT trading liquidity and cap it by the growth factor
if (liquidity.bntTradingLiquidity == 0) {
// if the current BNT trading liquidity is 0, set it to the minimum liquidity for trading (with an
// additional buffer so that initial trades will be less likely to trigger disabling of trading)
uint256 newTargetBNTTradingLiquidity = minLiquidityForTrading * BOOTSTRAPPING_LIQUIDITY_BUFFER_FACTOR;
// ensure that we're not allocating more than the previously established limits
if (newTargetBNTTradingLiquidity > targetBNTTradingLiquidity) {
return TradingLiquidityAction({ update: false, newAmount: 0 });
}
targetBNTTradingLiquidity = newTargetBNTTradingLiquidity;
} else if (targetBNTTradingLiquidity >= liquidity.bntTradingLiquidity) {
// if the target is above the current trading liquidity, limit it by factoring the current value up. Please
// note that if the target is below the current trading liquidity - it will be reduced to it immediately
targetBNTTradingLiquidity = Math.min(
targetBNTTradingLiquidity,
liquidity.bntTradingLiquidity * LIQUIDITY_GROWTH_FACTOR
);
}
return TradingLiquidityAction({ update: true, newAmount: targetBNTTradingLiquidity });
}
/**
* @dev adjusts the trading liquidity based on the base token vault balance and funding limits
*/
function _updateTradingLiquidity(
bytes32 contextId,
Token pool,
Pool storage data,
PoolLiquidity memory liquidity,
Fraction memory fundingRate,
uint256 minLiquidityForTrading
) private {
// ensure that the base token reserve isn't empty
uint256 tokenReserveAmount = pool.balanceOf(address(_masterVault));
if (tokenReserveAmount == 0) {
_resetTradingLiquidity(contextId, pool, data, TRADING_STATUS_UPDATE_MIN_LIQUIDITY);
return;
}
if (_poolRateState(liquidity, data.averageRate) == PoolRateState.Unstable) {
return;
}
if (!fundingRate.isPositive()) {
_resetTradingLiquidity(contextId, pool, data, TRADING_STATUS_UPDATE_MIN_LIQUIDITY);
return;
}
TradingLiquidityAction memory action = _calcTargetBNTTradingLiquidity(
tokenReserveAmount,
_bntPool.availableFunding(pool),
liquidity,
fundingRate,
minLiquidityForTrading
);
if (!action.update) {
return;
}
if (action.newAmount == 0) {
_resetTradingLiquidity(contextId, pool, data, TRADING_STATUS_UPDATE_MIN_LIQUIDITY);
return;
}
// update funding from the BNT pool
if (action.newAmount > liquidity.bntTradingLiquidity) {
_bntPool.requestFunding(contextId, pool, action.newAmount - liquidity.bntTradingLiquidity);
} else if (action.newAmount < liquidity.bntTradingLiquidity) {
_bntPool.renounceFunding(contextId, pool, liquidity.bntTradingLiquidity - action.newAmount);
}
// calculate the base token trading liquidity based on the new BNT trading liquidity and the effective
// funding rate (please note that the effective funding rate is always the rate between BNT and the base token)
uint256 baseTokenTradingLiquidity = MathEx.mulDivF(action.newAmount, fundingRate.d, fundingRate.n);
// trading liquidity is assumed to never exceed 128 bits (the cast below will revert otherwise)
PoolLiquidity memory newLiquidity = PoolLiquidity({
bntTradingLiquidity: SafeCast.toUint128(action.newAmount),
baseTokenTradingLiquidity: SafeCast.toUint128(baseTokenTradingLiquidity),
stakedBalance: liquidity.stakedBalance
});
// update the liquidity data of the pool
data.liquidity = newLiquidity;
_dispatchTradingLiquidityEvents(contextId, pool, data.poolToken.totalSupply(), liquidity, newLiquidity);
}
function _dispatchTradingLiquidityEvents(
bytes32 contextId,
Token pool,
PoolLiquidity memory prevLiquidity,
PoolLiquidity memory newLiquidity
) private {
if (newLiquidity.bntTradingLiquidity != prevLiquidity.bntTradingLiquidity) {
emit TradingLiquidityUpdated({
contextId: contextId,
pool: pool,
token: Token(address(_bnt)),
prevLiquidity: prevLiquidity.bntTradingLiquidity,
newLiquidity: newLiquidity.bntTradingLiquidity
});
}
if (newLiquidity.baseTokenTradingLiquidity != prevLiquidity.baseTokenTradingLiquidity) {
emit TradingLiquidityUpdated({
contextId: contextId,
pool: pool,
token: pool,
prevLiquidity: prevLiquidity.baseTokenTradingLiquidity,
newLiquidity: newLiquidity.baseTokenTradingLiquidity
});
}
}
function _dispatchTradingLiquidityEvents(
bytes32 contextId,
Token pool,
uint256 poolTokenTotalSupply,
PoolLiquidity memory prevLiquidity,
PoolLiquidity memory newLiquidity
) private {
_dispatchTradingLiquidityEvents(contextId, pool, prevLiquidity, newLiquidity);
if (newLiquidity.stakedBalance != prevLiquidity.stakedBalance) {
emit TotalLiquidityUpdated({
contextId: contextId,
pool: pool,
liquidity: pool.balanceOf(address(_masterVault)),
stakedBalance: newLiquidity.stakedBalance,
poolTokenSupply: poolTokenTotalSupply
});
}
}
/**
* @dev resets trading liquidity and renounces any remaining BNT funding
*/
function _resetTradingLiquidity(
bytes32 contextId,
Token pool,
Pool storage data,
uint8 reason
) private {
_resetTradingLiquidity(contextId, pool, data, data.liquidity.bntTradingLiquidity, reason);
}
/**
* @dev resets trading liquidity and renounces any remaining BNT funding
*/
function _resetTradingLiquidity(
bytes32 contextId,
Token pool,
Pool storage data,
uint256 currentBNTTradingLiquidity,
uint8 reason
) private {
// reset the network and base token trading liquidities
data.liquidity.bntTradingLiquidity = 0;
data.liquidity.baseTokenTradingLiquidity = 0;
// reset the recent average rage
data.averageRate = AverageRate({ blockNumber: 0, rate: zeroFraction112() });
// ensure that trading is disabled
if (data.tradingEnabled) {
data.tradingEnabled = false;
emit TradingEnabled({ pool: pool, newStatus: false, reason: reason });
}
// renounce all network liquidity
if (currentBNTTradingLiquidity > 0) {
_bntPool.renounceFunding(contextId, pool, currentBNTTradingLiquidity);
}
}
/**
* @dev returns initial trading params
*/
function _initTrade(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 amount,
uint256 limit,
bool bySourceAmount
) private view returns (TradeIntermediateResult memory result) {
// ensure that BNT is either the source or the target token
bool isSourceBNT = sourceToken.isEqual(_bnt);
bool isTargetBNT = targetToken.isEqual(_bnt);
if (isSourceBNT && !isTargetBNT) {
result.isSourceBNT = true;
result.pool = targetToken;
} else if (!isSourceBNT && isTargetBNT) {
result.isSourceBNT = false;
result.pool = sourceToken;
} else {
// BNT isn't one of the tokens or is both of them
revert DoesNotExist();
}
Pool storage data = _poolStorage(result.pool);
// verify that trading is enabled
if (!data.tradingEnabled) {
revert TradingDisabled();
}
result.contextId = contextId;
result.bySourceAmount = bySourceAmount;
if (result.bySourceAmount) {
result.sourceAmount = amount;
} else {
result.targetAmount = amount;
}
result.limit = limit;
result.tradingFeePPM = data.tradingFeePPM;
PoolLiquidity memory liquidity = data.liquidity;
if (result.isSourceBNT) {
result.sourceBalance = liquidity.bntTradingLiquidity;
result.targetBalance = liquidity.baseTokenTradingLiquidity;
} else {
result.sourceBalance = liquidity.baseTokenTradingLiquidity;
result.targetBalance = liquidity.bntTradingLiquidity;
}
result.stakedBalance = liquidity.stakedBalance;
}
/**
* @dev returns trade amount and fee by providing the source amount
*/
function _tradeAmountAndFeeBySourceAmount(
uint256 sourceBalance,
uint256 targetBalance,
uint32 tradingFeePPM,
uint256 sourceAmount
) private pure returns (TradeAmountAndTradingFee memory) {
if (sourceBalance == 0 || targetBalance == 0) {
revert InsufficientLiquidity();
}
uint256 targetAmount = MathEx.mulDivF(targetBalance, sourceAmount, sourceBalance + sourceAmount);
uint256 tradingFeeAmount = MathEx.mulDivF(targetAmount, tradingFeePPM, PPM_RESOLUTION);
return
TradeAmountAndTradingFee({ amount: targetAmount - tradingFeeAmount, tradingFeeAmount: tradingFeeAmount });
}
/**
* @dev returns trade amount and fee by providing either the target amount
*/
function _tradeAmountAndFeeByTargetAmount(
uint256 sourceBalance,
uint256 targetBalance,
uint32 tradingFeePPM,
uint256 targetAmount
) private pure returns (TradeAmountAndTradingFee memory) {
if (sourceBalance == 0) {
revert InsufficientLiquidity();
}
uint256 tradingFeeAmount = MathEx.mulDivF(targetAmount, tradingFeePPM, PPM_RESOLUTION - tradingFeePPM);
uint256 fullTargetAmount = targetAmount + tradingFeeAmount;
uint256 sourceAmount = MathEx.mulDivF(sourceBalance, fullTargetAmount, targetBalance - fullTargetAmount);
return TradeAmountAndTradingFee({ amount: sourceAmount, tradingFeeAmount: tradingFeeAmount });
}
/**
* @dev processes a trade by providing either the source or the target amount and updates the in-memory intermediate
* result
*/
function _processTrade(TradeIntermediateResult memory result) private view {
TradeAmountAndTradingFee memory tradeAmountAndFee;
if (result.bySourceAmount) {
tradeAmountAndFee = _tradeAmountAndFeeBySourceAmount(
result.sourceBalance,
result.targetBalance,
result.tradingFeePPM,
result.sourceAmount
);
result.targetAmount = tradeAmountAndFee.amount;
// ensure that the target amount is above the requested minimum return amount
if (result.targetAmount < result.limit) {
revert InsufficientTargetAmount();
}
} else {
tradeAmountAndFee = _tradeAmountAndFeeByTargetAmount(
result.sourceBalance,
result.targetBalance,
result.tradingFeePPM,
result.targetAmount
);
result.sourceAmount = tradeAmountAndFee.amount;
// ensure that the user has provided enough tokens to make the trade
if (result.sourceAmount > result.limit) {
revert InsufficientSourceAmount();
}
}
result.tradingFeeAmount = tradeAmountAndFee.tradingFeeAmount;
// sync the trading and staked balance
result.sourceBalance += result.sourceAmount;
result.targetBalance -= result.targetAmount;
if (result.isSourceBNT) {
result.stakedBalance += result.tradingFeeAmount;
}
_processNetworkFee(result);
}
/**
* @dev processes the network fee and updates the in-memory intermediate result
*/
function _processNetworkFee(TradeIntermediateResult memory result) private view {
uint32 networkFeePPM = _networkSettings.networkFeePPM();
if (networkFeePPM == 0) {
return;
}
// calculate the target network fee amount
uint256 targetNetworkFeeAmount = MathEx.mulDivF(result.tradingFeeAmount, networkFeePPM, PPM_RESOLUTION);
// update the target balance (but don't deduct it from the full trading fee amount)
result.targetBalance -= targetNetworkFeeAmount;
if (!result.isSourceBNT) {
result.networkFeeAmount = targetNetworkFeeAmount;
return;
}
// trade the network fee (taken from the base token) to BNT
result.networkFeeAmount = _tradeAmountAndFeeBySourceAmount(
result.targetBalance,
result.sourceBalance,
0,
targetNetworkFeeAmount
).amount;
// since we have received the network fee in base tokens and have traded them for BNT (so that the network fee
// is always kept in BNT), we'd need to adapt the trading liquidity and the staked balance accordingly
result.targetBalance += targetNetworkFeeAmount;
result.sourceBalance -= result.networkFeeAmount;
result.stakedBalance -= targetNetworkFeeAmount;
}
/**
* @dev performs a trade
*/
function _performTrade(TradeIntermediateResult memory result) private {
Pool storage data = _poolData[result.pool];
PoolLiquidity memory prevLiquidity = data.liquidity;
// update the recent average rate
_updateAverageRate(
data,
Fraction({ n: prevLiquidity.bntTradingLiquidity, d: prevLiquidity.baseTokenTradingLiquidity })
);
_processTrade(result);
// trading liquidity is assumed to never exceed 128 bits (the cast below will revert otherwise)
PoolLiquidity memory newLiquidity = PoolLiquidity({
bntTradingLiquidity: SafeCast.toUint128(result.isSourceBNT ? result.sourceBalance : result.targetBalance),
baseTokenTradingLiquidity: SafeCast.toUint128(
result.isSourceBNT ? result.targetBalance : result.sourceBalance
),
stakedBalance: result.stakedBalance
});
_dispatchTradingLiquidityEvents(result.contextId, result.pool, prevLiquidity, newLiquidity);
// update the liquidity data of the pool
data.liquidity = newLiquidity;
}
/**
* @dev returns the state of a pool's rate
*/
function _poolRateState(PoolLiquidity memory liquidity, AverageRate memory averageRateInfo)
internal
view
returns (PoolRateState)
{
Fraction memory spotRate = Fraction({
n: liquidity.bntTradingLiquidity,
d: liquidity.baseTokenTradingLiquidity
});
Fraction112 memory averageRate = averageRateInfo.rate;
if (!spotRate.isPositive() || !averageRate.isPositive()) {
return PoolRateState.Uninitialized;
}
if (averageRateInfo.blockNumber != _blockNumber()) {
averageRate = _calcAverageRate(averageRate, spotRate);
}
if (MathEx.isInRange(averageRate.fromFraction112(), spotRate, RATE_MAX_DEVIATION_PPM)) {
return PoolRateState.Stable;
}
return PoolRateState.Unstable;
}
/**
* @dev updates the average rate
*/
function _updateAverageRate(Pool storage data, Fraction memory spotRate) private {
uint32 blockNumber = _blockNumber();
if (data.averageRate.blockNumber != blockNumber) {
data.averageRate = AverageRate({
blockNumber: blockNumber,
rate: _calcAverageRate(data.averageRate.rate, spotRate)
});
}
}
/**
* @dev calculates the average rate
*/
function _calcAverageRate(Fraction112 memory averageRate, Fraction memory spotRate)
private
pure
returns (Fraction112 memory)
{
return
MathEx
.weightedAverage(averageRate.fromFraction112(), spotRate, EMA_AVERAGE_RATE_WEIGHT, EMA_SPOT_RATE_WEIGHT)
.toFraction112();
}
/**
* @dev verifies if the provided rate is valid
*/
function _validRate(Fraction memory rate) internal pure {
if (!rate.isPositive()) {
revert InvalidRate();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { PPM_RESOLUTION as M } from "../utility/Constants.sol";
import { Sint256, Uint512, MathEx } from "../utility/MathEx.sol";
error PoolCollectionWithdrawalInputInvalid();
/**
* @dev This library implements the mathematics behind base-token withdrawal.
* It exposes a single function which takes the following input values:
* `a` - BNT trading liquidity
* `b` - base token trading liquidity
* `c` - base token excess amount
* `e` - base token staked amount
* `w` - base token external protection vault balance
* `m` - trading fee in PPM units
* `n` - withdrawal fee in PPM units
* `x` - base token withdrawal amount
* And returns the following output values:
* `p` - BNT amount to add to the trading liquidity and to the master vault
* `q` - BNT amount to add to the protocol equity
* `r` - base token amount to add to the trading liquidity
* `s` - base token amount to transfer from the master vault to the provider
* `t` - BNT amount to mint directly for the provider
* `u` - base token amount to transfer from the external protection vault to the provider
* `v` - base token amount to keep in the pool as a withdrawal fee
* The following table depicts the actual formulae based on the current state of the system:
* +-----------+---------------------------------------------------------+----------------------------------------------------------+
* | | Deficit | Surplus |
* +-----------+---------------------------------------------------------+----------------------------------------------------------+
* | | p = a*x*(e*(1-n)-b-c)*(1-m)/(b*e-x*(e*(1-n)-b-c)*(1-m)) | p = -a*x*(b+c-e*(1-n))/(b*e*(1-m)+x*(b+c-e*(1-n))*(1-m)) |
* | | q = 0 | q = 0 |
* | | r = -x*(e*(1-n)-b-c)/e | r = x*(b+c-e*(1-n))/e |
* | Arbitrage | s = x*(1-n) | s = x*(1-n) |
* | | t = 0 | t = 0 |
* | | u = 0 | u = 0 |
* | | v = x*n | v = x*n |
* +-----------+---------------------------------------------------------+----------------------------------------------------------+
* | | p = -a*z/(b*e) where z = max(x*(1-n)*b-c*(e-x*(1-n)),0) | p = -a*z/b where z = max(x*(1-n)-c,0) |
* | | q = -a*z/(b*e) where z = max(x*(1-n)*b-c*(e-x*(1-n)),0) | q = -a*z/b where z = max(x*(1-n)-c,0) |
* | | r = -z/e where z = max(x*(1-n)*b-c*(e-x*(1-n)),0) | r = -z where z = max(x*(1-n)-c,0) |
* | Default | s = x*(1-n)*(b+c)/e | s = x*(1-n) |
* | | t = see function `externalProtection` | t = 0 |
* | | u = see function `externalProtection` | u = 0 |
* | | v = x*n | v = x*n |
* +-----------+---------------------------------------------------------+----------------------------------------------------------+
* | | p = 0 | p = 0 |
* | | q = 0 | q = 0 |
* | | r = 0 | r = 0 |
* | Bootstrap | s = x*(1-n)*c/e | s = x*(1-n) |
* | | t = see function `externalProtection` | t = 0 |
* | | u = see function `externalProtection` | u = 0 |
* | | v = x*n | v = x*n |
* +-----------+---------------------------------------------------------+----------------------------------------------------------+
* Note that for the sake of illustration, both `m` and `n` are assumed normalized (between 0 and 1).
* During runtime, it is taken into account that they are given in PPM units (between 0 and 1000000).
*/
library PoolCollectionWithdrawal {
using MathEx for uint256;
struct Output {
Sint256 p;
Sint256 q;
Sint256 r;
uint256 s;
uint256 t;
uint256 u;
uint256 v;
}
/**
* @dev returns `p`, `q`, `r`, `s`, `t`, `u` and `v` according to the current state:
* +-------------------+-----------------------------------------------------------+
* | `e > (b+c)/(1-n)` | bootstrap deficit or default deficit or arbitrage deficit |
* +-------------------+-----------------------------------------------------------+
* | `e < (b+c)` | bootstrap surplus or default surplus or arbitrage surplus |
* +-------------------+-----------------------------------------------------------+
* | otherwise | bootstrap surplus or default surplus |
* +-------------------+-----------------------------------------------------------+
*/
function calculateWithdrawalAmounts(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 c, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 w, // <= 2**128-1
uint256 m, // <= M == 1000000
uint256 n, // <= M == 1000000
uint256 x /// <= e <= 2**128-1
) internal pure returns (Output memory output) {
// given the restrictions above, everything below can be declared `unchecked`
if (
a > type(uint128).max ||
b > type(uint128).max ||
c > type(uint128).max ||
e > type(uint128).max ||
w > type(uint128).max ||
m > M ||
n > M ||
x > e
) {
revert PoolCollectionWithdrawalInputInvalid();
}
uint256 y = (x * (M - n)) / M;
if ((e * (M - n)) / M > b + c) {
uint256 f = (e * (M - n)) / M - (b + c);
uint256 g = e - (b + c);
if (isStable(b, c, e, x) && affordableDeficit(b, e, f, g, m, n, x)) {
output = arbitrageDeficit(a, b, e, f, m, x, y);
} else if (a > 0) {
output = defaultDeficit(a, b, c, e, y);
(output.t, output.u) = externalProtection(a, b, e, g, y, w);
} else {
output.s = (y * c) / e;
(output.t, output.u) = externalProtection(a, b, e, g, y, w);
}
} else {
uint256 f = MathEx.subMax0(b + c, e);
if (f > 0 && isStable(b, c, e, x) && affordableSurplus(b, e, f, m, n, x)) {
output = arbitrageSurplus(a, b, e, f, m, n, x, y);
} else if (a > 0) {
output = defaultSurplus(a, b, c, y);
} else {
output.s = y;
}
}
output.v = x - y;
}
/**
* @dev returns `x < e*c/(b+c)`
*/
function isStable(
uint256 b, // <= 2**128-1
uint256 c, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 x /// <= e <= 2**128-1
) private pure returns (bool) {
// given the restrictions above, everything below can be declared `unchecked`
return b * x < c * (e - x);
}
/**
* @dev returns `b*e*((e*(1-n)-b-c)*m+e*n) > (e*(1-n)-b-c)*x*(e-b-c)*(1-m)`
*/
function affordableDeficit(
uint256 b, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 f, // == e*(1-n)-b-c <= e <= 2**128-1
uint256 g, // == e-b-c <= e <= 2**128-1
uint256 m, // <= M == 1000000
uint256 n, // <= M == 1000000
uint256 x /// < e*c/(b+c) <= e <= 2**128-1
) private pure returns (bool) {
// given the restrictions above, everything below can be declared `unchecked`
Uint512 memory lhs = MathEx.mul512(b * e, f * m + e * n);
Uint512 memory rhs = MathEx.mul512(f * x, g * (M - m));
return MathEx.gt512(lhs, rhs);
}
/**
* @dev returns `b*e*((b+c-e)*m+e*n) > (b+c-e)*x*(b+c-e*(1-n))*(1-m)`
*/
function affordableSurplus(
uint256 b, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 f, // == b+c-e <= 2**129-2
uint256 m, // <= M == 1000000
uint256 n, // <= M == 1000000
uint256 x /// < e*c/(b+c) <= e <= 2**128-1
) private pure returns (bool) {
// given the restrictions above, everything below can be declared `unchecked`
Uint512 memory lhs = MathEx.mul512(b * e, (f * m + e * n) * M);
Uint512 memory rhs = MathEx.mul512(f * x, (f * M + e * n) * (M - m));
return MathEx.gt512(lhs, rhs); // `x < e*c/(b+c)` --> `f*x < e*c*(b+c-e)/(b+c) <= e*c <= 2**256-1`
}
/**
* @dev returns:
* `p = a*x*(e*(1-n)-b-c)*(1-m)/(b*e-x*(e*(1-n)-b-c)*(1-m))`
* `q = 0`
* `r = -x*(e*(1-n)-b-c)/e`
* `s = x*(1-n)`
*/
function arbitrageDeficit(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 f, // == e*(1-n)-b-c <= e <= 2**128-1
uint256 m, // <= M == 1000000
uint256 x, // <= e <= 2**128-1
uint256 y /// == x*(1-n) <= x <= e <= 2**128-1
) private pure returns (Output memory output) {
// given the restrictions above, everything below can be declared `unchecked`
uint256 i = f * (M - m);
uint256 j = mulSubMulDivF(b, e * M, x, i, 1);
output.p = MathEx.mulDivF(a * x, i, j).toPos256();
output.r = MathEx.mulDivF(x, f, e).toNeg256();
output.s = y;
}
/**
* @dev returns:
* `p = -a*x*(b+c-e*(1-n))/(b*e*(1-m)+x*(b+c-e*(1-n))*(1-m))`
* `q = 0`
* `r = x*(b+c-e*(1-n))/e`
* `s = x*(1-n)`
*/
function arbitrageSurplus(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 f, // == b+c-e <= 2**129-2
uint256 m, // <= M == 1000000
uint256 n, // <= M == 1000000
uint256 x, // <= e <= 2**128-1
uint256 y /// == x*(1-n) <= x <= e <= 2**128-1
) private pure returns (Output memory output) {
// given the restrictions above, everything below can be declared `unchecked`
uint256 i = f * M + e * n;
uint256 j = mulAddMulDivF(b, e * (M - m), x, i * (M - m), M);
output.p = MathEx.mulDivF(a * x, i, j).toNeg256();
output.r = MathEx.mulDivF(x, i, e * M).toPos256();
output.s = y;
}
/**
* @dev returns:
* `p = -a*z/(b*e)` where `z = max(x*(1-n)*b-c*(e-x*(1-n)),0)`
* `q = -a*z/(b*e)` where `z = max(x*(1-n)*b-c*(e-x*(1-n)),0)`
* `r = -z/e` where `z = max(x*(1-n)*b-c*(e-x*(1-n)),0)`
* `s = x*(1-n)*(b+c)/e`
*/
function defaultDeficit(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 c, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 y /// == x*(1-n) <= x <= e <= 2**128-1
) private pure returns (Output memory output) {
// given the restrictions above, everything below can be declared `unchecked`
uint256 z = MathEx.subMax0(y * b, c * (e - y));
output.p = MathEx.mulDivF(a, z, b * e).toNeg256();
output.q = output.p;
output.r = (z / e).toNeg256();
output.s = MathEx.mulDivF(y, b + c, e);
}
/**
* @dev returns:
* `p = -a*z/b` where `z = max(x*(1-n)-c,0)`
* `q = -a*z/b` where `z = max(x*(1-n)-c,0)`
* `r = -z` where `z = max(x*(1-n)-c,0)`
* `s = x*(1-n)`
*/
function defaultSurplus(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 c, // <= 2**128-1
uint256 y /// == x*(1-n) <= x <= e <= 2**128-1
) private pure returns (Output memory output) {
// given the restrictions above, everything below can be declared `unchecked`
uint256 z = MathEx.subMax0(y, c);
output.p = MathEx.mulDivF(a, z, b).toNeg256();
output.q = output.p;
output.r = z.toNeg256();
output.s = y;
}
/**
* @dev returns `t` and `u` according to the current state:
* +-----------------------+-------+---------------------------+-------------------+
* | x*(1-n)*(e-b-c)/e > w | a > 0 | t | u |
* +-----------------------+-------+---------------------------+-------------------+
* | true | true | a*(x*(1-n)*(e-b-c)/e-w)/b | w |
* +-----------------------+-------+---------------------------+-------------------+
* | true | false | 0 | w |
* +-----------------------+-------+---------------------------+-------------------+
* | false | true | 0 | x*(1-n)*(e-b-c)/e |
* +-----------------------+-------+---------------------------+-------------------+
* | false | false | 0 | x*(1-n)*(e-b-c)/e |
* +-----------------------+-------+---------------------------+-------------------+
*/
function externalProtection(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 g, // == e-b-c <= e <= 2**128-1
uint256 y, // == x*(1-n) <= x <= e <= 2**128-1
uint256 w /// <= 2**128-1
) private pure returns (uint256 t, uint256 u) {
// given the restrictions above, everything below can be declared `unchecked`
uint256 yg = y * g;
uint256 we = w * e;
if (yg > we) {
t = a > 0 ? MathEx.mulDivF(a, yg - we, b * e) : 0;
u = w;
} else {
t = 0;
u = yg / e;
}
}
/**
* @dev returns `a*b+x*y/z`
*/
function mulAddMulDivF(
uint256 a,
uint256 b,
uint256 x,
uint256 y,
uint256 z
) private pure returns (uint256) {
return a * b + MathEx.mulDivF(x, y, z);
}
/**
* @dev returns `a*b-x*y/z`
*/
function mulSubMulDivF(
uint256 a,
uint256 b,
uint256 x,
uint256 y,
uint256 z
) private pure returns (uint256) {
return a * b - MathEx.mulDivF(x, y, z);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IPoolToken } from "./IPoolToken.sol";
import { Token } from "../../token/Token.sol";
import { IVault } from "../../vaults/interfaces/IVault.sol";
// the BNT pool token manager role is required to access the BNT pool tokens
bytes32 constant ROLE_BNT_POOL_TOKEN_MANAGER = keccak256("ROLE_BNT_POOL_TOKEN_MANAGER");
// the BNT manager role is required to request the BNT pool to mint BNT
bytes32 constant ROLE_BNT_MANAGER = keccak256("ROLE_BNT_MANAGER");
// the vault manager role is required to request the BNT pool to burn BNT from the master vault
bytes32 constant ROLE_VAULT_MANAGER = keccak256("ROLE_VAULT_MANAGER");
// the funding manager role is required to request or renounce funding from the BNT pool
bytes32 constant ROLE_FUNDING_MANAGER = keccak256("ROLE_FUNDING_MANAGER");
/**
* @dev BNT Pool interface
*/
interface IBNTPool is IVault {
/**
* @dev returns the BNT pool token contract
*/
function poolToken() external view returns (IPoolToken);
/**
* @dev returns the total staked BNT balance in the network
*/
function stakedBalance() external view returns (uint256);
/**
* @dev returns the current funding of given pool
*/
function currentPoolFunding(Token pool) external view returns (uint256);
/**
* @dev returns the available BNT funding for a given pool
*/
function availableFunding(Token pool) external view returns (uint256);
/**
* @dev converts the specified pool token amount to the underlying BNT amount
*/
function poolTokenToUnderlying(uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev converts the specified underlying BNT amount to pool token amount
*/
function underlyingToPoolToken(uint256 bntAmount) external view returns (uint256);
/**
* @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
* amount
*/
function poolTokenAmountToBurn(uint256 bntAmountToDistribute) external view returns (uint256);
/**
* @dev mints BNT to the recipient
*
* requirements:
*
* - the caller must have the ROLE_BNT_MANAGER role
*/
function mint(address recipient, uint256 bntAmount) external;
/**
* @dev burns BNT from the vault
*
* requirements:
*
* - the caller must have the ROLE_VAULT_MANAGER role
*/
function burnFromVault(uint256 bntAmount) external;
/**
* @dev deposits BNT liquidity on behalf of a specific provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must be the network contract
* - BNT tokens must have been already deposited into the contract
*/
function depositFor(
bytes32 contextId,
address provider,
uint256 bntAmount,
bool isMigrating,
uint256 originalVBNTAmount
) external returns (uint256);
/**
* @dev withdraws BNT liquidity on behalf of a specific provider and returns the withdrawn BNT amount
*
* requirements:
*
* - the caller must be the network contract
* - VBNT token must have been already deposited into the contract
*/
function withdraw(
bytes32 contextId,
address provider,
uint256 poolTokenAmount
) external returns (uint256);
/**
* @dev returns the withdrawn BNT amount
*/
function withdrawalAmount(uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev requests BNT funding
*
* requirements:
*
* - the caller must have the ROLE_FUNDING_MANAGER role
* - the token must have been whitelisted
* - the request amount should be below the funding limit for a given pool
* - the average rate of the pool must not deviate too much from its spot rate
*/
function requestFunding(
bytes32 contextId,
Token pool,
uint256 bntAmount
) external;
/**
* @dev renounces BNT funding
*
* requirements:
*
* - the caller must have the ROLE_FUNDING_MANAGER role
* - the token must have been whitelisted
* - the average rate of the pool must not deviate too much from its spot rate
*/
function renounceFunding(
bytes32 contextId,
Token pool,
uint256 bntAmount
) external;
/**
* @dev notifies the pool of accrued fees
*
* requirements:
*
* - the caller must be the network contract
*/
function onFeesCollected(
Token pool,
uint256 feeAmount,
bool isTradeFee
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { Fraction112 } from "../../utility/FractionLibrary.sol";
import { Token } from "../../token/Token.sol";
import { IPoolToken } from "./IPoolToken.sol";
struct PoolLiquidity {
uint128 bntTradingLiquidity; // the BNT trading liquidity
uint128 baseTokenTradingLiquidity; // the base token trading liquidity
uint256 stakedBalance; // the staked balance
}
struct AverageRate {
uint32 blockNumber;
Fraction112 rate;
}
struct Pool {
IPoolToken poolToken; // the pool token of the pool
uint32 tradingFeePPM; // the trading fee (in units of PPM)
bool tradingEnabled; // whether trading is enabled
bool depositingEnabled; // whether depositing is enabled
AverageRate averageRate; // the recent average rate
uint256 depositLimit; // the deposit limit
PoolLiquidity liquidity; // the overall liquidity in the pool
}
struct WithdrawalAmounts {
uint256 totalAmount;
uint256 baseTokenAmount;
uint256 bntAmount;
}
// trading enabling/disabling reasons
uint8 constant TRADING_STATUS_UPDATE_DEFAULT = 0;
uint8 constant TRADING_STATUS_UPDATE_ADMIN = 1;
uint8 constant TRADING_STATUS_UPDATE_MIN_LIQUIDITY = 2;
struct TradeAmountAndFee {
uint256 amount; // the source/target amount (depending on the context) resulting from the trade
uint256 tradingFeeAmount; // the trading fee amount
uint256 networkFeeAmount; // the network fee amount (always in units of BNT)
}
/**
* @dev Pool Collection interface
*/
interface IPoolCollection is IVersioned {
/**
* @dev returns the type of the pool
*/
function poolType() external pure returns (uint16);
/**
* @dev returns the default trading fee (in units of PPM)
*/
function defaultTradingFeePPM() external view returns (uint32);
/**
* @dev returns all the pools which are managed by this pool collection
*/
function pools() external view returns (Token[] memory);
/**
* @dev returns the number of all the pools which are managed by this pool collection
*/
function poolCount() external view returns (uint256);
/**
* @dev returns whether a pool is valid
*/
function isPoolValid(Token pool) external view returns (bool);
/**
* @dev returns specific pool's data
*/
function poolData(Token pool) external view returns (Pool memory);
/**
* @dev returns the overall liquidity in the pool
*/
function poolLiquidity(Token pool) external view returns (PoolLiquidity memory);
/**
* @dev returns the pool token of the pool
*/
function poolToken(Token pool) external view returns (IPoolToken);
/**
* @dev converts the specified pool token amount to the underlying base token amount
*/
function poolTokenToUnderlying(Token pool, uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev converts the specified underlying base token amount to pool token amount
*/
function underlyingToPoolToken(Token pool, uint256 tokenAmount) external view returns (uint256);
/**
* @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
* amount
*/
function poolTokenAmountToBurn(
Token pool,
uint256 tokenAmountToDistribute,
uint256 protocolPoolTokenAmount
) external view returns (uint256);
/**
* @dev creates a new pool
*
* requirements:
*
* - the caller must be the network contract
* - the pool should have been whitelisted
* - the pool isn't already defined in the collection
*/
function createPool(Token token) external;
/**
* @dev deposits base token liquidity on behalf of a specific provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must be the network contract
* - assumes that the base token has been already deposited in the vault
*/
function depositFor(
bytes32 contextId,
address provider,
Token pool,
uint256 tokenAmount
) external returns (uint256);
/**
* @dev handles some of the withdrawal-related actions and returns the withdrawn base token amount
*
* requirements:
*
* - the caller must be the network contract
* - the caller must have approved the collection to transfer/burn the pool token amount on its behalf
*/
function withdraw(
bytes32 contextId,
address provider,
Token pool,
uint256 poolTokenAmount
) external returns (uint256);
/**
* @dev returns the amounts that would be returned if the position is currently withdrawn,
* along with the breakdown of the base token and the BNT compensation
*/
function withdrawalAmounts(Token pool, uint256 poolTokenAmount) external view returns (WithdrawalAmounts memory);
/**
* @dev performs a trade by providing the source amount and returns the target amount and the associated fee
*
* requirements:
*
* - the caller must be the network contract
*/
function tradeBySourceAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount
) external returns (TradeAmountAndFee memory);
/**
* @dev performs a trade by providing the target amount and returns the required source amount and the associated fee
*
* requirements:
*
* - the caller must be the network contract
*/
function tradeByTargetAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount
) external returns (TradeAmountAndFee memory);
/**
* @dev returns the output amount and fee when trading by providing the source amount
*/
function tradeOutputAndFeeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount
) external view returns (TradeAmountAndFee memory);
/**
* @dev returns the input amount and fee when trading by providing the target amount
*/
function tradeInputAndFeeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount
) external view returns (TradeAmountAndFee memory);
/**
* @dev notifies the pool of accrued fees
*
* requirements:
*
* - the caller must be the network contract
*/
function onFeesCollected(Token pool, uint256 feeAmount) external;
/**
* @dev migrates a pool to this pool collection
*
* requirements:
*
* - the caller must be the pool migrator contract
*/
function migratePoolIn(Token pool, Pool calldata data) external;
/**
* @dev migrates a pool from this pool collection
*
* requirements:
*
* - the caller must be the pool migrator contract
*/
function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Token } from "../../token/Token.sol";
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { IPoolCollection } from "./IPoolCollection.sol";
/**
* @dev Pool Migrator interface
*/
interface IPoolMigrator is IVersioned {
/**
* @dev migrates a pool and returns the new pool collection it exists in
*
* notes:
*
* - invalid or incompatible pools will be skipped gracefully
*
* requirements:
*
* - the caller must be the network contract
*/
function migratePool(Token pool) external returns (IPoolCollection);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol";
import { Token } from "../../token/Token.sol";
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { IOwned } from "../../utility/interfaces/IOwned.sol";
/**
* @dev Pool Token interface
*/
interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable {
/**
* @dev returns the address of the reserve token
*/
function reserveToken() external view returns (Token);
/**
* @dev increases the token supply and sends the new tokens to the given account
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function mint(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Token } from "../../token/Token.sol";
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { IPoolToken } from "./IPoolToken.sol";
/**
* @dev Pool Token Factory interface
*/
interface IPoolTokenFactory is IUpgradeable {
/**
* @dev returns the custom symbol override for a given reserve token
*/
function tokenSymbolOverride(Token token) external view returns (string memory);
/**
* @dev returns the custom decimals override for a given reserve token
*/
function tokenDecimalsOverride(Token token) external view returns (uint8);
/**
* @dev creates a pool token for the specified token
*/
function createPoolToken(Token token) external returns (IPoolToken);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/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.8.13;
/**
* @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions,
* but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract
*/
interface Token {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { SafeERC20Ex } from "./SafeERC20Ex.sol";
import { Token } from "./Token.sol";
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
/**
* @dev This library implements ERC20 and SafeERC20 utilities for both the native token and for ERC20 tokens
*/
library TokenLibrary {
using SafeERC20 for IERC20;
using SafeERC20Ex for IERC20;
error PermitUnsupported();
// the address that represents the native token reserve
address public constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// the symbol that represents the native token
string private constant NATIVE_TOKEN_SYMBOL = "ETH";
// the decimals for the native token
uint8 private constant NATIVE_TOKEN_DECIMALS = 18;
/**
* @dev returns whether the provided token represents an ERC20 or the native token reserve
*/
function isNative(Token token) internal pure returns (bool) {
return address(token) == NATIVE_TOKEN_ADDRESS;
}
/**
* @dev returns the symbol of the native token/ERC20 token
*/
function symbol(Token token) internal view returns (string memory) {
if (isNative(token)) {
return NATIVE_TOKEN_SYMBOL;
}
return toERC20(token).symbol();
}
/**
* @dev returns the decimals of the native token/ERC20 token
*/
function decimals(Token token) internal view returns (uint8) {
if (isNative(token)) {
return NATIVE_TOKEN_DECIMALS;
}
return toERC20(token).decimals();
}
/**
* @dev returns the balance of the native token/ERC20 token
*/
function balanceOf(Token token, address account) internal view returns (uint256) {
if (isNative(token)) {
return account.balance;
}
return toIERC20(token).balanceOf(account);
}
/**
* @dev transfers a specific amount of the native token/ERC20 token
*/
function safeTransfer(
Token token,
address to,
uint256 amount
) internal {
if (amount == 0) {
return;
}
if (isNative(token)) {
payable(to).transfer(amount);
} else {
toIERC20(token).safeTransfer(to, amount);
}
}
/**
* @dev transfers a specific amount of the native token/ERC20 token from a specific holder using the allowance mechanism
*
* note that the function does not perform any action if the native token is provided
*/
function safeTransferFrom(
Token token,
address from,
address to,
uint256 amount
) internal {
if (amount == 0 || isNative(token)) {
return;
}
toIERC20(token).safeTransferFrom(from, to, amount);
}
/**
* @dev approves a specific amount of the native token/ERC20 token from a specific holder
*
* note that the function does not perform any action if the native token is provided
*/
function safeApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).safeApprove(spender, amount);
}
/**
* @dev ensures that the spender has sufficient allowance
*
* note that the function does not perform any action if the native token is provided
*/
function ensureApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).ensureApprove(spender, amount);
}
/**
* @dev performs an EIP2612 permit
*/
function permit(
Token token,
address owner,
address spender,
uint256 tokenAmount,
uint256 deadline,
Signature memory signature
) internal {
if (isNative(token)) {
revert PermitUnsupported();
}
// permit the amount the owner is trying to deposit. Please note, that if the base token doesn't support
// EIP2612 permit - either this call or the inner safeTransferFrom will revert
IERC20Permit(address(token)).permit(
owner,
spender,
tokenAmount,
deadline,
signature.v,
signature.r,
signature.s
);
}
/**
* @dev compares between a token and another raw ERC20 token
*/
function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) {
return toIERC20(token) == erc20Token;
}
/**
* @dev utility function that converts an token to an IERC20
*/
function toIERC20(Token token) internal pure returns (IERC20) {
return IERC20(address(token));
}
/**
* @dev utility function that converts an token to an ERC20
*/
function toERC20(Token token) internal pure returns (ERC20) {
return ERC20(address(token));
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev burnable ERC20 interface
*/
interface IERC20Burnable {
/**
* @dev Destroys tokens from the caller.
*/
function burn(uint256 amount) external;
/**
* @dev Destroys tokens from a recipient, deducting from the caller's allowance
*
* requirements:
*
* - the caller must have allowance for recipient's tokens of at least the specified amount
*/
function burnFrom(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev this contract abstracts the block number in order to allow for more flexible control in tests
*/
contract BlockNumber {
/**
* @dev returns the current block-number
*/
function _blockNumber() internal view virtual returns (uint32) {
return uint32(block.number);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
uint32 constant PPM_RESOLUTION = 1000000;
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
struct Fraction {
uint256 n;
uint256 d;
}
struct Fraction112 {
uint112 n;
uint112 d;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Fraction, Fraction112 } from "./Fraction.sol";
import { MathEx } from "./MathEx.sol";
// solhint-disable-next-line func-visibility
function zeroFraction() pure returns (Fraction memory) {
return Fraction({ n: 0, d: 1 });
}
// solhint-disable-next-line func-visibility
function zeroFraction112() pure returns (Fraction112 memory) {
return Fraction112({ n: 0, d: 1 });
}
/**
* @dev this library provides a set of fraction operations
*/
library FractionLibrary {
/**
* @dev returns whether a standard fraction is valid
*/
function isValid(Fraction memory fraction) internal pure returns (bool) {
return fraction.d != 0;
}
/**
* @dev returns whether a standard fraction is positive
*/
function isPositive(Fraction memory fraction) internal pure returns (bool) {
return isValid(fraction) && fraction.n != 0;
}
/**
* @dev returns whether a 112-bit fraction is valid
*/
function isValid(Fraction112 memory fraction) internal pure returns (bool) {
return fraction.d != 0;
}
/**
* @dev returns whether a 112-bit fraction is positive
*/
function isPositive(Fraction112 memory fraction) internal pure returns (bool) {
return isValid(fraction) && fraction.n != 0;
}
/**
* @dev reduces a standard fraction to a 112-bit fraction
*/
function toFraction112(Fraction memory fraction) internal pure returns (Fraction112 memory) {
Fraction memory reducedFraction = MathEx.reducedFraction(fraction, type(uint112).max);
return Fraction112({ n: uint112(reducedFraction.n), d: uint112(reducedFraction.d) });
}
/**
* @dev expands a 112-bit fraction to a standard fraction
*/
function fromFraction112(Fraction112 memory fraction) internal pure returns (Fraction memory) {
return Fraction({ n: fraction.n, d: fraction.d });
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { Fraction } from "./Fraction.sol";
import { PPM_RESOLUTION } from "./Constants.sol";
uint256 constant ONE = 0x80000000000000000000000000000000;
uint256 constant LN2 = 0x58b90bfbe8e7bcd5e4f1d9cc01f97b57;
struct Uint512 {
uint256 hi; // 256 most significant bits
uint256 lo; // 256 least significant bits
}
struct Sint256 {
uint256 value;
bool isNeg;
}
/**
* @dev this library provides a set of complex math operations
*/
library MathEx {
error Overflow();
/**
* @dev returns `2 ^ f` by calculating `e ^ (f * ln(2))`, where `e` is Euler's number:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function exp2(Fraction memory f) internal pure returns (Fraction memory) {
uint256 x = MathEx.mulDivF(LN2, f.n, f.d);
uint256 y;
uint256 z;
uint256 n;
if (x >= (ONE << 4)) {
revert Overflow();
}
unchecked {
z = y = x % (ONE >> 3); // get the input modulo 2^(-3)
z = (z * y) / ONE;
n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = (z * y) / ONE;
n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = (z * y) / ONE;
n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = (z * y) / ONE;
n += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = (z * y) / ONE;
n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = (z * y) / ONE;
n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = (z * y) / ONE;
n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = (z * y) / ONE;
n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = (z * y) / ONE;
n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = (z * y) / ONE;
n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = (z * y) / ONE;
n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = (z * y) / ONE;
n += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = (z * y) / ONE;
n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = (z * y) / ONE;
n += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = (z * y) / ONE;
n += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = (z * y) / ONE;
n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = (z * y) / ONE;
n += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = (z * y) / ONE;
n += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = (z * y) / ONE;
n += z * 0x0000000000000001; // add y^20 * (20! / 20!)
n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & (ONE >> 3)) != 0)
n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & (ONE >> 2)) != 0)
n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & (ONE >> 1)) != 0)
n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & (ONE << 0)) != 0)
n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & (ONE << 1)) != 0)
n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & (ONE << 2)) != 0)
n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & (ONE << 3)) != 0)
n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
}
return Fraction({ n: n, d: ONE });
}
/**
* @dev returns a fraction with reduced components
*/
function reducedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) {
uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max);
return Fraction({ n: fraction.n / scale, d: fraction.d / scale });
}
/**
* @dev returns the weighted average of two fractions
*/
function weightedAverage(
Fraction memory fraction1,
Fraction memory fraction2,
uint256 weight1,
uint256 weight2
) internal pure returns (Fraction memory) {
return
Fraction({
n: fraction1.n * fraction2.d * weight1 + fraction1.d * fraction2.n * weight2,
d: fraction1.d * fraction2.d * (weight1 + weight2)
});
}
/**
* @dev returns whether or not the deviation of an offset sample from a base sample is within a permitted range
* for example, if the maximum permitted deviation is 5%, then evaluate `95% * base <= offset <= 105% * base`
*/
function isInRange(
Fraction memory baseSample,
Fraction memory offsetSample,
uint32 maxDeviationPPM
) internal pure returns (bool) {
Uint512 memory min = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION - maxDeviationPPM));
Uint512 memory mid = mul512(baseSample.d, offsetSample.n * PPM_RESOLUTION);
Uint512 memory max = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION + maxDeviationPPM));
return lte512(min, mid) && lte512(mid, max);
}
/**
* @dev returns an `Sint256` positive representation of an unsigned integer
*/
function toPos256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: false });
}
/**
* @dev returns an `Sint256` negative representation of an unsigned integer
*/
function toNeg256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: true });
}
/**
* @dev returns the largest integer smaller than or equal to `x * y / z`
*/
function mulDivF(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
Uint512 memory xy = mul512(x, y);
// if `x * y < 2 ^ 256`
if (xy.hi == 0) {
return xy.lo / z;
}
// assert `x * y / z < 2 ^ 256`
if (xy.hi >= z) {
revert Overflow();
}
uint256 m = _mulMod(x, y, z); // `m = x * y % z`
Uint512 memory n = _sub512(xy, m); // `n = x * y - m` hence `n / z = floor(x * y / z)`
// if `n < 2 ^ 256`
if (n.hi == 0) {
return n.lo / z;
}
uint256 p = _unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by
uint256 q = _div512(n, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p`
uint256 r = _inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256`
return _unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z`
}
/**
* @dev returns the smallest integer larger than or equal to `x * y / z`
*/
function mulDivC(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
uint256 w = mulDivF(x, y, z);
if (_mulMod(x, y, z) > 0) {
if (w >= type(uint256).max) {
revert Overflow();
}
return w + 1;
}
return w;
}
/**
* @dev returns the maximum of `n1 - n2` and 0
*/
function subMax0(uint256 n1, uint256 n2) internal pure returns (uint256) {
return n1 > n2 ? n1 - n2 : 0;
}
/**
* @dev returns the value of `x > y`
*/
function gt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi > y.hi || (x.hi == y.hi && x.lo > y.lo);
}
/**
* @dev returns the value of `x < y`
*/
function lt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo);
}
/**
* @dev returns the value of `x >= y`
*/
function gte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !lt512(x, y);
}
/**
* @dev returns the value of `x <= y`
*/
function lte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !gt512(x, y);
}
/**
* @dev returns the value of `x * y`
*/
function mul512(uint256 x, uint256 y) internal pure returns (Uint512 memory) {
uint256 p = _mulModMax(x, y);
uint256 q = _unsafeMul(x, y);
if (p >= q) {
return Uint512({ hi: p - q, lo: q });
}
return Uint512({ hi: _unsafeSub(p, q) - 1, lo: q });
}
/**
* @dev returns the value of `x - y`, given that `x >= y`
*/
function _sub512(Uint512 memory x, uint256 y) private pure returns (Uint512 memory) {
if (x.lo >= y) {
return Uint512({ hi: x.hi, lo: x.lo - y });
}
return Uint512({ hi: x.hi - 1, lo: _unsafeSub(x.lo, y) });
}
/**
* @dev returns the value of `x / pow2n`, given that `x` is divisible by `pow2n`
*/
function _div512(Uint512 memory x, uint256 pow2n) private pure returns (uint256) {
uint256 pow2nInv = _unsafeAdd(_unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)`
return _unsafeMul(x.hi, pow2nInv) | (x.lo / pow2n); // `(x.hi << (256 - n)) | (x.lo >> n)`
}
/**
* @dev returns the inverse of `d` modulo `2 ^ 256`, given that `d` is congruent to `1` modulo `2`
*/
function _inv256(uint256 d) private pure returns (uint256) {
// approximate the root of `f(x) = 1 / x - d` using the newtonβraphson convergence method
uint256 x = 1;
for (uint256 i = 0; i < 8; i++) {
x = _unsafeMul(x, _unsafeSub(2, _unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256`
}
return x;
}
/**
* @dev returns `(x + y) % 2 ^ 256`
*/
function _unsafeAdd(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x + y;
}
}
/**
* @dev returns `(x - y) % 2 ^ 256`
*/
function _unsafeSub(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x - y;
}
}
/**
* @dev returns `(x * y) % 2 ^ 256`
*/
function _unsafeMul(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x * y;
}
}
/**
* @dev returns `x * y % (2 ^ 256 - 1)`
*/
function _mulModMax(uint256 x, uint256 y) private pure returns (uint256) {
return mulmod(x, y, type(uint256).max);
}
/**
* @dev returns `x * y % z`
*/
function _mulMod(
uint256 x,
uint256 y,
uint256 z
) private pure returns (uint256) {
return mulmod(x, y, z);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IOwned } from "./interfaces/IOwned.sol";
import { AccessDenied } from "./Utils.sol";
/**
* @dev this contract provides support and utilities for contract ownership
*/
abstract contract Owned is IOwned {
error SameOwner();
address private _owner;
address private _newOwner;
/**
* @dev triggered when the owner is updated
*/
event OwnerUpdate(address indexed prevOwner, address indexed newOwner);
// solhint-disable func-name-mixedcase
/**
* @dev initializes the contract
*/
constructor() {
_transferOwnership(msg.sender);
}
// solhint-enable func-name-mixedcase
// allows execution by the owner only
modifier onlyOwner() {
_onlyOwner();
_;
}
// error message binary size optimization
function _onlyOwner() private view {
if (msg.sender != _owner) {
revert AccessDenied();
}
}
/**
* @inheritdoc IOwned
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @inheritdoc IOwned
*/
function transferOwnership(address ownerCandidate) public virtual onlyOwner {
if (ownerCandidate == _owner) {
revert SameOwner();
}
_newOwner = ownerCandidate;
}
/**
* @inheritdoc IOwned
*/
function acceptOwnership() public virtual {
if (msg.sender != _newOwner) {
revert AccessDenied();
}
_transferOwnership(_newOwner);
}
/**
* @dev returns the address of the new owner candidate
*/
function newOwner() external view returns (address) {
return _newOwner;
}
/**
* @dev sets the new owner internally
*/
function _transferOwnership(address ownerCandidate) private {
address prevOwner = _owner;
_owner = ownerCandidate;
_newOwner = address(0);
emit OwnerUpdate({ prevOwner: prevOwner, newOwner: ownerCandidate });
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { PPM_RESOLUTION } from "./Constants.sol";
error AccessDenied();
error AlreadyExists();
error DoesNotExist();
error InvalidAddress();
error InvalidExternalAddress();
error InvalidFee();
error InvalidPool();
error InvalidPoolCollection();
error InvalidStakedBalance();
error InvalidToken();
error InvalidType();
error InvalidParam();
error NotEmpty();
error NotPayable();
error ZeroValue();
/**
* @dev common utilities
*/
contract Utils {
// allows execution by the caller only
modifier only(address caller) {
_only(caller);
_;
}
function _only(address caller) internal view {
if (msg.sender != caller) {
revert AccessDenied();
}
}
// 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 {
if (value == 0) {
revert ZeroValue();
}
}
// 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 {
if (addr == address(0)) {
revert InvalidAddress();
}
}
// 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 {
if (addr == address(0) || addr == address(this)) {
revert InvalidExternalAddress();
}
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
if (fee > PPM_RESOLUTION) {
revert InvalidFee();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev Owned interface
*/
interface IOwned {
/**
* @dev returns the address of the current owner
*/
function owner() external view returns (address);
/**
* @dev allows transferring the contract ownership
*
* requirements:
*
* - the caller must be the owner of the contract
* - the new owner still needs to accept the transfer
*/
function transferOwnership(address ownerCandidate) external;
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVersioned } from "./IVersioned.sol";
import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol";
/**
* @dev this is the common interface for upgradeable contracts
*/
interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev an interface for a versioned contract
*/
interface IVersioned {
function version() external view returns (uint16);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVault } from "./IVault.sol";
interface IExternalProtectionVault is IVault {}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVault } from "./IVault.sol";
interface IMasterVault is IVault {}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
// the asset manager role is required to access all the funds
bytes32 constant ROLE_ASSET_MANAGER = keccak256("ROLE_ASSET_MANAGER");
interface IVault is IUpgradeable {
/**
* @dev triggered when tokens have been withdrawn from the vault
*/
event FundsWithdrawn(Token indexed token, address indexed caller, address indexed target, uint256 amount);
/**
* @dev triggered when tokens have been burned from the vault
*/
event FundsBurned(Token indexed token, address indexed caller, uint256 amount);
/**
* @dev tells whether the vault accepts native token deposits
*/
function isPayable() external view returns (bool);
/**
* @dev withdraws funds held by the contract and sends them to an account
*/
function withdrawFunds(
Token token,
address payable target,
uint256 amount
) external;
/**
* @dev burns funds held by the contract
*/
function burn(Token token, uint256 amount) external;
} | sets the deposit limit of a given pool requirements: - the caller must be the owner of the contract/ | function setDepositLimit(Token pool, uint256 newDepositLimit) external onlyOwner {
Pool storage data = _poolStorage(pool);
uint256 prevDepositLimit = data.depositLimit;
if (prevDepositLimit == newDepositLimit) {
return;
}
data.depositLimit = newDepositLimit;
}
| 10,394,349 |
// SPDX-License-Identifier: MIT
pragma solidity 0.5.16;
import "./SafeMath.sol";
import "./Token.sol";
/// @title ΠΠΎΠ½ΡΡΠ°ΠΊΡ ICO
contract TokenCrowdSale {
using SafeMath for uint256;
address payable private owner; /// Π°Π΄ΡΠ΅Ρ Π²Π»Π°Π΄Π΅Π»ΡΡΠ°
uint256 private _openingTime; /// Π²ΡΠ΅ΠΌΡ ΠΎΡΠΊΡΡΡΠΈΡ ICO (Unix Timestamp)
uint256 private _closingTime; /// Π²ΡΠ΅ΠΌΡ Π·Π°ΠΊΡΡΡΠΈΡ ICO (Unix Timestamp)
/// @notice Π²ΠΊΠ»Π°Π΄ Π² ICO
mapping(address => uint256) private contributions;
Token private token; /// ΡΠ°ΠΌ ΡΠΎΠΊΠ΅Π½
uint256 private _rate; /// Π‘ΠΊΠΎΠ»ΡΠΊΠΎ Π΅Π΄ΠΈΠ½ΠΈΡ ΡΠΎΠΊΠ΅Π½Π° Π²ΠΊΠ»Π°Π΄ΡΠΈΠΊ ΠΏΠΎΠ»ΡΡΠΈΡ Π·Π° 1 wei
uint256 private _softCap; /// Π½ΠΈΠΆΠ½ΠΈΠΉ ΠΏΠΎΡΠΎΠ»ΠΎΠΊ Π΄Π»Ρ ΡΡΠΏΠ΅ΡΠ½ΠΎΠ³ΠΎ ICO (Π² wei)
uint256 private _hardCap; /// Π²Π΅ΡΡ
Π½ΠΈΠΉ ΠΏΠΎΡΠΎΠ»ΠΎΠΊ (Π² wei)
uint256 private _weiRaised; /// ΡΠΈΡΠ»ΠΎ ΡΠΎΠ±ΡΠ°Π½Π½ΡΡ
ΡΡΠ΅Π΄ΡΡΠ² (Π² wei)
bool private _allowRefunds = false; /// ΠΏΠ΅ΡΠ΅ΠΌΠ΅Π½Π½Π°Ρ Π΄Π»Ρ Π²ΠΎΠ·Π²ΡΠ°ΡΠ° ΡΡΠ΅Π΄ΡΡΠ² Π² ΡΠ»ΡΡΠ°Π΅ Π½Π΅ΡΡΠΏΠ΅ΡΠ½ΠΎΠ³ΠΎ ICO
modifier onlyWhileOpen {
require(block.timestamp >= _openingTime && block.timestamp <= _closingTime);
_;
}
/// @notice ΠΠΎΠ»ΡΡΠΈΡΡ ΠΈΠ½ΡΠΎΡΠΌΠ°ΡΠΈΡ ΠΎ ΡΠΎΠΌ, Π·Π°ΠΊΡΡΡ Π»ΠΈ ICO
function hasClosed() public view returns (bool) {
return block.timestamp > _closingTime;
}
/// @notice ΠΠΎΠ»ΡΡΠΈΡΡ ΠΈΠ½ΡΠΎΡΠΌΠ°ΡΠΈΡ ΠΎ ΡΠΎΠΌ, ΠΎΡΠΊΡΡΡ Π»ΠΈ ICO
function hasOpen() public view returns(bool) {
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
constructor(Token _token, uint256 rate_, uint256 softCap_, uint256 hardCap_, uint256 openingTime_, uint256 closingTime_) public {
_rate = rate_;
token = _token;
_softCap = softCap_;
_hardCap = hardCap_;
owner = msg.sender;
_openingTime = openingTime_;
_closingTime = closingTime_;
}
/// @notice ΠΠΎΠ»ΡΡΠΈΡΡ Π½ΠΈΠΆΠ½ΠΈΠΉ Π³ΡΠ°Π½ΠΈΡΡ Π΄Π»Ρ ΡΡΠΏΠ΅ΡΠ½ΠΎΠ³ΠΎ ICO
function softCap() public view returns(uint256) {
return _softCap;
}
/// @notice ΠΠΎΠ»ΡΡΠΈΡΡ Π²Π΅ΡΡ
Π½ΡΡ Π³ΡΠ°Π½ΠΈΡΡ ΡΠ±ΠΎΡΠΎΠ²
function hardCap() public view returns(uint256) {
return _hardCap;
}
/// @notice ΠΠΎΠ»ΡΡΠΈΡΡ Π²ΡΠ΅ΠΌΡ ΠΎΡΠΊΡΡΡΠΈΡ ICO
function openingTime() public view returns(uint256) {
return _openingTime;
}
/// @notice ΠΠΎΠ»ΡΡΠΈΡΡ Π²ΡΠ΅ΠΌΡ Π·Π°ΠΊΡΡΡΠΈΡ ICO
function closingTime() public view returns(uint256) {
return _closingTime;
}
/// @notice ΠΠΎΠ»ΡΡΠΈΡΡ Π²ΠΊΠ»Π°Π΄ Π² ICO
/// @param _investor Π°Π΄ΡΠ΅Ρ ΠΈΠ½Π²Π΅ΡΡΠΎΡΠ°
function contribution(address _investor) public view returns(uint256) {
return contributions[_investor];
}
/// @notice ΠΠΎΠ»ΡΡΠΈΡΡ ΡΠΊΠΎΠ»ΡΠΊΠΎ Π΅Π΄ΠΈΠ½ΠΈΡ ΡΠΎΠΊΠ΅Π½Π° Π²ΠΊΠ»Π°Π΄ΡΠΈΠΊ ΠΏΠΎΠ»ΡΡΠΈΡ Π·Π° 1 wei
function rate() public view returns(uint256) {
return _rate;
}
/// @notice ΠΠΎΠ»ΡΡΠΈΡΡ ΡΠΈΡΠ»ΠΎ ΡΠΎΠ±ΡΠ°Π½Π½ΡΡ
ΡΡΠ΅Π΄ΡΡΠ² (Π² wei)
function weiRased() public view returns(uint256) {
return _weiRaised;
}
/// @notice ΠΠΎΠ»ΡΡΠΈΡΡ ΠΈΠ½ΡΠΎΡΠΌΠ°ΡΠΈΡ ΠΎ ΡΠ°Π·ΡΠ΅ΡΠ΅Π½ΠΈΠΈ Π½Π° Π²ΡΠ²ΠΎΠ΄ ΡΡΠ΅Π΄ΡΡΠ² (ΡΠ»ΡΡΠ°ΠΉ Π½Π΅ΡΡΠΏΠ΅ΡΠ½ΠΎΠ³ΠΎ ICO)
function allowRefunds() public view returns(bool) {
return _allowRefunds;
}
/// @notice Π€ΡΠ½ΠΊΡΠΈΡ Π΄Π»Ρ ΠΏΡΠΈΠ΅ΠΌΠ° ΡΡΠ΅Π΄ΡΡΠ²
function() external payable {
buyTokens(msg.sender);
}
/// @notice ΠΡΠΏΠΈΡΡ ΡΠΎΠΊΠ΅Π½
/// @param _beneficiary Π°Π΄ΡΠ΅Ρ Π±Π΅Π½ΠΈΡΠΈΡΠΈΠ°ΡΠ° (ΠΊΠΎΠΌΡ ΠΊΡΠΏΠ»Π΅Π½Π½ΡΠ΅ ΡΠΎΠΊΠ΅Π½Ρ ΠΏΠ΅ΡΠ΅Π²Π΅Π΄ΡΡΡΡ)
function buyTokens(address _beneficiary) onlyWhileOpen public payable returns (bool success) {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
require(_weiRaised.add(weiAmount) <= _hardCap, "The ceiling has already been reached");
// update state
_weiRaised = _weiRaised.add(weiAmount);
contributions[msg.sender] = contributions[msg.sender].add(msg.value);
_processPurchase(_beneficiary, tokens);
return true;
}
/// @notice ΠΠ°Π»ΠΈΠ΄Π°ΡΠΈΡ Π΄Π°Π½Π½ΡΡ
Π΄Π»Ρ ΠΏΠΎΠΊΡΠΏΠΊΠΈ
function _preValidatePurchase(address _beneficiary,uint256 _weiAmount) internal pure {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/// @notice ΠΠΎΡΡΠ°Π²ΠΊΠ° ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π±Π΅Π½ΠΈΡΠΈΡΠΈΠ°ΡΡ
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.mint(_beneficiary, _tokenAmount);
}
/// @notice ΠΠ½ΡΡΡΠ΅Π½Π½ΡΡ ΡΡΠ½ΠΊΡΠΈΡ ΠΏΡΠΎΠ΄ΠΎΠ»ΠΆΠ΅Π½ΠΈΡ ΠΏΡΠΎΡΠ΅ΡΡΠ° ΠΏΠΎΠΊΡΠΏΠΊΠΈ ΡΠΎΠΊΠ΅Π½Π°
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/// @notice ΠΠΎΠ»ΡΡΠΈΡΡ ΡΠΈΡΠ»ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ², ΡΠΎΠΎΡΠ²Π΅ΡΡΡΠ²ΡΡΡΠΈΡ
ΡΡΠΌΠΌΠ΅ (Π² wei)
/// @param _weiAmount ΡΡΠΌΠΌΠ° Π² wei
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(_rate);
}
/// @notice Π Π°Π·ΡΠ΅ΡΠΈΡΡ Π²ΡΠ²ΠΎΠ΄ ΡΡΠ΅Π΄ΡΡΠ² (ICO Π½Π΅ΡΡΠΏΠ΅ΡΠ΅Π½)
function enableRefunds() private {
require(msg.sender == owner);
_allowRefunds = true;
}
/// @notice ΠΡΠ²ΠΎΠ΄ ΡΡΠ΅Π΄ΡΡΠ² Ρ ICO (ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΠ΅Π»Ρ ΡΠ°ΠΌ Π²ΡΠ·ΡΠ²Π°Π΅Ρ ΡΡΠ½ΠΊΡΠΈΡ)
function refund() public returns (bool success) {
require(allowRefunds(), 'Refunds is not allowed, ICO is in progress');
uint amount = contributions[msg.sender];
if (amount > 0) {
// It is important to set this to zero because the recipient
// can call this function again as part of the receiving call
// before `send` returns.
contributions[msg.sender] = 0;
if (!msg.sender.send(amount)) {
// No need to call throw here, just reset the amount owing
contributions[msg.sender] = amount;
return false;
}
}
return true;
}
/// @notice ΠΠ°ΠΊΡΡΡΠΈΠ΅ ICO
function finalization() public {
require(msg.sender == owner, "Only owner can finalize ICO");
require(hasClosed(), "Crowdsale is still open");
if (goalReached()) {
token.unpause_token();
token.finishMint();
owner.transfer(_weiRaised);
} else {
enableRefunds();
token.finishMint();
}
}
/// @notice ΠΡΠΎΠ²Π΅ΡΠΊΠ° Π΄ΠΎΡΡΠΈΠ³Π½ΡΡΠ° Π»ΠΈ ΡΠ΅Π»Ρ
function goalReached() public view returns (bool) {
return _weiRaised >= _softCap;
}
} | ΠΠΎΠ»ΡΡΠΈΡΡ ΠΈΠ½ΡΠΎΡΠΌΠ°ΡΠΈΡ ΠΎ ΡΠ°Π·ΡΠ΅ΡΠ΅Π½ΠΈΠΈ Π½Π° Π²ΡΠ²ΠΎΠ΄ ΡΡΠ΅Π΄ΡΡΠ² (ΡΠ»ΡΡΠ°ΠΉ Π½Π΅ΡΡΠΏΠ΅ΡΠ½ΠΎΠ³ΠΎ ICO) | function allowRefunds() public view returns(bool) {
return _allowRefunds;
}
| 975,312 |
./full_match/97/0xe00aedd1F593B82429ea304A29b947d1FdF8Daba/sources/project_/contracts/BakaCoin.sol | Transfer many address for airdrop/ | function transferMany(address[] memory to, uint256[] memory amount) public {
for (uint256 i; i < to.length; i++) {
super._transfer(_msgSender(), address(to[i]), amount[i]);
}
}
| 3,268,291 |
./full_match/1/0x0439e60F02a8900a951603950d8D4527f400C3f1/sources/contracts/MetaBridge.sol | Unpauses the contract to make the bridge function callable./ | function unpauseBridge() external onlyOwner {
_unpause();
}
| 17,185,298 |
pragma solidity ^0.5.0;
// import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "@nomiclabs/buidler/console.sol";
import "./LBCR.sol";
import "./UserProxy.sol";
import "./UserProxyFactory.sol";
import "./ILBCR.sol";
/// @title Registers users, protocols, aggregates reputation
contract WebOfTrust {
address constant aETHAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UserProxyFactory userProxyFactory;
LBCR[] lbcrs;
mapping (address => address) protocolToLBCR;
mapping (address => address) protocolToProxy;
mapping (address => bool) protocolProxy;
uint agentFactorDecimals;
constructor() public {
userProxyFactory = new UserProxyFactory(address(this));
agentFactorDecimals = 3;
}
function() external payable {
console.log("reached the fallback");
}
/// @notice Sign up with Byzantic as a user
function registerAgent() external {
userProxyFactory.registerAgent(msg.sender);
}
/// @notice Check if agent has signed up with Byzantic
/// @param agent The address of `msg.sender` when calling `registerAgent()`
/// @return isAgentRegistered boolean value representing the membership of the agent in Byzantic
function isAgentRegistered(address agent) public view returns (bool) {
return userProxyFactory.isAgentRegistered(agent);
}
/// @notice Integrate your protocol with Byzantic
/// @dev You need to deploy a Proxy contract for your protocol to integrate with Byzantic.
/// After calling `addProtocolIntegration`, you need to call `getProtocolLBCR` and configure your LBCR.
/// @param protocolAddress The address of the contract in your protocol you want to integrate with Byzantic.
/// @param protocolProxyAddress The address of the proxy to your contract. Written in the same style as the `SimpleLendingProxy` example contract.
function addProtocolIntegration(address protocolAddress, address protocolProxyAddress) external {
require(protocolToLBCR[protocolAddress] == address(0), "protocol has already been added");
LBCR lbcr = new LBCR();
protocolToLBCR[protocolAddress] = address(lbcr);
lbcr.addAuthorisedContract(address(userProxyFactory));
lbcr.addAuthorisedContract(msg.sender);
lbcrs.push(lbcr);
userProxyFactory.addLBCR(address(lbcr));
protocolToProxy[protocolAddress] = protocolProxyAddress;
protocolProxy[protocolProxyAddress] = true;
}
/// @return userProxyFactoryAddress The address of the UserProxyFactory contract
function getUserProxyFactoryAddress() public view returns (address) {
return address(userProxyFactory);
}
/// @return LBCR The address of the LBCR contract of a given protocol
function getProtocolLBCR(address protocolAddress) public view returns (address) {
return protocolToLBCR[protocolAddress];
}
/// @notice Record a user action into the LBCR, to update their score
/// @dev The `require` statement replaces a modifier that prevents unauthorised calls
/// @param protocolAddress The address of the contract in your protocol you want to integrate with Byzantic.
/// @param agent The address of the user whose reputation is being updated in the LBCR
/// @param action The action that the user has performed and is being rewarded / punished for.
function updateLBCR(address protocolAddress, address agent, uint256 action) public {
address proxyAddress = protocolToProxy[protocolAddress];
require(
proxyAddress == msg.sender,
"caller is either not a registered protocol or not the proxy of the destination protocol"
);
LBCR lbcr = LBCR(protocolToLBCR[protocolAddress]);
lbcr.update(agent, action);
}
/// @notice Uses information from all LBCRs and the subjective measures
/// of compatibility between them to compute how much collateral a
/// user should pay.
/// @param agent The address of the user whose reputation is being computed
/// @param protocol Address of the protocol with respect to which the reputation is being computed.
/// @return DiscountedCollateral - User reputation, expressed as the percentage of collateral they need to pay.
/// A return value of 900 means the agent only needs
/// to pay 90% of the normally required collateral (so the result needs to be divided by 10^3).
/// If the agent has not signed up with Byzantic, they need to pay the full collateral (100%)
function getAggregateAgentFactorForProtocol(address agent, address protocol) external view returns (uint256) {
uint agentFactorSum = 0;
uint agentFactorDenominator = 0;
address LBCRAddress = protocolToLBCR[protocol];
for(uint i = 0; i < lbcrs.length; i ++) {
LBCR lbcr = lbcrs[i];
if(lbcr.getInteractionCount(agent) > 0) {
agentFactorSum += (lbcr.getAgentFactor(agent) * ILBCR(LBCRAddress).getCompatibilityScoreWith(address(lbcr)));
agentFactorDenominator += ILBCR(LBCRAddress).getCompatibilityScoreWith(address(lbcr));
}
}
if(agentFactorDenominator > 0) {
return agentFactorSum / agentFactorDenominator;
}
// agent has not signed up with Byzantic
return 1000;
}
/// @notice For each of the LBCRs in Byzantic, if the round has elapsed, users will be curated into layers according to their score
function curateLBCRs() public {
for(uint i = 0; i < lbcrs.length; i++) {
lbcrs[i].curateIfRoundEnded();
}
}
/// @return agentFactorDecimals Number of decimals used to express the aggregate agent factor returned by `getAggregateAgentFactorForProtocol()`
function getAgentFactorDecimals() external view returns (uint) {
return agentFactorDecimals;
}
function isProtocolProxy(address addr) external returns (bool) {
return protocolProxy[addr];
}
function getProtocolProxy(address addr) external returns (address) {
return protocolToProxy[addr];
}
} | For each of the LBCRs in Byzantic, if the round has elapsed, users will be curated into layers according to their score | function curateLBCRs() public {
for(uint i = 0; i < lbcrs.length; i++) {
lbcrs[i].curateIfRoundEnded();
}
}
| 2,512,824 |
pragma solidity ^0.6.0;
import "../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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
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;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
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 use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been 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) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.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 AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
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());
}
}
uint256[49] private __gap;
}
pragma solidity ^0.6.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);
}
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);
}
}
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;
}
}
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;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
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;
/**
* @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;
import "../GSN/Context.sol";
import "../Initializable.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 PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @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.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_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());
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If 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].
*/
contract ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// 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() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
// solhint-disable
// Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/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**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**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);
}
}
}
// SPDX-License-Identifier: MIT
// Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IERC20withDec.sol";
interface ICUSDCContract is IERC20withDec {
/*** User Interface ***/
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function balanceOfUnderlying(address owner) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
/*** Admin Functions ***/
function _addReserves(uint256 addAmount) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract ICreditDesk {
uint256 public totalWritedowns;
uint256 public totalLoansOutstanding;
function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual;
function drawdown(address creditLineAddress, uint256 amount) external virtual;
function pay(address creditLineAddress, uint256 amount) external virtual;
function assessCreditLine(address creditLineAddress) external virtual;
function applyPayment(address creditLineAddress, uint256 amount) external virtual;
function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface ICreditLine {
function borrower() external view returns (address);
function limit() external view returns (uint256);
function interestApr() external view returns (uint256);
function paymentPeriodInDays() external view returns (uint256);
function termInDays() external view returns (uint256);
function lateFeeApr() external view returns (uint256);
// Accounting variables
function balance() external view returns (uint256);
function interestOwed() external view returns (uint256);
function principalOwed() external view returns (uint256);
function termEndTime() external view returns (uint256);
function nextDueTime() external view returns (uint256);
function interestAccruedAsOf() external view returns (uint256);
function lastFullPaymentTime() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
/*
Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's.
*/
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20withDec is IERC20 {
/**
* @dev Returns the number of decimals used for the token
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IERC20withDec.sol";
interface IFidu is IERC20withDec {
function mintTo(address to, uint256 amount) external;
function burnFrom(address to, uint256 amount) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IGo {
/// @notice Returns the address of the UniqueIdentity contract.
function uniqueIdentity() external view returns (address);
function go(address account) external view returns (bool);
function updateGoldfinchConfig() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IGoldfinchConfig {
function getNumber(uint256 index) external returns (uint256);
function getAddress(uint256 index) external returns (address);
function setAddress(uint256 index, address newAddress) external returns (address);
function setNumber(uint256 index, uint256 newNumber) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IGoldfinchFactory {
function createCreditLine() external returns (address);
function createBorrower(address owner) external returns (address);
function createPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) external returns (address);
function createMigratedPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) external returns (address);
function updateGoldfinchConfig() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IPool {
uint256 public sharePrice;
function deposit(uint256 amount) external virtual;
function withdraw(uint256 usdcAmount) external virtual;
function withdrawInFidu(uint256 fiduAmount) external virtual;
function collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) public virtual;
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool);
function drawdown(address to, uint256 amount) public virtual returns (bool);
function sweepToCompound() public virtual;
function sweepFromCompound() public virtual;
function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual;
function assets() public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol";
interface IPoolTokens is IERC721 {
event TokenMinted(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 amount,
uint256 tranche
);
event TokenRedeemed(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed,
uint256 tranche
);
event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);
struct TokenInfo {
address pool;
uint256 tranche;
uint256 principalAmount;
uint256 principalRedeemed;
uint256 interestRedeemed;
}
struct MintParams {
uint256 principalAmount;
uint256 tranche;
}
function mint(MintParams calldata params, address to) external returns (uint256);
function redeem(
uint256 tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed
) external;
function burn(uint256 tokenId) external;
function onPoolCreated(address newPool) external;
function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory);
function validPool(address sender) external view returns (bool);
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ITranchedPool.sol";
abstract contract ISeniorPool {
uint256 public sharePrice;
uint256 public totalLoansOutstanding;
uint256 public totalWritedowns;
function deposit(uint256 amount) external virtual returns (uint256 depositShares);
function depositWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 depositShares);
function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount);
function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount);
function sweepToCompound() public virtual;
function sweepFromCompound() public virtual;
function invest(ITranchedPool pool) public virtual;
function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256);
function investJunior(ITranchedPool pool, uint256 amount) public virtual;
function redeem(uint256 tokenId) public virtual;
function writedown(uint256 tokenId) public virtual;
function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount);
function assets() public view virtual returns (uint256);
function getNumShares(uint256 amount) public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ISeniorPool.sol";
import "./ITranchedPool.sol";
abstract contract ISeniorPoolStrategy {
function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256);
function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount);
function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IV2CreditLine.sol";
abstract contract ITranchedPool {
IV2CreditLine public creditLine;
uint256 public createdAt;
enum Tranches {
Reserved,
Senior,
Junior
}
struct TrancheInfo {
uint256 id;
uint256 principalDeposited;
uint256 principalSharePrice;
uint256 interestSharePrice;
uint256 lockedUntil;
}
function initialize(
address _config,
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) public virtual;
function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory);
function pay(uint256 amount) external virtual;
function lockJuniorCapital() external virtual;
function lockPool() external virtual;
function drawdown(uint256 amount) external virtual;
function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId);
function assess() external virtual;
function depositWithPermit(
uint256 tranche,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 tokenId);
function availableToWithdraw(uint256 tokenId)
external
view
virtual
returns (uint256 interestRedeemable, uint256 principalRedeemable);
function withdraw(uint256 tokenId, uint256 amount)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMax(uint256 tokenId)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ICreditLine.sol";
abstract contract IV2CreditLine is ICreditLine {
function principal() external view virtual returns (uint256);
function totalInterestAccrued() external view virtual returns (uint256);
function termStartTime() external view virtual returns (uint256);
function setLimit(uint256 newAmount) external virtual;
function setBalance(uint256 newBalance) external virtual;
function setPrincipal(uint256 _principal) external virtual;
function setTotalInterestAccrued(uint256 _interestAccrued) external virtual;
function drawdown(uint256 amount) external virtual;
function assess()
external
virtual
returns (
uint256,
uint256,
uint256
);
function initialize(
address _config,
address owner,
address _borrower,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) public virtual;
function setTermEndTime(uint256 newTermEndTime) external virtual;
function setNextDueTime(uint256 newNextDueTime) external virtual;
function setInterestOwed(uint256 newInterestOwed) external virtual;
function setPrincipalOwed(uint256 newPrincipalOwed) external virtual;
function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual;
function setWritedownAmount(uint256 newWritedownAmount) external virtual;
function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual;
function setLateFeeApr(uint256 newLateFeeApr) external virtual;
function updateGoldfinchConfig() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./CreditLine.sol";
import "../../interfaces/ICreditLine.sol";
import "../../external/FixedPoint.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title The Accountant
* @notice Library for handling key financial calculations, such as interest and principal accrual.
* @author Goldfinch
*/
library Accountant {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Signed;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for int256;
using FixedPoint for uint256;
// Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled
uint256 public constant FP_SCALING_FACTOR = 10**18;
uint256 public constant INTEREST_DECIMALS = 1e18;
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
uint256 public constant SECONDS_PER_YEAR = (SECONDS_PER_DAY * 365);
struct PaymentAllocation {
uint256 interestPayment;
uint256 principalPayment;
uint256 additionalBalancePayment;
}
function calculateInterestAndPrincipalAccrued(
CreditLine cl,
uint256 timestamp,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
uint256 balance = cl.balance(); // gas optimization
uint256 interestAccrued = calculateInterestAccrued(cl, balance, timestamp, lateFeeGracePeriod);
uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, timestamp);
return (interestAccrued, principalAccrued);
}
function calculateInterestAndPrincipalAccruedOverPeriod(
CreditLine cl,
uint256 balance,
uint256 startTime,
uint256 endTime,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
uint256 interestAccrued = calculateInterestAccruedOverPeriod(cl, balance, startTime, endTime, lateFeeGracePeriod);
uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, endTime);
return (interestAccrued, principalAccrued);
}
function calculatePrincipalAccrued(
ICreditLine cl,
uint256 balance,
uint256 timestamp
) public view returns (uint256) {
// If we've already accrued principal as of the term end time, then don't accrue more principal
uint256 termEndTime = cl.termEndTime();
if (cl.interestAccruedAsOf() >= termEndTime) {
return 0;
}
if (timestamp >= termEndTime) {
return balance;
} else {
return 0;
}
}
function calculateWritedownFor(
ICreditLine cl,
uint256 timestamp,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
return calculateWritedownForPrincipal(cl, cl.balance(), timestamp, gracePeriodInDays, maxDaysLate);
}
function calculateWritedownForPrincipal(
ICreditLine cl,
uint256 principal,
uint256 timestamp,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl);
if (amountOwedPerDay.isEqual(0)) {
return (0, 0);
}
FixedPoint.Unsigned memory fpGracePeriod = FixedPoint.fromUnscaledUint(gracePeriodInDays);
FixedPoint.Unsigned memory daysLate;
// Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30,
// Before the term end date, we use the interestOwed to calculate the periods late. However, after the loan term
// has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to
// calculate the periods later.
uint256 totalOwed = cl.interestOwed().add(cl.principalOwed());
daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay);
if (timestamp > cl.termEndTime()) {
uint256 secondsLate = timestamp.sub(cl.termEndTime());
daysLate = daysLate.add(FixedPoint.fromUnscaledUint(secondsLate).div(SECONDS_PER_DAY));
}
FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate);
FixedPoint.Unsigned memory writedownPercent;
if (daysLate.isLessThanOrEqual(fpGracePeriod)) {
// Within the grace period, we don't have to write down, so assume 0%
writedownPercent = FixedPoint.fromUnscaledUint(0);
} else {
writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate));
}
FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(principal).div(FP_SCALING_FACTOR);
// This will return a number between 0-100 representing the write down percent with no decimals
uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue;
return (unscaledWritedownPercent, writedownAmount.rawValue);
}
function calculateAmountOwedForOneDay(ICreditLine cl) public view returns (FixedPoint.Unsigned memory interestOwed) {
// Determine theoretical interestOwed for one full day
uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS);
interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365);
return interestOwed;
}
function calculateInterestAccrued(
CreditLine cl,
uint256 balance,
uint256 timestamp,
uint256 lateFeeGracePeriodInDays
) public view returns (uint256) {
// We use Math.min here to prevent integer overflow (ie. go negative) when calculating
// numSecondsElapsed. Typically this shouldn't be possible, because
// the interestAccruedAsOf couldn't be *after* the current timestamp. However, when assessing
// we allow this function to be called with a past timestamp, which raises the possibility
// of overflow.
// This use of min should not generate incorrect interest calculations, since
// this function's purpose is just to normalize balances, and handing in a past timestamp
// will necessarily return zero interest accrued (because zero elapsed time), which is correct.
uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf());
return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays);
}
function calculateInterestAccruedOverPeriod(
CreditLine cl,
uint256 balance,
uint256 startTime,
uint256 endTime,
uint256 lateFeeGracePeriodInDays
) public view returns (uint256 interestOwed) {
uint256 secondsElapsed = endTime.sub(startTime);
uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS);
interestOwed = totalInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR);
if (lateFeeApplicable(cl, endTime, lateFeeGracePeriodInDays)) {
uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS);
uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR);
interestOwed = interestOwed.add(additionalLateFeeInterest);
}
return interestOwed;
}
function lateFeeApplicable(
CreditLine cl,
uint256 timestamp,
uint256 gracePeriodInDays
) public view returns (bool) {
uint256 secondsLate = timestamp.sub(cl.lastFullPaymentTime());
return cl.lateFeeApr() > 0 && secondsLate > gracePeriodInDays.mul(SECONDS_PER_DAY);
}
function allocatePayment(
uint256 paymentAmount,
uint256 balance,
uint256 interestOwed,
uint256 principalOwed
) public pure returns (PaymentAllocation memory) {
uint256 paymentRemaining = paymentAmount;
uint256 interestPayment = Math.min(interestOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(interestPayment);
uint256 principalPayment = Math.min(principalOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(principalPayment);
uint256 balanceRemaining = balance.sub(principalPayment);
uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining);
return
PaymentAllocation({
interestPayment: interestPayment,
principalPayment: principalPayment,
additionalBalancePayment: additionalBalancePayment
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./PauserPausable.sol";
/**
* @title BaseUpgradeablePausable contract
* @notice This is our Base contract that most other contracts inherit from. It includes many standard
* useful abilities like ugpradeability, pausability, access control, and re-entrancy guards.
* @author Goldfinch
*/
contract BaseUpgradeablePausable is
Initializable,
AccessControlUpgradeSafe,
PauserPausable,
ReentrancyGuardUpgradeSafe
{
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
using SafeMath for uint256;
// Pre-reserving a few slots in the base contract in case we need to add things in the future.
// This does not actually take up gas cost or storage cost, but it does reserve the storage slots.
// See OpenZeppelin's use of this pattern here:
// https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37
uint256[50] private __gap1;
uint256[50] private __gap2;
uint256[50] private __gap3;
uint256[50] private __gap4;
// solhint-disable-next-line func-name-mixedcase
function __BaseUpgradeablePausable__init(address owner) public initializer {
require(owner != address(0), "Owner cannot be the zero address");
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "../../interfaces/IPool.sol";
import "../../interfaces/IFidu.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ICreditDesk.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ICUSDCContract.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../interfaces/IGoldfinchFactory.sol";
import "../../interfaces/IGo.sol";
/**
* @title ConfigHelper
* @notice A convenience library for getting easy access to other contracts and constants within the
* protocol, through the use of the GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigHelper {
function getPool(GoldfinchConfig config) internal view returns (IPool) {
return IPool(poolAddress(config));
}
function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) {
return ISeniorPool(seniorPoolAddress(config));
}
function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) {
return ISeniorPoolStrategy(seniorPoolStrategyAddress(config));
}
function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) {
return IERC20withDec(usdcAddress(config));
}
function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) {
return ICreditDesk(creditDeskAddress(config));
}
function getFidu(GoldfinchConfig config) internal view returns (IFidu) {
return IFidu(fiduAddress(config));
}
function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) {
return ICUSDCContract(cusdcContractAddress(config));
}
function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) {
return IPoolTokens(poolTokensAddress(config));
}
function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) {
return IGoldfinchFactory(goldfinchFactoryAddress(config));
}
function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) {
return IERC20withDec(gfiAddress(config));
}
function getGo(GoldfinchConfig config) internal view returns (IGo) {
return IGo(goAddress(config));
}
function oneInchAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.OneInch));
}
function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation));
}
function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder));
}
function configAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig));
}
function poolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Pool));
}
function poolTokensAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens));
}
function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool));
}
function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy));
}
function creditDeskAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk));
}
function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory));
}
function gfiAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GFI));
}
function fiduAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Fidu));
}
function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract));
}
function usdcAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.USDC));
}
function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation));
}
function migratedTranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.MigratedTranchedPoolImplementation));
}
function reserveAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve));
}
function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin));
}
function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation));
}
function goAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Go));
}
function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator));
}
function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator));
}
function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays));
}
function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays));
}
function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds));
}
function getTransferRestrictionPeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays));
}
function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @title ConfigOptions
* @notice A central place for enumerating the configurable options of our GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigOptions {
// NEVER EVER CHANGE THE ORDER OF THESE!
// You can rename or append. But NEVER change the order.
enum Numbers {
TransactionLimit,
TotalFundsLimit,
MaxUnderwriterLimit,
ReserveDenominator,
WithdrawFeeDenominator,
LatenessGracePeriodInDays,
LatenessMaxDays,
DrawdownPeriodInSeconds,
TransferRestrictionPeriodInDays,
LeverageRatio
}
enum Addresses {
Pool,
CreditLineImplementation,
GoldfinchFactory,
CreditDesk,
Fidu,
USDC,
TreasuryReserve,
ProtocolAdmin,
OneInch,
TrustedForwarder,
CUSDCContract,
GoldfinchConfig,
PoolTokens,
TranchedPoolImplementation,
SeniorPool,
SeniorPoolStrategy,
MigratedTranchedPoolImplementation,
BorrowerImplementation,
GFI,
Go
}
function getNumberName(uint256 number) public pure returns (string memory) {
Numbers numberName = Numbers(number);
if (Numbers.TransactionLimit == numberName) {
return "TransactionLimit";
}
if (Numbers.TotalFundsLimit == numberName) {
return "TotalFundsLimit";
}
if (Numbers.MaxUnderwriterLimit == numberName) {
return "MaxUnderwriterLimit";
}
if (Numbers.ReserveDenominator == numberName) {
return "ReserveDenominator";
}
if (Numbers.WithdrawFeeDenominator == numberName) {
return "WithdrawFeeDenominator";
}
if (Numbers.LatenessGracePeriodInDays == numberName) {
return "LatenessGracePeriodInDays";
}
if (Numbers.LatenessMaxDays == numberName) {
return "LatenessMaxDays";
}
if (Numbers.DrawdownPeriodInSeconds == numberName) {
return "DrawdownPeriodInSeconds";
}
if (Numbers.TransferRestrictionPeriodInDays == numberName) {
return "TransferRestrictionPeriodInDays";
}
if (Numbers.LeverageRatio == numberName) {
return "LeverageRatio";
}
revert("Unknown value passed to getNumberName");
}
function getAddressName(uint256 addressKey) public pure returns (string memory) {
Addresses addressName = Addresses(addressKey);
if (Addresses.Pool == addressName) {
return "Pool";
}
if (Addresses.CreditLineImplementation == addressName) {
return "CreditLineImplementation";
}
if (Addresses.GoldfinchFactory == addressName) {
return "GoldfinchFactory";
}
if (Addresses.CreditDesk == addressName) {
return "CreditDesk";
}
if (Addresses.Fidu == addressName) {
return "Fidu";
}
if (Addresses.USDC == addressName) {
return "USDC";
}
if (Addresses.TreasuryReserve == addressName) {
return "TreasuryReserve";
}
if (Addresses.ProtocolAdmin == addressName) {
return "ProtocolAdmin";
}
if (Addresses.OneInch == addressName) {
return "OneInch";
}
if (Addresses.TrustedForwarder == addressName) {
return "TrustedForwarder";
}
if (Addresses.CUSDCContract == addressName) {
return "CUSDCContract";
}
if (Addresses.PoolTokens == addressName) {
return "PoolTokens";
}
if (Addresses.TranchedPoolImplementation == addressName) {
return "TranchedPoolImplementation";
}
if (Addresses.SeniorPool == addressName) {
return "SeniorPool";
}
if (Addresses.SeniorPoolStrategy == addressName) {
return "SeniorPoolStrategy";
}
if (Addresses.MigratedTranchedPoolImplementation == addressName) {
return "MigratedTranchedPoolImplementation";
}
if (Addresses.BorrowerImplementation == addressName) {
return "BorrowerImplementation";
}
if (Addresses.GFI == addressName) {
return "GFI";
}
if (Addresses.Go == addressName) {
return "Go";
}
revert("Unknown value passed to getAddressName");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "./ConfigHelper.sol";
import "./BaseUpgradeablePausable.sol";
import "./Accountant.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ICreditLine.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
/**
* @title CreditLine
* @notice A contract that represents the agreement between Backers and
* a Borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed.
* A CreditLine belongs to a TranchedPool, and is fully controlled by that TranchedPool. It does not
* operate in any standalone capacity. It should generally be considered internal to the TranchedPool.
* @author Goldfinch
*/
// solhint-disable-next-line max-states-count
contract CreditLine is BaseUpgradeablePausable, ICreditLine {
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
// Credit line terms
address public override borrower;
uint256 public override limit;
uint256 public override interestApr;
uint256 public override paymentPeriodInDays;
uint256 public override termInDays;
uint256 public override lateFeeApr;
// Accounting variables
uint256 public override balance;
uint256 public override interestOwed;
uint256 public override principalOwed;
uint256 public override termEndTime;
uint256 public override nextDueTime;
uint256 public override interestAccruedAsOf;
uint256 public override lastFullPaymentTime;
uint256 public totalInterestAccrued;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
function initialize(
address _config,
address owner,
address _borrower,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) public initializer {
require(_config != address(0) && owner != address(0) && _borrower != address(0), "Zero address passed in");
__BaseUpgradeablePausable__init(owner);
config = GoldfinchConfig(_config);
borrower = _borrower;
limit = _limit;
interestApr = _interestApr;
paymentPeriodInDays = _paymentPeriodInDays;
termInDays = _termInDays;
lateFeeApr = _lateFeeApr;
interestAccruedAsOf = block.timestamp;
// Unlock owner, which is a TranchedPool, for infinite amount
bool success = config.getUSDC().approve(owner, uint256(-1));
require(success, "Failed to approve USDC");
}
/**
* @notice Updates the internal accounting to track a drawdown as of current block timestamp.
* Does not move any money
* @param amount The amount in USDC that has been drawndown
*/
function drawdown(uint256 amount) external onlyAdmin {
require(amount.add(balance) <= limit, "Cannot drawdown more than the limit");
uint256 timestamp = currentTime();
if (balance == 0) {
setInterestAccruedAsOf(timestamp);
setLastFullPaymentTime(timestamp);
setTotalInterestAccrued(0);
setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays)));
}
(uint256 _interestOwed, uint256 _principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp);
balance = balance.add(amount);
updateCreditLineAccounting(balance, _interestOwed, _principalOwed);
require(!isLate(timestamp), "Cannot drawdown when payments are past due");
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin {
lateFeeApr = newLateFeeApr;
}
function setLimit(uint256 newAmount) external onlyAdmin {
limit = newAmount;
}
function termStartTime() external view returns (uint256) {
return termEndTime.sub(SECONDS_PER_DAY.mul(termInDays));
}
function setTermEndTime(uint256 newTermEndTime) public onlyAdmin {
termEndTime = newTermEndTime;
}
function setNextDueTime(uint256 newNextDueTime) public onlyAdmin {
nextDueTime = newNextDueTime;
}
function setBalance(uint256 newBalance) public onlyAdmin {
balance = newBalance;
}
function setTotalInterestAccrued(uint256 _totalInterestAccrued) public onlyAdmin {
totalInterestAccrued = _totalInterestAccrued;
}
function setInterestOwed(uint256 newInterestOwed) public onlyAdmin {
interestOwed = newInterestOwed;
}
function setPrincipalOwed(uint256 newPrincipalOwed) public onlyAdmin {
principalOwed = newPrincipalOwed;
}
function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) public onlyAdmin {
interestAccruedAsOf = newInterestAccruedAsOf;
}
function setLastFullPaymentTime(uint256 newLastFullPaymentTime) public onlyAdmin {
lastFullPaymentTime = newLastFullPaymentTime;
}
/**
* @notice Triggers an assessment of the creditline. Any USDC balance available in the creditline is applied
* towards the interest and principal.
* @return Any amount remaining after applying payments towards the interest and principal
* @return Amount applied towards interest
* @return Amount applied towards principal
*/
function assess()
public
onlyAdmin
returns (
uint256,
uint256,
uint256
)
{
// Do not assess until a full period has elapsed or past due
require(balance > 0, "Must have balance to assess credit line");
// Don't assess credit lines early!
if (currentTime() < nextDueTime && !isLate(currentTime())) {
return (0, 0, 0);
}
uint256 timeToAssess = calculateNextDueTime();
setNextDueTime(timeToAssess);
// We always want to assess for the most recently *past* nextDueTime.
// So if the recalculation above sets the nextDueTime into the future,
// then ensure we pass in the one just before this.
if (timeToAssess > currentTime()) {
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
timeToAssess = timeToAssess.sub(secondsPerPeriod);
}
return handlePayment(getUSDCBalance(address(this)), timeToAssess);
}
function calculateNextDueTime() internal view returns (uint256) {
uint256 newNextDueTime = nextDueTime;
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
uint256 curTimestamp = currentTime();
// You must have just done your first drawdown
if (newNextDueTime == 0 && balance > 0) {
return curTimestamp.add(secondsPerPeriod);
}
// Active loan that has entered a new period, so return the *next* newNextDueTime.
// But never return something after the termEndTime
if (balance > 0 && curTimestamp >= newNextDueTime) {
uint256 secondsToAdvance = (curTimestamp.sub(newNextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod);
newNextDueTime = newNextDueTime.add(secondsToAdvance);
return Math.min(newNextDueTime, termEndTime);
}
// You're paid off, or have not taken out a loan yet, so no next due time.
if (balance == 0 && newNextDueTime != 0) {
return 0;
}
// Active loan in current period, where we've already set the newNextDueTime correctly, so should not change.
if (balance > 0 && curTimestamp < newNextDueTime) {
return newNextDueTime;
}
revert("Error: could not calculate next due time.");
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function isLate(uint256 timestamp) internal view returns (bool) {
uint256 secondsElapsedSinceFullPayment = timestamp.sub(lastFullPaymentTime);
return secondsElapsedSinceFullPayment > paymentPeriodInDays.mul(SECONDS_PER_DAY);
}
/**
* @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool.
* It also updates all the accounting variables. Note that interest is always paid back first, then principal.
* Any extra after paying the minimum will go towards existing principal (reducing the
* effective interest rate). Any extra after the full loan has been paid off will remain in the
* USDC Balance of the creditLine, where it will be automatically used for the next drawdown.
* @param paymentAmount The amount, in USDC atomic units, to be applied
* @param timestamp The timestamp on which accrual calculations should be based. This allows us
* to be precise when we assess a Credit Line
*/
function handlePayment(uint256 paymentAmount, uint256 timestamp)
internal
returns (
uint256,
uint256,
uint256
)
{
(uint256 newInterestOwed, uint256 newPrincipalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp);
Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(
paymentAmount,
balance,
newInterestOwed,
newPrincipalOwed
);
uint256 newBalance = balance.sub(pa.principalPayment);
// Apply any additional payment towards the balance
newBalance = newBalance.sub(pa.additionalBalancePayment);
uint256 totalPrincipalPayment = balance.sub(newBalance);
uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);
updateCreditLineAccounting(
newBalance,
newInterestOwed.sub(pa.interestPayment),
newPrincipalOwed.sub(pa.principalPayment)
);
assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount);
return (paymentRemaining, pa.interestPayment, totalPrincipalPayment);
}
function updateAndGetInterestAndPrincipalOwedAsOf(uint256 timestamp) internal returns (uint256, uint256) {
(uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
this,
timestamp,
config.getLatenessGracePeriodInDays()
);
if (interestAccrued > 0) {
// If we've accrued any interest, update interestAccruedAsOf to the time that we've
// calculated interest for. If we've not accrued any interest, then we keep the old value so the next
// time the entire period is taken into account.
setInterestAccruedAsOf(timestamp);
totalInterestAccrued = totalInterestAccrued.add(interestAccrued);
}
return (interestOwed.add(interestAccrued), principalOwed.add(principalAccrued));
}
function updateCreditLineAccounting(
uint256 newBalance,
uint256 newInterestOwed,
uint256 newPrincipalOwed
) internal nonReentrant {
setBalance(newBalance);
setInterestOwed(newInterestOwed);
setPrincipalOwed(newPrincipalOwed);
// This resets lastFullPaymentTime. These conditions assure that they have
// indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown)
uint256 _nextDueTime = nextDueTime;
if (newInterestOwed == 0 && _nextDueTime != 0) {
// If interest was fully paid off, then set the last full payment as the previous due time
uint256 mostRecentLastDueTime;
if (currentTime() < _nextDueTime) {
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
mostRecentLastDueTime = _nextDueTime.sub(secondsPerPeriod);
} else {
mostRecentLastDueTime = _nextDueTime;
}
setLastFullPaymentTime(mostRecentLastDueTime);
}
setNextDueTime(calculateNextDueTime());
}
function getUSDCBalance(address _address) internal view returns (uint256) {
return config.getUSDC().balanceOf(_address);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "../../interfaces/IGoldfinchConfig.sol";
import "./ConfigOptions.sol";
/**
* @title GoldfinchConfig
* @notice This contract stores mappings of useful "protocol config state", giving a central place
* for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars
* are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol.
* Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this
* is mostly to save gas costs of having each call go through a proxy)
* @author Goldfinch
*/
contract GoldfinchConfig is BaseUpgradeablePausable {
bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE");
mapping(uint256 => address) public addresses;
mapping(uint256 => uint256) public numbers;
mapping(address => bool) public goList;
event AddressUpdated(address owner, uint256 index, address oldValue, address newValue);
event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue);
event GoListed(address indexed member);
event NoListed(address indexed member);
bool public valuesInitialized;
function initialize(address owner) public initializer {
require(owner != address(0), "Owner address cannot be empty");
__BaseUpgradeablePausable__init(owner);
_setupRole(GO_LISTER_ROLE, owner);
_setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE);
}
function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin {
require(addresses[addressIndex] == address(0), "Address has already been initialized");
emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress);
addresses[addressIndex] = newAddress;
}
function setNumber(uint256 index, uint256 newNumber) public onlyAdmin {
emit NumberUpdated(msg.sender, index, numbers[index], newNumber);
numbers[index] = newNumber;
}
function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve);
emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve);
addresses[key] = newTreasuryReserve;
}
function setSeniorPoolStrategy(address newStrategy) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy);
emit AddressUpdated(msg.sender, key, addresses[key], newStrategy);
addresses[key] = newStrategy;
}
function setCreditLineImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setBorrowerImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setGoldfinchConfig(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function initializeFromOtherConfig(address _initialConfig) public onlyAdmin {
require(!valuesInitialized, "Already initialized values");
IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig);
for (uint256 i = 0; i < 10; i++) {
setNumber(i, initialConfig.getNumber(i));
}
for (uint256 i = 0; i < 11; i++) {
if (getAddress(i) == address(0)) {
setAddress(i, initialConfig.getAddress(i));
}
}
valuesInitialized = true;
}
/**
* @dev Adds a user to go-list
* @param _member address to add to go-list
*/
function addToGoList(address _member) public onlyGoListerRole {
goList[_member] = true;
emit GoListed(_member);
}
/**
* @dev removes a user from go-list
* @param _member address to remove from go-list
*/
function removeFromGoList(address _member) public onlyGoListerRole {
goList[_member] = false;
emit NoListed(_member);
}
/**
* @dev adds many users to go-list at once
* @param _members addresses to ad to go-list
*/
function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole {
for (uint256 i = 0; i < _members.length; i++) {
addToGoList(_members[i]);
}
}
/**
* @dev removes many users from go-list at once
* @param _members addresses to remove from go-list
*/
function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole {
for (uint256 i = 0; i < _members.length; i++) {
removeFromGoList(_members[i]);
}
}
/*
Using custom getters in case we want to change underlying implementation later,
or add checks or validations later on.
*/
function getAddress(uint256 index) public view returns (address) {
return addresses[index];
}
function getNumber(uint256 index) public view returns (uint256) {
return numbers[index];
}
modifier onlyGoListerRole() {
require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
/**
* @title PauserPausable
* @notice Inheriting from OpenZeppelin's Pausable contract, this does small
* augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract.
* It is meant to be inherited.
* @author Goldfinch
*/
contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// solhint-disable-next-line func-name-mixedcase
function __PauserPausable__init() public initializer {
__Pausable_init_unchained();
}
/**
* @dev Pauses all functions guarded by Pause
*
* See {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the PAUSER_ROLE.
*/
function pause() public onlyPauserRole {
_pause();
}
/**
* @dev Unpauses the contract
*
* See {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the Pauser role
*/
function unpause() public onlyPauserRole {
_unpause();
}
modifier onlyPauserRole() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action");
_;
}
} | Whether `a` is equal to `b`. a a FixedPoint. 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;
}
| 469,936 |
./partial_match/3/0x8252AaBFFa377a323F11DFa0d7cBB41409878BA3/sources/yaDelayu3.sol | Only staking contract can call | function burnToken(address burnFrom, uint burnAmount) public returns(bool){ | 5,198,057 |
./full_match/1/0x76f87b70D20547B2415cf6fcba0091072d86B21e/sources/Donation.sol | used to check whether donation is active or not return bool returns true if donation is active, otherwise false/ | function isDonationActive() external view returns (bool) {
return donationState == 0 ? true : false;
}
| 4,943,108 |
pragma solidity ^0.5.8;
// https://github.com/pipermerriam/ethereum-datetime
contract DateTime {
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) internal pure 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) internal pure returns (uint) {
year -= 1;
return year / 4 - year / 100 + year / 400;
}
function getDaysInMonth(uint8 month, uint16 year) internal pure 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 pure returns (_DateTime memory 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);
dt.weekday = getWeekday(timestamp);
}
function getYear(uint timestamp) internal pure 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) internal pure returns (uint8) {
return parseTimestamp(timestamp).month;
}
function getDay(uint timestamp) internal pure returns (uint8) {
return parseTimestamp(timestamp).day;
}
function getHour(uint timestamp) internal pure returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
function getMinute(uint timestamp) internal pure returns (uint8) {
return uint8((timestamp / 60) % 60);
}
function getSecond(uint timestamp) internal pure returns (uint8) {
return uint8(timestamp % 60);
}
function getWeekday(uint timestamp) internal pure returns (uint8) {
return uint8((timestamp / DAY_IN_SECONDS + 4) % 7);
}
function toTimestamp(uint16 year, uint8 month, uint8 day) internal pure returns (uint timestamp) {
return toTimestamp(year, month, day, 0, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) internal pure returns (uint timestamp) {
return toTimestamp(year, month, day, hour, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute)
internal
pure
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)
internal
pure
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;
}
}
pragma solidity ^0.5.8;
/*
* 'Bolton Holding Group' CORPORATE BOND Subscription contract
*
* Token : Bolton Coin (BFCL)
* Interest rate : 22% yearly
* Duration subscription: 24 months
*
* Copyright (C) 2019 Raffaele Bini - 5esse Informatica (https://www.5esse.it)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./IERC20.sol";
import "./Whitelist.sol";
import "./Vault.sol";
import "./PriceManagerRole.sol";
import "./DateTime.sol";
contract DepositPlan is Ownable, ReentrancyGuard, PriceManagerRole, DateTime {
using SafeMath for uint;
enum Currency {BFCL, EURO}
event AddInvestor(address indexed investor);
event CloseAccount(address indexed investor);
event InvestorDeposit(address indexed investor, uint bfclAmount, uint euroAmount, uint depositTime);
event Reinvest(
uint oldBfcl,
uint oldEuro,
uint oldLastWithdrawTime,
uint bfclDividends,
uint euroDividends,
uint lastWithdrawTime
);
event DeleteDebt(address indexed investor, uint index);
event DeleteDeposit(address indexed investor, uint index);
event AddDebt(address indexed investor, uint bfclDebt, uint euroDebt);
uint internal constant RATE_MULTIPLIER = 10 ** 18;
uint internal constant MIN_INVESTMENT_EURO_CENT = 50000 * RATE_MULTIPLIER; // 50k EURO in cents
uint internal constant MIN_REPLENISH_EURO_CENT = 1000 * RATE_MULTIPLIER; // 1k EURO in cents
uint internal HUNDRED_PERCENTS = 10000; // 100%
uint internal PERCENT_PER_YEAR = 2200; // 22%
IERC20 public bfclToken;
IERC20 public euroToken;
Whitelist public whitelist;
address public tokensWallet;
uint public bfclEuroRateFor72h; // 1 EUR = bfclEuroRateFor72h BFCL / 10^18
bool public isStopped;
mapping(address => Account) public accounts;
mapping(address => Deposit[]) public deposits;
mapping(address => Debt[]) public debts;
struct Account {
Vault vault;
uint firstDepositTimestamp;
uint stopTime;
}
struct Deposit {
uint bfcl;
uint euro;
uint lastWithdrawTime;
}
struct Debt {
uint bfcl;
uint euro;
}
constructor(IERC20 _bfclToken, Whitelist _whitelist, address _tokensWallet, uint _initialBfclEuroRateFor72h) public {
bfclToken = _bfclToken;
whitelist = _whitelist;
tokensWallet = _tokensWallet;
bfclEuroRateFor72h = _initialBfclEuroRateFor72h;
}
modifier onlyIfWhitelisted() {
require(whitelist.isWhitelisted(msg.sender), "Not whitelisted");
_;
}
// reverts ETH transfers
function() external {
revert();
}
// reverts erc223 token transfers
function tokenFallback(address, uint, bytes calldata) external pure {
revert();
}
function transferErc20(IERC20 _token, address _to, uint _value) external onlyOwner nonReentrant {
_token.transfer(_to, _value);
}
function transferBfcl(address _to, uint _value) external onlyOwner nonReentrant {
bfclToken.transfer(_to, _value);
}
function stop() external onlyOwner {
isStopped = true;
}
function invest(uint _bfclAmount) external onlyIfWhitelisted nonReentrant {
require(!isStopped, "Contract stopped. You can no longer invest.");
uint bfclAmount;
uint euroAmount;
address investor = msg.sender;
Account storage account = accounts[investor];
if (account.vault == Vault(0)) {
// first deposit
bfclAmount = _bfclAmount;
euroAmount = _bfclAmount.mul(RATE_MULTIPLIER).div(bfclEuroRateFor72h);
require(euroAmount >= MIN_INVESTMENT_EURO_CENT, "Should be more than minimum");
account.vault = new Vault(investor, bfclToken);
account.firstDepositTimestamp = now;
account.stopTime = now + 730 days;
emit AddInvestor(investor);
} else {
// replenish
require(now < account.stopTime, "2 years have passed. You can no longer replenish.");
uint oneKEuroInBfcl = bfclEuroRateFor72h.mul(MIN_REPLENISH_EURO_CENT).div(RATE_MULTIPLIER);
uint times = _bfclAmount.div(oneKEuroInBfcl);
bfclAmount = times.mul(oneKEuroInBfcl);
euroAmount = times.mul(MIN_REPLENISH_EURO_CENT);
require(euroAmount >= MIN_REPLENISH_EURO_CENT, "Should be more than minimum");
}
require(bfclToken.allowance(investor, address(this)) >= bfclAmount, "Allowance should not be less than amount");
bfclToken.transferFrom(investor, address(account.vault), bfclAmount);
deposits[investor].push(Deposit(bfclAmount, euroAmount, now));
emit InvestorDeposit(investor, bfclAmount, euroAmount, now);
}
function withdraw() external nonReentrant {
address investor = msg.sender;
Account storage account = accounts[investor];
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
uint result;
result += _tryToWithdrawDividends(investor, account, currency);
result += _tryToWithdrawDebts(investor, currency);
require(result > 0, "Nothing to withdraw");
_checkAndCloseAccount(investor);
}
function _tryToWithdrawDividends(address _investor, Account storage _account, Currency _currency)
internal
returns (uint result)
{
if (isInIntervals(now) || now >= _account.stopTime) {
uint depositCount = deposits[_investor].length;
if (depositCount > 0) {
for (uint i = 0; i < depositCount; i++) {
if (_withdrawOneDividend(_investor, _account, _currency, i)) {
result++;
}
}
if (now >= _account.stopTime) {
for (uint i = depositCount; i > 0; i--) {
_withdrawDeposit(_investor, i - 1);
}
}
}
}
}
function _tryToWithdrawDebts(address _investor, Currency _currency) internal returns (uint result) {
uint debtCount = debts[_investor].length;
if (debtCount > 0) {
for (uint i = 0; i < debtCount; i++) {
if (_withdrawOneDebt(_investor, _currency, i)) {
result++;
}
}
for (uint i = debtCount; i > 0; i--) {
_deleteDebt(_investor, i - 1);
}
}
}
function _withdrawDeposit(address _investor, uint _index) internal {
Vault vault = accounts[_investor].vault;
Deposit storage deposit = deposits[_investor][_index];
uint mustPay = deposit.bfcl;
uint toPayFromVault;
uint toPayFromWallet;
if (vault.getBalance() >= mustPay) {
toPayFromVault = mustPay;
} else {
toPayFromVault = vault.getBalance();
toPayFromWallet = mustPay.sub(toPayFromVault);
}
_deleteDeposit(_investor, _index);
if (toPayFromVault > 0) {
vault.withdrawToInvestor(toPayFromVault);
}
if (toPayFromWallet > 0) {
_send(_investor, toPayFromWallet, 0, Currency.BFCL);
}
}
function withdrawDividends() external nonReentrant {
address investor = msg.sender;
Account storage account = accounts[investor];
require(isInIntervals(now) || now >= account.stopTime, "Should be in interval or after 2 years");
require(deposits[investor].length > 0, "There is no deposits for your address");
uint result;
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
result += _tryToWithdrawDividends(investor, account, currency);
require(result > 0, "Nothing to withdraw");
_checkAndCloseAccount(investor);
}
function withdrawOneDividend(uint index) external nonReentrant {
address investor = msg.sender;
Account storage account = accounts[investor];
require(isInIntervals(now) || now >= account.stopTime, "Should be in interval or after 2 years");
require(deposits[investor].length > 0, "There is no deposits for your address");
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
require(_withdrawOneDividend(investor, account, currency, index), "Nothing to withdraw");
if (now >= account.stopTime) {
_withdrawDeposit(investor, index);
}
_checkAndCloseAccount(investor);
}
function withdrawDebts() external nonReentrant {
address investor = msg.sender;
require(debts[investor].length > 0, "There is no deposits for your address");
uint result;
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
result += _tryToWithdrawDebts(investor, currency);
require(result > 0, "Nothing to withdraw");
_checkAndCloseAccount(investor);
}
function withdrawOneDebt(uint index) external nonReentrant {
address investor = msg.sender;
require(debts[investor].length > 0, "There is no deposits for your address");
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
require(_withdrawOneDebt(investor, currency, index), "Nothing to withdraw");
_deleteDebt(investor, index);
_checkAndCloseAccount(investor);
}
function setBfclEuroRateFor72h(uint _rate) public onlyPriceManager {
bfclEuroRateFor72h = _rate;
}
function switchToBfcl() public onlyOwner {
require(address(euroToken) != address(0), "You are already using BFCL");
euroToken = IERC20(address(0));
}
function switchToEuro(IERC20 _euro) public onlyOwner {
require(address(_euro) != address(euroToken), "Trying to change euro token to same address");
euroToken = _euro;
}
function calculateDividendsForTimestamp(address _investor, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
Account storage account = accounts[_investor];
uint withdrawingTimestamp = _findIntervalStart(account, _timestamp);
for (uint i = 0; i < deposits[_investor].length; i++) {
(uint bfclDiv, uint euroDiv) = _calculateDividendForTimestamp(_investor, withdrawingTimestamp, i);
bfcl = bfcl.add(bfclDiv);
euro = euro.add(euroDiv);
}
if (withdrawingTimestamp >= account.stopTime) {
bfcl = bfcl.sub(account.vault.getBalance());
}
}
function calculateGroupDividendsForTimestamp(address[] memory _investors, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
for (uint i = 0; i < _investors.length; i++) {
address investor = _investors[i];
Account storage account = accounts[investor];
uint withdrawingTimestamp = _findIntervalStart(account, _timestamp);
for (uint d = 0; d < deposits[investor].length; d++) {
(uint bfclDiv, uint euroDiv) = _calculateDividendForTimestamp(investor, withdrawingTimestamp, d);
bfcl = bfcl.add(bfclDiv);
euro = euro.add(euroDiv);
}
if (withdrawingTimestamp >= account.stopTime) {
bfcl = bfcl.sub(account.vault.getBalance());
}
}
}
function calculateDividendsWithDebtsForTimestamp(address _investor, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
(bfcl, euro) = calculateDividendsForTimestamp(_investor, _timestamp);
for (uint d = 0; d < debts[_investor].length; d++) {
Debt storage debt = debts[_investor][d];
bfcl = bfcl.add(debt.bfcl);
euro = euro.add(debt.euro);
}
}
function calculateGroupDividendsWithDebtsForTimestamp(address[] memory _investors, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
(bfcl, euro) = calculateGroupDividendsForTimestamp(_investors, _timestamp);
for (uint i = 0; i < _investors.length; i++) {
address investor = _investors[i];
for (uint d = 0; d < debts[investor].length; d++) {
Debt storage debt = debts[investor][d];
bfcl = bfcl.add(debt.bfcl);
euro = euro.add(debt.euro);
}
}
}
function isInIntervals(uint _timestamp) public pure returns (bool) {
uint8[4] memory months = [1, 4, 7, 10];
_DateTime memory dt = parseTimestamp(_timestamp);
for (uint i = 0; i < months.length; i++) {
if (dt.month == months[i]) {
return 1 <= dt.day && dt.day <= 5;
}
}
return false;
}
function _getNextDate(uint _timestamp) internal pure returns (uint) {
_DateTime memory dt = parseTimestamp(_timestamp);
uint16 year;
uint8 month;
uint8[4] memory months = [1, 4, 7, 10];
for (uint i = months.length; i > 0; --i) {
if (dt.month >= months[i - 1]) {
if (i == months.length) {
year = dt.year + 1;
month = months[0];
} else {
year = dt.year;
month = months[i];
}
break;
}
}
return toTimestamp(year, month, 1);
}
// implies that the timestamp is exactly in any of the intervals or after stopTime
function _findIntervalStart(Account storage _account, uint _timestamp) internal view returns (uint) {
if (_timestamp >= _account.stopTime) {
return _account.stopTime;
} else {
_DateTime memory dt = parseTimestamp(_timestamp);
return toTimestamp(dt.year, dt.month, 1);
}
}
function _getBalance(Currency _currency) internal view returns (uint) {
IERC20 token = _currency == Currency.BFCL ? bfclToken : euroToken;
uint balance = token.balanceOf(tokensWallet);
uint allowance = token.allowance(tokensWallet, address(this));
return balance < allowance ? balance : allowance;
}
function _checkAndCloseAccount(address _investor) internal {
bool isDepositWithdrawn = accounts[_investor].vault.getBalance() == 0;
bool isDividendsWithdrawn = deposits[_investor].length == 0;
bool isDebtsWithdrawn = debts[_investor].length == 0;
if (isDepositWithdrawn && isDividendsWithdrawn && isDebtsWithdrawn) {
delete accounts[_investor];
emit CloseAccount(_investor);
}
}
function _withdrawOneDebt(address _investor, Currency _currency, uint _index) internal returns (bool) {
Debt storage debt = debts[_investor][_index];
return _send(_investor, debt.bfcl, debt.euro, _currency);
}
function _deleteDebt(address _investor, uint _index) internal {
uint lastIndex = debts[_investor].length - 1;
if (_index == lastIndex) {
delete debts[_investor][_index];
} else {
debts[_investor][_index] = debts[_investor][lastIndex];
delete debts[_investor][lastIndex];
}
emit DeleteDebt(_investor, _index);
debts[_investor].length--;
}
function _checkAndReinvest(Deposit storage _deposit, uint _currentIntervalStart) internal {
while (true) {
uint nextDate = _getNextDate(_deposit.lastWithdrawTime);
if (nextDate >= _currentIntervalStart) {
return;
}
uint periodSeconds = nextDate.sub(_deposit.lastWithdrawTime);
(uint bfclDividends, uint euroDividends) = _calculateDividendForPeriod(_deposit, periodSeconds);
emit Reinvest(_deposit.bfcl, _deposit.euro, _deposit.lastWithdrawTime, bfclDividends, euroDividends, nextDate);
_deposit.bfcl = _deposit.bfcl.add(bfclDividends);
_deposit.euro = _deposit.euro.add(euroDividends);
_deposit.lastWithdrawTime = nextDate;
}
}
function _withdrawOneDividend(address _investor, Account storage _account, Currency _currency, uint _index)
internal
returns (bool result)
{
Deposit storage deposit = deposits[_investor][_index];
uint intervalStart = _findIntervalStart(_account, now);
if (deposit.lastWithdrawTime > intervalStart) {
return false;
}
_checkAndReinvest(deposit, intervalStart);
uint periodSeconds = intervalStart.sub(deposit.lastWithdrawTime);
deposit.lastWithdrawTime = intervalStart;
(uint bfclDividends, uint euroDividends) = _calculateDividendForPeriod(deposit, periodSeconds);
result = _send(_investor, bfclDividends, euroDividends, _currency);
}
function _deleteDeposit(address _investor, uint _index) internal {
uint lastIndex = deposits[_investor].length - 1;
if (_index == lastIndex) {
delete deposits[_investor][_index];
} else {
deposits[_investor][_index] = deposits[_investor][lastIndex];
delete deposits[_investor][lastIndex];
}
emit DeleteDeposit(_investor, _index);
deposits[_investor].length--;
}
function _calculateDividendForTimestamp(address _investor, uint _withdrawingTimestamp, uint _depositIndex)
internal
view
returns (uint bfcl, uint euro)
{
Deposit storage deposit = deposits[_investor][_depositIndex];
if (deposit.lastWithdrawTime >= _withdrawingTimestamp) {
return (0, 0);
}
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
uint b = deposit.bfcl;
uint e = deposit.euro;
// check reinvestment
uint lastWithdrawTime = deposit.lastWithdrawTime;
while (true) {
uint nextDate = _getNextDate(lastWithdrawTime);
if (nextDate >= _withdrawingTimestamp) {
break;
}
uint periodSeconds = nextDate.sub(lastWithdrawTime);
(uint bfclDividends, uint euroDividends) = _calculateDividendForPeriod(b, e, periodSeconds);
b = b.add(bfclDividends);
e = e.add(euroDividends);
lastWithdrawTime = nextDate;
}
// calculate dividends for last interval
uint periodSeconds = _withdrawingTimestamp.sub(lastWithdrawTime);
(bfcl, euro) = _calculateDividendForPeriod(b, e, periodSeconds);
if (currency == Currency.BFCL) {
euro = 0;
} else if (_withdrawingTimestamp < accounts[_investor].stopTime) {
bfcl = 0;
}
if (_withdrawingTimestamp >= accounts[_investor].stopTime) {
if (currency == Currency.BFCL) {
bfcl = bfcl.add(b);
} else {
bfcl = b;
}
}
}
function _calculateDividendForPeriod(Deposit storage _deposit, uint _periodSeconds)
internal
view
returns (uint bfcl, uint euro)
{
(bfcl, euro) = _calculateDividendForPeriod(_deposit.bfcl, _deposit.euro, _periodSeconds);
}
function _calculateDividendForPeriod(uint _bfcl, uint _euro, uint _periodSeconds)
internal
view
returns (uint bfcl, uint euro)
{
bfcl = _bfcl.mul(_periodSeconds).mul(PERCENT_PER_YEAR).div(HUNDRED_PERCENTS).div(365 days);
euro = _euro.mul(_periodSeconds).mul(PERCENT_PER_YEAR).div(HUNDRED_PERCENTS).div(365 days);
}
function _send(address _investor, uint _bfclAmount, uint _euroAmount, Currency _currency) internal returns (bool) {
if (_bfclAmount == 0 && _euroAmount == 0) {
return false;
}
uint balance = _getBalance(_currency);
if (_currency == Currency.EURO) {
balance = balance.mul(RATE_MULTIPLIER).div(10 ** euroToken.decimals());
}
uint canPay;
if ((_currency == Currency.BFCL && balance >= _bfclAmount) || (_currency == Currency.EURO && balance >= _euroAmount)) {
if (_currency == Currency.BFCL) {
canPay = _bfclAmount;
} else {
canPay = _euroAmount;
}
} else {
canPay = balance;
uint bfclDebt;
uint euroDebt;
if (_currency == Currency.BFCL) {
bfclDebt = _bfclAmount.sub(canPay);
euroDebt = bfclDebt.mul(_euroAmount).div(_bfclAmount);
} else {
euroDebt = _euroAmount.sub(canPay);
bfclDebt = euroDebt.mul(_bfclAmount).div(_euroAmount);
}
debts[_investor].push(Debt(bfclDebt, euroDebt));
emit AddDebt(_investor, bfclDebt, euroDebt);
}
if (canPay == 0) {
return true;
}
uint toPay;
IERC20 token;
if (_currency == Currency.BFCL) {
toPay = canPay;
token = bfclToken;
} else {
toPay = canPay.mul(10 ** euroToken.decimals()).div(RATE_MULTIPLIER);
token = euroToken;
}
token.transferFrom(tokensWallet, _investor, toPay);
return true;
}
}
pragma solidity ^0.5.8;
/**
* @title ERC20 interface without bool returns
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external;
function transferFrom(address from, address to, uint256 value) external;
function decimals() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
}
pragma solidity ^0.5.2;
/**
* @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.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice 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 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;
}
}
pragma solidity ^0.5.8;
import "./Roles.sol";
contract PriceManagerRole {
using Roles for Roles.Role;
event PriceManagerAdded(address indexed account);
event PriceManagerRemoved(address indexed account);
Roles.Role private managers;
constructor() internal {
_addPriceManager(msg.sender);
}
modifier onlyPriceManager() {
require(isPriceManager(msg.sender), "Only for price manager");
_;
}
function isPriceManager(address account) public view returns (bool) {
return managers.has(account);
}
function addPriceManager(address account) public onlyPriceManager {
_addPriceManager(account);
}
function renouncePriceManager() public {
_removePriceManager(msg.sender);
}
function _addPriceManager(address account) internal {
managers.add(account);
emit PriceManagerAdded(account);
}
function _removePriceManager(address account) internal {
managers.remove(account);
emit PriceManagerRemoved(account);
}
}
pragma solidity ^0.5.2;
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2Ο.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
pragma solidity ^0.5.2;
/**
* @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;
}
}
pragma solidity ^0.5.8;
import "./Ownable.sol";
import "./SafeMath.sol";
import "./IERC20.sol";
contract Vault is Ownable {
using SafeMath for uint;
address public investor;
IERC20 internal bfclToken;
constructor(address _investor, IERC20 _bfclToken) public {
investor = _investor;
bfclToken = _bfclToken;
}
// reverts erc223 transfers
function tokenFallback(address, uint, bytes calldata) external pure {
revert("ERC223 tokens not allowed in Vault");
}
function withdrawToInvestor(uint _amount) external onlyOwner returns (bool) {
bfclToken.transfer(investor, _amount);
return true;
}
function getBalance() public view returns (uint) {
return bfclToken.balanceOf(address(this));
}
}
pragma solidity ^0.5.8;
import "./Roles.sol";
import "./Ownable.sol";
contract Whitelist is Ownable {
using Roles for Roles.Role;
Roles.Role private whitelist;
event WhitelistedAddressAdded(address indexed _address);
function isWhitelisted(address _address) public view returns (bool) {
return whitelist.has(_address);
}
function addAddressToWhitelist(address _address) external onlyOwner {
_addAddressToWhitelist(_address);
}
function addAddressesToWhitelist(address[] calldata _addresses) external onlyOwner {
for (uint i = 0; i < _addresses.length; i++) {
_addAddressToWhitelist(_addresses[i]);
}
}
function _addAddressToWhitelist(address _address) internal {
whitelist.add(_address);
emit WhitelistedAddressAdded(_address);
}
}
pragma solidity ^0.5.8;
// https://github.com/pipermerriam/ethereum-datetime
contract DateTime {
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) internal pure 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) internal pure returns (uint) {
year -= 1;
return year / 4 - year / 100 + year / 400;
}
function getDaysInMonth(uint8 month, uint16 year) internal pure 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 pure returns (_DateTime memory 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);
dt.weekday = getWeekday(timestamp);
}
function getYear(uint timestamp) internal pure 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) internal pure returns (uint8) {
return parseTimestamp(timestamp).month;
}
function getDay(uint timestamp) internal pure returns (uint8) {
return parseTimestamp(timestamp).day;
}
function getHour(uint timestamp) internal pure returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
function getMinute(uint timestamp) internal pure returns (uint8) {
return uint8((timestamp / 60) % 60);
}
function getSecond(uint timestamp) internal pure returns (uint8) {
return uint8(timestamp % 60);
}
function getWeekday(uint timestamp) internal pure returns (uint8) {
return uint8((timestamp / DAY_IN_SECONDS + 4) % 7);
}
function toTimestamp(uint16 year, uint8 month, uint8 day) internal pure returns (uint timestamp) {
return toTimestamp(year, month, day, 0, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) internal pure returns (uint timestamp) {
return toTimestamp(year, month, day, hour, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute)
internal
pure
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)
internal
pure
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;
}
}
pragma solidity ^0.5.8;
/*
* 'Bolton Holding Group' CORPORATE BOND Subscription contract
*
* Token : Bolton Coin (BFCL)
* Interest rate : 22% yearly
* Duration subscription: 24 months
*
* Copyright (C) 2019 Raffaele Bini - 5esse Informatica (https://www.5esse.it)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./IERC20.sol";
import "./Whitelist.sol";
import "./Vault.sol";
import "./PriceManagerRole.sol";
import "./DateTime.sol";
contract DepositPlan is Ownable, ReentrancyGuard, PriceManagerRole, DateTime {
using SafeMath for uint;
enum Currency {BFCL, EURO}
event AddInvestor(address indexed investor);
event CloseAccount(address indexed investor);
event InvestorDeposit(address indexed investor, uint bfclAmount, uint euroAmount, uint depositTime);
event Reinvest(
uint oldBfcl,
uint oldEuro,
uint oldLastWithdrawTime,
uint bfclDividends,
uint euroDividends,
uint lastWithdrawTime
);
event DeleteDebt(address indexed investor, uint index);
event DeleteDeposit(address indexed investor, uint index);
event AddDebt(address indexed investor, uint bfclDebt, uint euroDebt);
uint internal constant RATE_MULTIPLIER = 10 ** 18;
uint internal constant MIN_INVESTMENT_EURO_CENT = 50000 * RATE_MULTIPLIER; // 50k EURO in cents
uint internal constant MIN_REPLENISH_EURO_CENT = 1000 * RATE_MULTIPLIER; // 1k EURO in cents
uint internal HUNDRED_PERCENTS = 10000; // 100%
uint internal PERCENT_PER_YEAR = 2200; // 22%
IERC20 public bfclToken;
IERC20 public euroToken;
Whitelist public whitelist;
address public tokensWallet;
uint public bfclEuroRateFor72h; // 1 EUR = bfclEuroRateFor72h BFCL / 10^18
bool public isStopped;
mapping(address => Account) public accounts;
mapping(address => Deposit[]) public deposits;
mapping(address => Debt[]) public debts;
struct Account {
Vault vault;
uint firstDepositTimestamp;
uint stopTime;
}
struct Deposit {
uint bfcl;
uint euro;
uint lastWithdrawTime;
}
struct Debt {
uint bfcl;
uint euro;
}
constructor(IERC20 _bfclToken, Whitelist _whitelist, address _tokensWallet, uint _initialBfclEuroRateFor72h) public {
bfclToken = _bfclToken;
whitelist = _whitelist;
tokensWallet = _tokensWallet;
bfclEuroRateFor72h = _initialBfclEuroRateFor72h;
}
modifier onlyIfWhitelisted() {
require(whitelist.isWhitelisted(msg.sender), "Not whitelisted");
_;
}
// reverts ETH transfers
function() external {
revert();
}
// reverts erc223 token transfers
function tokenFallback(address, uint, bytes calldata) external pure {
revert();
}
function transferErc20(IERC20 _token, address _to, uint _value) external onlyOwner nonReentrant {
_token.transfer(_to, _value);
}
function transferBfcl(address _to, uint _value) external onlyOwner nonReentrant {
bfclToken.transfer(_to, _value);
}
function stop() external onlyOwner {
isStopped = true;
}
function invest(uint _bfclAmount) external onlyIfWhitelisted nonReentrant {
require(!isStopped, "Contract stopped. You can no longer invest.");
uint bfclAmount;
uint euroAmount;
address investor = msg.sender;
Account storage account = accounts[investor];
if (account.vault == Vault(0)) {
// first deposit
bfclAmount = _bfclAmount;
euroAmount = _bfclAmount.mul(RATE_MULTIPLIER).div(bfclEuroRateFor72h);
require(euroAmount >= MIN_INVESTMENT_EURO_CENT, "Should be more than minimum");
account.vault = new Vault(investor, bfclToken);
account.firstDepositTimestamp = now;
account.stopTime = now + 730 days;
emit AddInvestor(investor);
} else {
// replenish
require(now < account.stopTime, "2 years have passed. You can no longer replenish.");
uint oneKEuroInBfcl = bfclEuroRateFor72h.mul(MIN_REPLENISH_EURO_CENT).div(RATE_MULTIPLIER);
uint times = _bfclAmount.div(oneKEuroInBfcl);
bfclAmount = times.mul(oneKEuroInBfcl);
euroAmount = times.mul(MIN_REPLENISH_EURO_CENT);
require(euroAmount >= MIN_REPLENISH_EURO_CENT, "Should be more than minimum");
}
require(bfclToken.allowance(investor, address(this)) >= bfclAmount, "Allowance should not be less than amount");
bfclToken.transferFrom(investor, address(account.vault), bfclAmount);
deposits[investor].push(Deposit(bfclAmount, euroAmount, now));
emit InvestorDeposit(investor, bfclAmount, euroAmount, now);
}
function withdraw() external nonReentrant {
address investor = msg.sender;
Account storage account = accounts[investor];
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
uint result;
result += _tryToWithdrawDividends(investor, account, currency);
result += _tryToWithdrawDebts(investor, currency);
require(result > 0, "Nothing to withdraw");
_checkAndCloseAccount(investor);
}
function _tryToWithdrawDividends(address _investor, Account storage _account, Currency _currency)
internal
returns (uint result)
{
if (isInIntervals(now) || now >= _account.stopTime) {
uint depositCount = deposits[_investor].length;
if (depositCount > 0) {
for (uint i = 0; i < depositCount; i++) {
if (_withdrawOneDividend(_investor, _account, _currency, i)) {
result++;
}
}
if (now >= _account.stopTime) {
for (uint i = depositCount; i > 0; i--) {
_withdrawDeposit(_investor, i - 1);
}
}
}
}
}
function _tryToWithdrawDebts(address _investor, Currency _currency) internal returns (uint result) {
uint debtCount = debts[_investor].length;
if (debtCount > 0) {
for (uint i = 0; i < debtCount; i++) {
if (_withdrawOneDebt(_investor, _currency, i)) {
result++;
}
}
for (uint i = debtCount; i > 0; i--) {
_deleteDebt(_investor, i - 1);
}
}
}
function _withdrawDeposit(address _investor, uint _index) internal {
Vault vault = accounts[_investor].vault;
Deposit storage deposit = deposits[_investor][_index];
uint mustPay = deposit.bfcl;
uint toPayFromVault;
uint toPayFromWallet;
if (vault.getBalance() >= mustPay) {
toPayFromVault = mustPay;
} else {
toPayFromVault = vault.getBalance();
toPayFromWallet = mustPay.sub(toPayFromVault);
}
_deleteDeposit(_investor, _index);
if (toPayFromVault > 0) {
vault.withdrawToInvestor(toPayFromVault);
}
if (toPayFromWallet > 0) {
_send(_investor, toPayFromWallet, 0, Currency.BFCL);
}
}
function withdrawDividends() external nonReentrant {
address investor = msg.sender;
Account storage account = accounts[investor];
require(isInIntervals(now) || now >= account.stopTime, "Should be in interval or after 2 years");
require(deposits[investor].length > 0, "There is no deposits for your address");
uint result;
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
result += _tryToWithdrawDividends(investor, account, currency);
require(result > 0, "Nothing to withdraw");
_checkAndCloseAccount(investor);
}
function withdrawOneDividend(uint index) external nonReentrant {
address investor = msg.sender;
Account storage account = accounts[investor];
require(isInIntervals(now) || now >= account.stopTime, "Should be in interval or after 2 years");
require(deposits[investor].length > 0, "There is no deposits for your address");
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
require(_withdrawOneDividend(investor, account, currency, index), "Nothing to withdraw");
if (now >= account.stopTime) {
_withdrawDeposit(investor, index);
}
_checkAndCloseAccount(investor);
}
function withdrawDebts() external nonReentrant {
address investor = msg.sender;
require(debts[investor].length > 0, "There is no deposits for your address");
uint result;
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
result += _tryToWithdrawDebts(investor, currency);
require(result > 0, "Nothing to withdraw");
_checkAndCloseAccount(investor);
}
function withdrawOneDebt(uint index) external nonReentrant {
address investor = msg.sender;
require(debts[investor].length > 0, "There is no deposits for your address");
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
require(_withdrawOneDebt(investor, currency, index), "Nothing to withdraw");
_deleteDebt(investor, index);
_checkAndCloseAccount(investor);
}
function setBfclEuroRateFor72h(uint _rate) public onlyPriceManager {
bfclEuroRateFor72h = _rate;
}
function switchToBfcl() public onlyOwner {
require(address(euroToken) != address(0), "You are already using BFCL");
euroToken = IERC20(address(0));
}
function switchToEuro(IERC20 _euro) public onlyOwner {
require(address(_euro) != address(euroToken), "Trying to change euro token to same address");
euroToken = _euro;
}
function calculateDividendsForTimestamp(address _investor, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
Account storage account = accounts[_investor];
uint withdrawingTimestamp = _findIntervalStart(account, _timestamp);
for (uint i = 0; i < deposits[_investor].length; i++) {
(uint bfclDiv, uint euroDiv) = _calculateDividendForTimestamp(_investor, withdrawingTimestamp, i);
bfcl = bfcl.add(bfclDiv);
euro = euro.add(euroDiv);
}
if (withdrawingTimestamp >= account.stopTime) {
bfcl = bfcl.sub(account.vault.getBalance());
}
}
function calculateGroupDividendsForTimestamp(address[] memory _investors, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
for (uint i = 0; i < _investors.length; i++) {
address investor = _investors[i];
Account storage account = accounts[investor];
uint withdrawingTimestamp = _findIntervalStart(account, _timestamp);
for (uint d = 0; d < deposits[investor].length; d++) {
(uint bfclDiv, uint euroDiv) = _calculateDividendForTimestamp(investor, withdrawingTimestamp, d);
bfcl = bfcl.add(bfclDiv);
euro = euro.add(euroDiv);
}
if (withdrawingTimestamp >= account.stopTime) {
bfcl = bfcl.sub(account.vault.getBalance());
}
}
}
function calculateDividendsWithDebtsForTimestamp(address _investor, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
(bfcl, euro) = calculateDividendsForTimestamp(_investor, _timestamp);
for (uint d = 0; d < debts[_investor].length; d++) {
Debt storage debt = debts[_investor][d];
bfcl = bfcl.add(debt.bfcl);
euro = euro.add(debt.euro);
}
}
function calculateGroupDividendsWithDebtsForTimestamp(address[] memory _investors, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
(bfcl, euro) = calculateGroupDividendsForTimestamp(_investors, _timestamp);
for (uint i = 0; i < _investors.length; i++) {
address investor = _investors[i];
for (uint d = 0; d < debts[investor].length; d++) {
Debt storage debt = debts[investor][d];
bfcl = bfcl.add(debt.bfcl);
euro = euro.add(debt.euro);
}
}
}
function isInIntervals(uint _timestamp) public pure returns (bool) {
uint8[4] memory months = [1, 4, 7, 10];
_DateTime memory dt = parseTimestamp(_timestamp);
for (uint i = 0; i < months.length; i++) {
if (dt.month == months[i]) {
return 1 <= dt.day && dt.day <= 5;
}
}
return false;
}
function _getNextDate(uint _timestamp) internal pure returns (uint) {
_DateTime memory dt = parseTimestamp(_timestamp);
uint16 year;
uint8 month;
uint8[4] memory months = [1, 4, 7, 10];
for (uint i = months.length; i > 0; --i) {
if (dt.month >= months[i - 1]) {
if (i == months.length) {
year = dt.year + 1;
month = months[0];
} else {
year = dt.year;
month = months[i];
}
break;
}
}
return toTimestamp(year, month, 1);
}
// implies that the timestamp is exactly in any of the intervals or after stopTime
function _findIntervalStart(Account storage _account, uint _timestamp) internal view returns (uint) {
if (_timestamp >= _account.stopTime) {
return _account.stopTime;
} else {
_DateTime memory dt = parseTimestamp(_timestamp);
return toTimestamp(dt.year, dt.month, 1);
}
}
function _getBalance(Currency _currency) internal view returns (uint) {
IERC20 token = _currency == Currency.BFCL ? bfclToken : euroToken;
uint balance = token.balanceOf(tokensWallet);
uint allowance = token.allowance(tokensWallet, address(this));
return balance < allowance ? balance : allowance;
}
function _checkAndCloseAccount(address _investor) internal {
bool isDepositWithdrawn = accounts[_investor].vault.getBalance() == 0;
bool isDividendsWithdrawn = deposits[_investor].length == 0;
bool isDebtsWithdrawn = debts[_investor].length == 0;
if (isDepositWithdrawn && isDividendsWithdrawn && isDebtsWithdrawn) {
delete accounts[_investor];
emit CloseAccount(_investor);
}
}
function _withdrawOneDebt(address _investor, Currency _currency, uint _index) internal returns (bool) {
Debt storage debt = debts[_investor][_index];
return _send(_investor, debt.bfcl, debt.euro, _currency);
}
function _deleteDebt(address _investor, uint _index) internal {
uint lastIndex = debts[_investor].length - 1;
if (_index == lastIndex) {
delete debts[_investor][_index];
} else {
debts[_investor][_index] = debts[_investor][lastIndex];
delete debts[_investor][lastIndex];
}
emit DeleteDebt(_investor, _index);
debts[_investor].length--;
}
function _checkAndReinvest(Deposit storage _deposit, uint _currentIntervalStart) internal {
while (true) {
uint nextDate = _getNextDate(_deposit.lastWithdrawTime);
if (nextDate >= _currentIntervalStart) {
return;
}
uint periodSeconds = nextDate.sub(_deposit.lastWithdrawTime);
(uint bfclDividends, uint euroDividends) = _calculateDividendForPeriod(_deposit, periodSeconds);
emit Reinvest(_deposit.bfcl, _deposit.euro, _deposit.lastWithdrawTime, bfclDividends, euroDividends, nextDate);
_deposit.bfcl = _deposit.bfcl.add(bfclDividends);
_deposit.euro = _deposit.euro.add(euroDividends);
_deposit.lastWithdrawTime = nextDate;
}
}
function _withdrawOneDividend(address _investor, Account storage _account, Currency _currency, uint _index)
internal
returns (bool result)
{
Deposit storage deposit = deposits[_investor][_index];
uint intervalStart = _findIntervalStart(_account, now);
if (deposit.lastWithdrawTime > intervalStart) {
return false;
}
_checkAndReinvest(deposit, intervalStart);
uint periodSeconds = intervalStart.sub(deposit.lastWithdrawTime);
deposit.lastWithdrawTime = intervalStart;
(uint bfclDividends, uint euroDividends) = _calculateDividendForPeriod(deposit, periodSeconds);
result = _send(_investor, bfclDividends, euroDividends, _currency);
}
function _deleteDeposit(address _investor, uint _index) internal {
uint lastIndex = deposits[_investor].length - 1;
if (_index == lastIndex) {
delete deposits[_investor][_index];
} else {
deposits[_investor][_index] = deposits[_investor][lastIndex];
delete deposits[_investor][lastIndex];
}
emit DeleteDeposit(_investor, _index);
deposits[_investor].length--;
}
function _calculateDividendForTimestamp(address _investor, uint _withdrawingTimestamp, uint _depositIndex)
internal
view
returns (uint bfcl, uint euro)
{
Deposit storage deposit = deposits[_investor][_depositIndex];
if (deposit.lastWithdrawTime >= _withdrawingTimestamp) {
return (0, 0);
}
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
uint b = deposit.bfcl;
uint e = deposit.euro;
// check reinvestment
uint lastWithdrawTime = deposit.lastWithdrawTime;
while (true) {
uint nextDate = _getNextDate(lastWithdrawTime);
if (nextDate >= _withdrawingTimestamp) {
break;
}
uint periodSeconds = nextDate.sub(lastWithdrawTime);
(uint bfclDividends, uint euroDividends) = _calculateDividendForPeriod(b, e, periodSeconds);
b = b.add(bfclDividends);
e = e.add(euroDividends);
lastWithdrawTime = nextDate;
}
// calculate dividends for last interval
uint periodSeconds = _withdrawingTimestamp.sub(lastWithdrawTime);
(bfcl, euro) = _calculateDividendForPeriod(b, e, periodSeconds);
if (currency == Currency.BFCL) {
euro = 0;
} else if (_withdrawingTimestamp < accounts[_investor].stopTime) {
bfcl = 0;
}
if (_withdrawingTimestamp >= accounts[_investor].stopTime) {
if (currency == Currency.BFCL) {
bfcl = bfcl.add(b);
} else {
bfcl = b;
}
}
}
function _calculateDividendForPeriod(Deposit storage _deposit, uint _periodSeconds)
internal
view
returns (uint bfcl, uint euro)
{
(bfcl, euro) = _calculateDividendForPeriod(_deposit.bfcl, _deposit.euro, _periodSeconds);
}
function _calculateDividendForPeriod(uint _bfcl, uint _euro, uint _periodSeconds)
internal
view
returns (uint bfcl, uint euro)
{
bfcl = _bfcl.mul(_periodSeconds).mul(PERCENT_PER_YEAR).div(HUNDRED_PERCENTS).div(365 days);
euro = _euro.mul(_periodSeconds).mul(PERCENT_PER_YEAR).div(HUNDRED_PERCENTS).div(365 days);
}
function _send(address _investor, uint _bfclAmount, uint _euroAmount, Currency _currency) internal returns (bool) {
if (_bfclAmount == 0 && _euroAmount == 0) {
return false;
}
uint balance = _getBalance(_currency);
if (_currency == Currency.EURO) {
balance = balance.mul(RATE_MULTIPLIER).div(10 ** euroToken.decimals());
}
uint canPay;
if ((_currency == Currency.BFCL && balance >= _bfclAmount) || (_currency == Currency.EURO && balance >= _euroAmount)) {
if (_currency == Currency.BFCL) {
canPay = _bfclAmount;
} else {
canPay = _euroAmount;
}
} else {
canPay = balance;
uint bfclDebt;
uint euroDebt;
if (_currency == Currency.BFCL) {
bfclDebt = _bfclAmount.sub(canPay);
euroDebt = bfclDebt.mul(_euroAmount).div(_bfclAmount);
} else {
euroDebt = _euroAmount.sub(canPay);
bfclDebt = euroDebt.mul(_bfclAmount).div(_euroAmount);
}
debts[_investor].push(Debt(bfclDebt, euroDebt));
emit AddDebt(_investor, bfclDebt, euroDebt);
}
if (canPay == 0) {
return true;
}
uint toPay;
IERC20 token;
if (_currency == Currency.BFCL) {
toPay = canPay;
token = bfclToken;
} else {
toPay = canPay.mul(10 ** euroToken.decimals()).div(RATE_MULTIPLIER);
token = euroToken;
}
token.transferFrom(tokensWallet, _investor, toPay);
return true;
}
}
pragma solidity ^0.5.8;
/**
* @title ERC20 interface without bool returns
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external;
function transferFrom(address from, address to, uint256 value) external;
function decimals() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
}
pragma solidity ^0.5.2;
/**
* @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.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice 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 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;
}
}
pragma solidity ^0.5.8;
import "./Roles.sol";
contract PriceManagerRole {
using Roles for Roles.Role;
event PriceManagerAdded(address indexed account);
event PriceManagerRemoved(address indexed account);
Roles.Role private managers;
constructor() internal {
_addPriceManager(msg.sender);
}
modifier onlyPriceManager() {
require(isPriceManager(msg.sender), "Only for price manager");
_;
}
function isPriceManager(address account) public view returns (bool) {
return managers.has(account);
}
function addPriceManager(address account) public onlyPriceManager {
_addPriceManager(account);
}
function renouncePriceManager() public {
_removePriceManager(msg.sender);
}
function _addPriceManager(address account) internal {
managers.add(account);
emit PriceManagerAdded(account);
}
function _removePriceManager(address account) internal {
managers.remove(account);
emit PriceManagerRemoved(account);
}
}
pragma solidity ^0.5.2;
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2Ο.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
pragma solidity ^0.5.2;
/**
* @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;
}
}
pragma solidity ^0.5.8;
import "./Ownable.sol";
import "./SafeMath.sol";
import "./IERC20.sol";
contract Vault is Ownable {
using SafeMath for uint;
address public investor;
IERC20 internal bfclToken;
constructor(address _investor, IERC20 _bfclToken) public {
investor = _investor;
bfclToken = _bfclToken;
}
// reverts erc223 transfers
function tokenFallback(address, uint, bytes calldata) external pure {
revert("ERC223 tokens not allowed in Vault");
}
function withdrawToInvestor(uint _amount) external onlyOwner returns (bool) {
bfclToken.transfer(investor, _amount);
return true;
}
function getBalance() public view returns (uint) {
return bfclToken.balanceOf(address(this));
}
}
pragma solidity ^0.5.8;
import "./Roles.sol";
import "./Ownable.sol";
contract Whitelist is Ownable {
using Roles for Roles.Role;
Roles.Role private whitelist;
event WhitelistedAddressAdded(address indexed _address);
function isWhitelisted(address _address) public view returns (bool) {
return whitelist.has(_address);
}
function addAddressToWhitelist(address _address) external onlyOwner {
_addAddressToWhitelist(_address);
}
function addAddressesToWhitelist(address[] calldata _addresses) external onlyOwner {
for (uint i = 0; i < _addresses.length; i++) {
_addAddressToWhitelist(_addresses[i]);
}
}
function _addAddressToWhitelist(address _address) internal {
whitelist.add(_address);
emit WhitelistedAddressAdded(_address);
}
}
pragma solidity ^0.5.8;
// https://github.com/pipermerriam/ethereum-datetime
contract DateTime {
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) internal pure 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) internal pure returns (uint) {
year -= 1;
return year / 4 - year / 100 + year / 400;
}
function getDaysInMonth(uint8 month, uint16 year) internal pure 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 pure returns (_DateTime memory 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);
dt.weekday = getWeekday(timestamp);
}
function getYear(uint timestamp) internal pure 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) internal pure returns (uint8) {
return parseTimestamp(timestamp).month;
}
function getDay(uint timestamp) internal pure returns (uint8) {
return parseTimestamp(timestamp).day;
}
function getHour(uint timestamp) internal pure returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
function getMinute(uint timestamp) internal pure returns (uint8) {
return uint8((timestamp / 60) % 60);
}
function getSecond(uint timestamp) internal pure returns (uint8) {
return uint8(timestamp % 60);
}
function getWeekday(uint timestamp) internal pure returns (uint8) {
return uint8((timestamp / DAY_IN_SECONDS + 4) % 7);
}
function toTimestamp(uint16 year, uint8 month, uint8 day) internal pure returns (uint timestamp) {
return toTimestamp(year, month, day, 0, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) internal pure returns (uint timestamp) {
return toTimestamp(year, month, day, hour, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute)
internal
pure
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)
internal
pure
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;
}
}
pragma solidity ^0.5.8;
/*
* 'Bolton Holding Group' CORPORATE BOND Subscription contract
*
* Token : Bolton Coin (BFCL)
* Interest rate : 22% yearly
* Duration subscription: 24 months
*
* Copyright (C) 2019 Raffaele Bini - 5esse Informatica (https://www.5esse.it)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./IERC20.sol";
import "./Whitelist.sol";
import "./Vault.sol";
import "./PriceManagerRole.sol";
import "./DateTime.sol";
contract DepositPlan is Ownable, ReentrancyGuard, PriceManagerRole, DateTime {
using SafeMath for uint;
enum Currency {BFCL, EURO}
event AddInvestor(address indexed investor);
event CloseAccount(address indexed investor);
event InvestorDeposit(address indexed investor, uint bfclAmount, uint euroAmount, uint depositTime);
event Reinvest(
uint oldBfcl,
uint oldEuro,
uint oldLastWithdrawTime,
uint bfclDividends,
uint euroDividends,
uint lastWithdrawTime
);
event DeleteDebt(address indexed investor, uint index);
event DeleteDeposit(address indexed investor, uint index);
event AddDebt(address indexed investor, uint bfclDebt, uint euroDebt);
uint internal constant RATE_MULTIPLIER = 10 ** 18;
uint internal constant MIN_INVESTMENT_EURO_CENT = 50000 * RATE_MULTIPLIER; // 50k EURO in cents
uint internal constant MIN_REPLENISH_EURO_CENT = 1000 * RATE_MULTIPLIER; // 1k EURO in cents
uint internal HUNDRED_PERCENTS = 10000; // 100%
uint internal PERCENT_PER_YEAR = 2200; // 22%
IERC20 public bfclToken;
IERC20 public euroToken;
Whitelist public whitelist;
address public tokensWallet;
uint public bfclEuroRateFor72h; // 1 EUR = bfclEuroRateFor72h BFCL / 10^18
bool public isStopped;
mapping(address => Account) public accounts;
mapping(address => Deposit[]) public deposits;
mapping(address => Debt[]) public debts;
struct Account {
Vault vault;
uint firstDepositTimestamp;
uint stopTime;
}
struct Deposit {
uint bfcl;
uint euro;
uint lastWithdrawTime;
}
struct Debt {
uint bfcl;
uint euro;
}
constructor(IERC20 _bfclToken, Whitelist _whitelist, address _tokensWallet, uint _initialBfclEuroRateFor72h) public {
bfclToken = _bfclToken;
whitelist = _whitelist;
tokensWallet = _tokensWallet;
bfclEuroRateFor72h = _initialBfclEuroRateFor72h;
}
modifier onlyIfWhitelisted() {
require(whitelist.isWhitelisted(msg.sender), "Not whitelisted");
_;
}
// reverts ETH transfers
function() external {
revert();
}
// reverts erc223 token transfers
function tokenFallback(address, uint, bytes calldata) external pure {
revert();
}
function transferErc20(IERC20 _token, address _to, uint _value) external onlyOwner nonReentrant {
_token.transfer(_to, _value);
}
function transferBfcl(address _to, uint _value) external onlyOwner nonReentrant {
bfclToken.transfer(_to, _value);
}
function stop() external onlyOwner {
isStopped = true;
}
function invest(uint _bfclAmount) external onlyIfWhitelisted nonReentrant {
require(!isStopped, "Contract stopped. You can no longer invest.");
uint bfclAmount;
uint euroAmount;
address investor = msg.sender;
Account storage account = accounts[investor];
if (account.vault == Vault(0)) {
// first deposit
bfclAmount = _bfclAmount;
euroAmount = _bfclAmount.mul(RATE_MULTIPLIER).div(bfclEuroRateFor72h);
require(euroAmount >= MIN_INVESTMENT_EURO_CENT, "Should be more than minimum");
account.vault = new Vault(investor, bfclToken);
account.firstDepositTimestamp = now;
account.stopTime = now + 730 days;
emit AddInvestor(investor);
} else {
// replenish
require(now < account.stopTime, "2 years have passed. You can no longer replenish.");
uint oneKEuroInBfcl = bfclEuroRateFor72h.mul(MIN_REPLENISH_EURO_CENT).div(RATE_MULTIPLIER);
uint times = _bfclAmount.div(oneKEuroInBfcl);
bfclAmount = times.mul(oneKEuroInBfcl);
euroAmount = times.mul(MIN_REPLENISH_EURO_CENT);
require(euroAmount >= MIN_REPLENISH_EURO_CENT, "Should be more than minimum");
}
require(bfclToken.allowance(investor, address(this)) >= bfclAmount, "Allowance should not be less than amount");
bfclToken.transferFrom(investor, address(account.vault), bfclAmount);
deposits[investor].push(Deposit(bfclAmount, euroAmount, now));
emit InvestorDeposit(investor, bfclAmount, euroAmount, now);
}
function withdraw() external nonReentrant {
address investor = msg.sender;
Account storage account = accounts[investor];
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
uint result;
result += _tryToWithdrawDividends(investor, account, currency);
result += _tryToWithdrawDebts(investor, currency);
require(result > 0, "Nothing to withdraw");
_checkAndCloseAccount(investor);
}
function _tryToWithdrawDividends(address _investor, Account storage _account, Currency _currency)
internal
returns (uint result)
{
if (isInIntervals(now) || now >= _account.stopTime) {
uint depositCount = deposits[_investor].length;
if (depositCount > 0) {
for (uint i = 0; i < depositCount; i++) {
if (_withdrawOneDividend(_investor, _account, _currency, i)) {
result++;
}
}
if (now >= _account.stopTime) {
for (uint i = depositCount; i > 0; i--) {
_withdrawDeposit(_investor, i - 1);
}
}
}
}
}
function _tryToWithdrawDebts(address _investor, Currency _currency) internal returns (uint result) {
uint debtCount = debts[_investor].length;
if (debtCount > 0) {
for (uint i = 0; i < debtCount; i++) {
if (_withdrawOneDebt(_investor, _currency, i)) {
result++;
}
}
for (uint i = debtCount; i > 0; i--) {
_deleteDebt(_investor, i - 1);
}
}
}
function _withdrawDeposit(address _investor, uint _index) internal {
Vault vault = accounts[_investor].vault;
Deposit storage deposit = deposits[_investor][_index];
uint mustPay = deposit.bfcl;
uint toPayFromVault;
uint toPayFromWallet;
if (vault.getBalance() >= mustPay) {
toPayFromVault = mustPay;
} else {
toPayFromVault = vault.getBalance();
toPayFromWallet = mustPay.sub(toPayFromVault);
}
_deleteDeposit(_investor, _index);
if (toPayFromVault > 0) {
vault.withdrawToInvestor(toPayFromVault);
}
if (toPayFromWallet > 0) {
_send(_investor, toPayFromWallet, 0, Currency.BFCL);
}
}
function withdrawDividends() external nonReentrant {
address investor = msg.sender;
Account storage account = accounts[investor];
require(isInIntervals(now) || now >= account.stopTime, "Should be in interval or after 2 years");
require(deposits[investor].length > 0, "There is no deposits for your address");
uint result;
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
result += _tryToWithdrawDividends(investor, account, currency);
require(result > 0, "Nothing to withdraw");
_checkAndCloseAccount(investor);
}
function withdrawOneDividend(uint index) external nonReentrant {
address investor = msg.sender;
Account storage account = accounts[investor];
require(isInIntervals(now) || now >= account.stopTime, "Should be in interval or after 2 years");
require(deposits[investor].length > 0, "There is no deposits for your address");
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
require(_withdrawOneDividend(investor, account, currency, index), "Nothing to withdraw");
if (now >= account.stopTime) {
_withdrawDeposit(investor, index);
}
_checkAndCloseAccount(investor);
}
function withdrawDebts() external nonReentrant {
address investor = msg.sender;
require(debts[investor].length > 0, "There is no deposits for your address");
uint result;
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
result += _tryToWithdrawDebts(investor, currency);
require(result > 0, "Nothing to withdraw");
_checkAndCloseAccount(investor);
}
function withdrawOneDebt(uint index) external nonReentrant {
address investor = msg.sender;
require(debts[investor].length > 0, "There is no deposits for your address");
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
require(_withdrawOneDebt(investor, currency, index), "Nothing to withdraw");
_deleteDebt(investor, index);
_checkAndCloseAccount(investor);
}
function setBfclEuroRateFor72h(uint _rate) public onlyPriceManager {
bfclEuroRateFor72h = _rate;
}
function switchToBfcl() public onlyOwner {
require(address(euroToken) != address(0), "You are already using BFCL");
euroToken = IERC20(address(0));
}
function switchToEuro(IERC20 _euro) public onlyOwner {
require(address(_euro) != address(euroToken), "Trying to change euro token to same address");
euroToken = _euro;
}
function calculateDividendsForTimestamp(address _investor, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
Account storage account = accounts[_investor];
uint withdrawingTimestamp = _findIntervalStart(account, _timestamp);
for (uint i = 0; i < deposits[_investor].length; i++) {
(uint bfclDiv, uint euroDiv) = _calculateDividendForTimestamp(_investor, withdrawingTimestamp, i);
bfcl = bfcl.add(bfclDiv);
euro = euro.add(euroDiv);
}
if (withdrawingTimestamp >= account.stopTime) {
bfcl = bfcl.sub(account.vault.getBalance());
}
}
function calculateGroupDividendsForTimestamp(address[] memory _investors, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
for (uint i = 0; i < _investors.length; i++) {
address investor = _investors[i];
Account storage account = accounts[investor];
uint withdrawingTimestamp = _findIntervalStart(account, _timestamp);
for (uint d = 0; d < deposits[investor].length; d++) {
(uint bfclDiv, uint euroDiv) = _calculateDividendForTimestamp(investor, withdrawingTimestamp, d);
bfcl = bfcl.add(bfclDiv);
euro = euro.add(euroDiv);
}
if (withdrawingTimestamp >= account.stopTime) {
bfcl = bfcl.sub(account.vault.getBalance());
}
}
}
function calculateDividendsWithDebtsForTimestamp(address _investor, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
(bfcl, euro) = calculateDividendsForTimestamp(_investor, _timestamp);
for (uint d = 0; d < debts[_investor].length; d++) {
Debt storage debt = debts[_investor][d];
bfcl = bfcl.add(debt.bfcl);
euro = euro.add(debt.euro);
}
}
function calculateGroupDividendsWithDebtsForTimestamp(address[] memory _investors, uint _timestamp)
public
view
returns (uint bfcl, uint euro)
{
(bfcl, euro) = calculateGroupDividendsForTimestamp(_investors, _timestamp);
for (uint i = 0; i < _investors.length; i++) {
address investor = _investors[i];
for (uint d = 0; d < debts[investor].length; d++) {
Debt storage debt = debts[investor][d];
bfcl = bfcl.add(debt.bfcl);
euro = euro.add(debt.euro);
}
}
}
function isInIntervals(uint _timestamp) public pure returns (bool) {
uint8[4] memory months = [1, 4, 7, 10];
_DateTime memory dt = parseTimestamp(_timestamp);
for (uint i = 0; i < months.length; i++) {
if (dt.month == months[i]) {
return 1 <= dt.day && dt.day <= 5;
}
}
return false;
}
function _getNextDate(uint _timestamp) internal pure returns (uint) {
_DateTime memory dt = parseTimestamp(_timestamp);
uint16 year;
uint8 month;
uint8[4] memory months = [1, 4, 7, 10];
for (uint i = months.length; i > 0; --i) {
if (dt.month >= months[i - 1]) {
if (i == months.length) {
year = dt.year + 1;
month = months[0];
} else {
year = dt.year;
month = months[i];
}
break;
}
}
return toTimestamp(year, month, 1);
}
// implies that the timestamp is exactly in any of the intervals or after stopTime
function _findIntervalStart(Account storage _account, uint _timestamp) internal view returns (uint) {
if (_timestamp >= _account.stopTime) {
return _account.stopTime;
} else {
_DateTime memory dt = parseTimestamp(_timestamp);
return toTimestamp(dt.year, dt.month, 1);
}
}
function _getBalance(Currency _currency) internal view returns (uint) {
IERC20 token = _currency == Currency.BFCL ? bfclToken : euroToken;
uint balance = token.balanceOf(tokensWallet);
uint allowance = token.allowance(tokensWallet, address(this));
return balance < allowance ? balance : allowance;
}
function _checkAndCloseAccount(address _investor) internal {
bool isDepositWithdrawn = accounts[_investor].vault.getBalance() == 0;
bool isDividendsWithdrawn = deposits[_investor].length == 0;
bool isDebtsWithdrawn = debts[_investor].length == 0;
if (isDepositWithdrawn && isDividendsWithdrawn && isDebtsWithdrawn) {
delete accounts[_investor];
emit CloseAccount(_investor);
}
}
function _withdrawOneDebt(address _investor, Currency _currency, uint _index) internal returns (bool) {
Debt storage debt = debts[_investor][_index];
return _send(_investor, debt.bfcl, debt.euro, _currency);
}
function _deleteDebt(address _investor, uint _index) internal {
uint lastIndex = debts[_investor].length - 1;
if (_index == lastIndex) {
delete debts[_investor][_index];
} else {
debts[_investor][_index] = debts[_investor][lastIndex];
delete debts[_investor][lastIndex];
}
emit DeleteDebt(_investor, _index);
debts[_investor].length--;
}
function _checkAndReinvest(Deposit storage _deposit, uint _currentIntervalStart) internal {
while (true) {
uint nextDate = _getNextDate(_deposit.lastWithdrawTime);
if (nextDate >= _currentIntervalStart) {
return;
}
uint periodSeconds = nextDate.sub(_deposit.lastWithdrawTime);
(uint bfclDividends, uint euroDividends) = _calculateDividendForPeriod(_deposit, periodSeconds);
emit Reinvest(_deposit.bfcl, _deposit.euro, _deposit.lastWithdrawTime, bfclDividends, euroDividends, nextDate);
_deposit.bfcl = _deposit.bfcl.add(bfclDividends);
_deposit.euro = _deposit.euro.add(euroDividends);
_deposit.lastWithdrawTime = nextDate;
}
}
function _withdrawOneDividend(address _investor, Account storage _account, Currency _currency, uint _index)
internal
returns (bool result)
{
Deposit storage deposit = deposits[_investor][_index];
uint intervalStart = _findIntervalStart(_account, now);
if (deposit.lastWithdrawTime > intervalStart) {
return false;
}
_checkAndReinvest(deposit, intervalStart);
uint periodSeconds = intervalStart.sub(deposit.lastWithdrawTime);
deposit.lastWithdrawTime = intervalStart;
(uint bfclDividends, uint euroDividends) = _calculateDividendForPeriod(deposit, periodSeconds);
result = _send(_investor, bfclDividends, euroDividends, _currency);
}
function _deleteDeposit(address _investor, uint _index) internal {
uint lastIndex = deposits[_investor].length - 1;
if (_index == lastIndex) {
delete deposits[_investor][_index];
} else {
deposits[_investor][_index] = deposits[_investor][lastIndex];
delete deposits[_investor][lastIndex];
}
emit DeleteDeposit(_investor, _index);
deposits[_investor].length--;
}
function _calculateDividendForTimestamp(address _investor, uint _withdrawingTimestamp, uint _depositIndex)
internal
view
returns (uint bfcl, uint euro)
{
Deposit storage deposit = deposits[_investor][_depositIndex];
if (deposit.lastWithdrawTime >= _withdrawingTimestamp) {
return (0, 0);
}
Currency currency = address(euroToken) == address(0) ? Currency.BFCL : Currency.EURO;
uint b = deposit.bfcl;
uint e = deposit.euro;
// check reinvestment
uint lastWithdrawTime = deposit.lastWithdrawTime;
while (true) {
uint nextDate = _getNextDate(lastWithdrawTime);
if (nextDate >= _withdrawingTimestamp) {
break;
}
uint periodSeconds = nextDate.sub(lastWithdrawTime);
(uint bfclDividends, uint euroDividends) = _calculateDividendForPeriod(b, e, periodSeconds);
b = b.add(bfclDividends);
e = e.add(euroDividends);
lastWithdrawTime = nextDate;
}
// calculate dividends for last interval
uint periodSeconds = _withdrawingTimestamp.sub(lastWithdrawTime);
(bfcl, euro) = _calculateDividendForPeriod(b, e, periodSeconds);
if (currency == Currency.BFCL) {
euro = 0;
} else if (_withdrawingTimestamp < accounts[_investor].stopTime) {
bfcl = 0;
}
if (_withdrawingTimestamp >= accounts[_investor].stopTime) {
if (currency == Currency.BFCL) {
bfcl = bfcl.add(b);
} else {
bfcl = b;
}
}
}
function _calculateDividendForPeriod(Deposit storage _deposit, uint _periodSeconds)
internal
view
returns (uint bfcl, uint euro)
{
(bfcl, euro) = _calculateDividendForPeriod(_deposit.bfcl, _deposit.euro, _periodSeconds);
}
function _calculateDividendForPeriod(uint _bfcl, uint _euro, uint _periodSeconds)
internal
view
returns (uint bfcl, uint euro)
{
bfcl = _bfcl.mul(_periodSeconds).mul(PERCENT_PER_YEAR).div(HUNDRED_PERCENTS).div(365 days);
euro = _euro.mul(_periodSeconds).mul(PERCENT_PER_YEAR).div(HUNDRED_PERCENTS).div(365 days);
}
function _send(address _investor, uint _bfclAmount, uint _euroAmount, Currency _currency) internal returns (bool) {
if (_bfclAmount == 0 && _euroAmount == 0) {
return false;
}
uint balance = _getBalance(_currency);
if (_currency == Currency.EURO) {
balance = balance.mul(RATE_MULTIPLIER).div(10 ** euroToken.decimals());
}
uint canPay;
if ((_currency == Currency.BFCL && balance >= _bfclAmount) || (_currency == Currency.EURO && balance >= _euroAmount)) {
if (_currency == Currency.BFCL) {
canPay = _bfclAmount;
} else {
canPay = _euroAmount;
}
} else {
canPay = balance;
uint bfclDebt;
uint euroDebt;
if (_currency == Currency.BFCL) {
bfclDebt = _bfclAmount.sub(canPay);
euroDebt = bfclDebt.mul(_euroAmount).div(_bfclAmount);
} else {
euroDebt = _euroAmount.sub(canPay);
bfclDebt = euroDebt.mul(_bfclAmount).div(_euroAmount);
}
debts[_investor].push(Debt(bfclDebt, euroDebt));
emit AddDebt(_investor, bfclDebt, euroDebt);
}
if (canPay == 0) {
return true;
}
uint toPay;
IERC20 token;
if (_currency == Currency.BFCL) {
toPay = canPay;
token = bfclToken;
} else {
toPay = canPay.mul(10 ** euroToken.decimals()).div(RATE_MULTIPLIER);
token = euroToken;
}
token.transferFrom(tokensWallet, _investor, toPay);
return true;
}
}
pragma solidity ^0.5.8;
/**
* @title ERC20 interface without bool returns
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external;
function transferFrom(address from, address to, uint256 value) external;
function decimals() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
}
pragma solidity ^0.5.2;
/**
* @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.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice 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 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;
}
}
pragma solidity ^0.5.8;
import "./Roles.sol";
contract PriceManagerRole {
using Roles for Roles.Role;
event PriceManagerAdded(address indexed account);
event PriceManagerRemoved(address indexed account);
Roles.Role private managers;
constructor() internal {
_addPriceManager(msg.sender);
}
modifier onlyPriceManager() {
require(isPriceManager(msg.sender), "Only for price manager");
_;
}
function isPriceManager(address account) public view returns (bool) {
return managers.has(account);
}
function addPriceManager(address account) public onlyPriceManager {
_addPriceManager(account);
}
function renouncePriceManager() public {
_removePriceManager(msg.sender);
}
function _addPriceManager(address account) internal {
managers.add(account);
emit PriceManagerAdded(account);
}
function _removePriceManager(address account) internal {
managers.remove(account);
emit PriceManagerRemoved(account);
}
}
pragma solidity ^0.5.2;
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2Ο.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
pragma solidity ^0.5.2;
/**
* @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;
}
}
pragma solidity ^0.5.8;
import "./Ownable.sol";
import "./SafeMath.sol";
import "./IERC20.sol";
contract Vault is Ownable {
using SafeMath for uint;
address public investor;
IERC20 internal bfclToken;
constructor(address _investor, IERC20 _bfclToken) public {
investor = _investor;
bfclToken = _bfclToken;
}
// reverts erc223 transfers
function tokenFallback(address, uint, bytes calldata) external pure {
revert("ERC223 tokens not allowed in Vault");
}
function withdrawToInvestor(uint _amount) external onlyOwner returns (bool) {
bfclToken.transfer(investor, _amount);
return true;
}
function getBalance() public view returns (uint) {
return bfclToken.balanceOf(address(this));
}
}
pragma solidity ^0.5.8;
import "./Roles.sol";
import "./Ownable.sol";
contract Whitelist is Ownable {
using Roles for Roles.Role;
Roles.Role private whitelist;
event WhitelistedAddressAdded(address indexed _address);
function isWhitelisted(address _address) public view returns (bool) {
return whitelist.has(_address);
}
function addAddressToWhitelist(address _address) external onlyOwner {
_addAddressToWhitelist(_address);
}
function addAddressesToWhitelist(address[] calldata _addresses) external onlyOwner {
for (uint i = 0; i < _addresses.length; i++) {
_addAddressToWhitelist(_addresses[i]);
}
}
function _addAddressToWhitelist(address _address) internal {
whitelist.add(_address);
emit WhitelistedAddressAdded(_address);
}
}
| reverts erc223 transfers | function tokenFallback(address, uint, bytes calldata) external pure {
revert("ERC223 tokens not allowed in Vault");
}
| 13,048,609 |
./partial_match/56/0x55441C50a1aDa087D41070dF99d9570a9913e020/sources/MasterChef.sol | Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance | function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "NOOM::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 11,142,878 |
./partial_match/42/0x098F3795ebc7D9533392347BdCb610Cb0D4DF338/sources/WyAttackV1.sol | Compound ε½θΏcERC20 θ΅εERC20 amount=ε½θΏcERC20ηζ°ι amount=θ¦θ΅εηERC20ηζ°ι | function redeemCErc20Tokens(uint256 amount, bool redeemType, address cErc20Contract) public {
CErc20 cToken = CErc20(cErc20Contract);
uint256 redeemResult;
if (redeemType == true) {
redeemResult = cToken.redeem(amount);
redeemResult = cToken.redeemUnderlying(amount);
}
require(redeemResult==0, "redeemCErc20Tokens error");
}
| 3,418,133 |
pragma solidity ^0.4.18;
import './FloatMath.sol';
contract Tester {
FloatMath floatLib;
// using FloatMath for bytes32;
// using FloatMath for uint256[3];
// bytes32 public res;
// uint256 constant public SIGNIF_BITS = 236;
// uint256 constant public EXP_BITS = 19;
// uint256 constant public SIGN_BITS = 1;
// uint256 constant public EXP_MIN = 0;
// uint256 constant public EXP_BIAS = 262143;
// uint256 constant public EXP_MAX = 524287;
// uint256 constant public SIGNIF_MAX = (uint256(2) << (SIGNIF_BITS)) - 1;
// uint256 constant public SIGNIF_MIN = (uint256(1) << SIGNIF_BITS);
// bytes32 constant public SIGNIF_MAX_BYTES = bytes32(SIGNIF_MAX);
// bytes32 constant public SIGNIF_MIN_BYTES = bytes32(SIGNIF_MIN);
function testIntToFloat(int256 a) public view returns (bytes32 result) {
result = floatLib.initFromInt(a);
return result;
}
function testBytesToArray(bytes32 a) public view returns (uint256[3] result) {
// result = a.toArray();
floatLib.toArray(a);
return result;
}
function testAddBytes(bytes32 a, bytes32 b) public view returns (bytes32 result) {
result = floatLib.add(a,b);
return result;
}
function testSubBytes(bytes32 a, bytes32 b) public view returns (bytes32 result) {
result = floatLib.sub(a,b);
return result;
}
function testMulBytes(bytes32 a, bytes32 b) public view returns (bytes32 result) {
result = floatLib.mul(a,b);
return result;
}
function testDivBytes(bytes32 a, bytes32 b) public view returns (bytes32 result) {
result = floatLib.div(a,b);
return result;
}
function testLog2Bytes(bytes32 a) public view returns (bytes32 result) {
result = floatLib.log2bytes(a);
return result;
}
function testFastInvSqrtBytes(bytes32 a) public view returns (bytes32 result) {
result = floatLib.fastInvSqrt(a);
return result;
}
function Tester(address _flib) public {
floatLib = FloatMath(_flib);
}
} | result = a.toArray(); | function testBytesToArray(bytes32 a) public view returns (uint256[3] result) {
floatLib.toArray(a);
return result;
}
| 1,828,153 |
./partial_match/1/0x45c00508C14601fd1C1e296eB3C0e3eEEdCa45D0/sources/contracts/interfaces/ILendingPoolAddressesProviderV2.sol | LendingPoolAddressesProvider contract Main registry of addresses part of or connected to the protocol, including permissioned roles - Acting also as factory of proxies and admin of those, so with right to change its implementations - Owned by the Aave Governance Aave/ | interface ILendingPoolAddressesProviderV2 {
event MarketIdSet(string newMarketId);
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
pragma solidity ^0.6.10;
}
| 9,182,592 |
./partial_match/42/0xe29fEfa1ECD4b1Ca55deC29A7EfDBc622998FD99/sources/GebUniswapV2MultiCollateralKeeperFlashProxy.sol | --- Core Bidding and Settling Logic --- Liquidates an underwater SAFE and settles the auction right away It will revert for protected safes (those that have saviours), these need to be liquidated through the LiquidationEngine collateralJoin Join address for a collateral type safe A SAFE's ID return auction Auction ID | function liquidateAndSettleSAFE(CollateralJoinLike collateralJoin, address safe) public returns (uint auction) {
collateralType = collateralJoin.collateralType();
if (liquidationEngine.safeSaviours(liquidationEngine.chosenSAFESaviour(collateralType, safe)) == 1) {
require (liquidationEngine.chosenSAFESaviour(collateralType, safe) == address(0),
"GebUniswapV2MultiCollateralKeeperFlashProxy/safe-is-protected");
}
auction = liquidationEngine.liquidateSAFE(collateralType, safe);
settleAuction(collateralJoin, auction);
}
| 3,448,357 |
./full_match/1/0x13dD6168C0027E75FE76AEA000e9e742C862a281/sources/contracts/messaging/libraries/DomainIndexer.sol | Validate given domains and connectors arrays are correct (i.e. they mirror what is currently saved in storage). Reverts if domains or connectors do not match, including ordering. _domains The given domains array to check. _connectors The given connectors array to check./ Sanity check: arguments are same length. Validate that given domains match the current array in storage. Validate that given connectors match the current array in storage. | function validateDomains(uint32[] calldata _domains, address[] calldata _connectors) public view {
require(_domains.length == _connectors.length, "!matching length");
require(keccak256(abi.encode(_domains)) == domainsHash, "!domains");
require(keccak256(abi.encode(_connectors)) == connectorsHash, "!connectors");
}
| 9,801,356 |
pragma solidity 0.4.24;
// File: contracts\lib\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 public 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;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "only owner is able to call this function");
_;
}
/**
* @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;
}
}
// File: contracts\lib\Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: contracts\lib\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
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 a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts\lib\Crowdsale.sol
/**
* @title Crowdsale - modified from zeppelin-solidity library
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
// event for token purchase logging
// purchaser who paid for the tokens
// beneficiary who got the tokens
// value weis paid for purchase
// amount amount of tokens purchased
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function initCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(
startTime == 0 && endTime == 0 && rate == 0 && wallet == address(0),
"Global variables must be empty when initializing crowdsale!"
);
require(_startTime >= now, "_startTime must be more than current time!");
require(_endTime >= _startTime, "_endTime must be more than _startTime!");
require(_wallet != address(0), "_wallet parameter must not be empty!");
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
}
// File: contracts\lib\FinalizableCrowdsale.sol
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @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 {
}
}
// File: contracts\lib\ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
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);
}
// File: contracts\lib\BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @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);
emit 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];
}
}
// File: contracts\lib\ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
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);
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts\lib\StandardToken.sol
/**
* @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);
emit 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;
emit 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) {
return allowed[_owner][_spender];
}
/**
* @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
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
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
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts\lib\MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev 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(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: contracts\lib\PausableToken.sol
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: contracts\CompanyToken.sol
/**
* @title CompanyToken contract - ERC20 compatible token contract with customized token parameters.
* @author Gustavo Guimaraes - <[email protected]>
*/
contract CompanyToken is PausableToken, MintableToken {
string public name;
string public symbol;
uint8 public decimals;
/**
* @dev Contract constructor function
* @param _name Token name
* @param _symbol Token symbol - up to 4 characters
* @param _decimals Decimals for token
*/
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
pause();
}
}
// File: contracts\Whitelist.sol
/**
* @title Whitelist - crowdsale whitelist contract
* @author Gustavo Guimaraes - <[email protected]>
*/
contract Whitelist is Ownable {
mapping(address => bool) public allowedAddresses;
event WhitelistUpdated(uint256 timestamp, string operation, address indexed member);
/**
* @dev Adds single address to whitelist.
* @param _address Address to be added to the whitelist
*/
function addToWhitelist(address _address) external onlyOwner {
allowedAddresses[_address] = true;
emit WhitelistUpdated(now, "Added", _address);
}
/**
* @dev add various whitelist addresses
* @param _addresses Array of ethereum addresses
*/
function addManyToWhitelist(address[] _addresses) external onlyOwner {
for (uint256 i = 0; i < _addresses.length; i++) {
allowedAddresses[_addresses[i]] = true;
emit WhitelistUpdated(now, "Added", _addresses[i]);
}
}
/**
* @dev remove whitelist addresses
* @param _addresses Array of ethereum addresses
*/
function removeManyFromWhitelist(address[] _addresses) public onlyOwner {
for (uint256 i = 0; i < _addresses.length; i++) {
allowedAddresses[_addresses[i]] = false;
emit WhitelistUpdated(now, "Removed", _addresses[i]);
}
}
}
// File: contracts\TokenSaleInterface.sol
/**
* @title TokenSale contract interface
*/
interface TokenSaleInterface {
function init
(
uint256 _startTime,
uint256 _endTime,
address _whitelist,
address _starToken,
address _companyToken,
uint256 _rate,
uint256 _starRate,
address _wallet,
uint256 _crowdsaleCap,
bool _isWeiAccepted
)
external;
}
// File: contracts\TokenSale.sol
/**
* @title Token Sale contract - crowdsale of company tokens.
* @author Gustavo Guimaraes - <[email protected]>
*/
contract TokenSale is FinalizableCrowdsale, Pausable {
uint256 public crowdsaleCap;
// amount of raised money in STAR
uint256 public starRaised;
uint256 public starRate;
address public initialTokenOwner;
bool public isWeiAccepted;
// external contracts
Whitelist public whitelist;
StandardToken public starToken;
// The token being sold
MintableToken public tokenOnSale;
event TokenRateChanged(uint256 previousRate, uint256 newRate);
event TokenStarRateChanged(uint256 previousStarRate, uint256 newStarRate);
event TokenPurchaseWithStar(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @dev initialization function
* @param _startTime The timestamp of the beginning of the crowdsale
* @param _endTime Timestamp when the crowdsale will finish
* @param _whitelist contract containing the whitelisted addresses
* @param _starToken STAR token contract address
* @param _companyToken ERC20 CompanyToken contract address
* @param _rate The token rate per ETH
* @param _starRate The token rate per STAR
* @param _wallet Multisig wallet that will hold the crowdsale funds.
* @param _crowdsaleCap Cap for the token sale
* @param _isWeiAccepted Bool for acceptance of ether in token sale
*/
function init(
uint256 _startTime,
uint256 _endTime,
address _whitelist,
address _starToken,
address _companyToken,
uint256 _rate,
uint256 _starRate,
address _wallet,
uint256 _crowdsaleCap,
bool _isWeiAccepted
)
external
{
require(
whitelist == address(0) &&
starToken == address(0) &&
rate == 0 &&
starRate == 0 &&
tokenOnSale == address(0) &&
crowdsaleCap == 0,
"Global variables should not have been set before!"
);
require(
_whitelist != address(0) &&
_starToken != address(0) &&
!(_rate == 0 && _starRate == 0) &&
_companyToken != address(0) &&
_crowdsaleCap != 0,
"Parameter variables cannot be empty!"
);
initCrowdsale(_startTime, _endTime, _rate, _wallet);
tokenOnSale = CompanyToken(_companyToken);
whitelist = Whitelist(_whitelist);
starToken = StandardToken(_starToken);
starRate = _starRate;
isWeiAccepted = _isWeiAccepted;
owner = tx.origin;
initialTokenOwner = CompanyToken(tokenOnSale).owner();
uint256 tokenDecimals = CompanyToken(tokenOnSale).decimals();
crowdsaleCap = _crowdsaleCap.mul(10 ** tokenDecimals);
require(CompanyToken(tokenOnSale).paused(), "Company token must be paused upon initialization!");
}
modifier isWhitelisted(address beneficiary) {
require(whitelist.allowedAddresses(beneficiary), "Beneficiary not whitelisted!");
_;
}
modifier crowdsaleIsTokenOwner() {
require(tokenOnSale.owner() == address(this), "The token owner must be contract address!");
_;
}
/**
* @dev override fallback function. cannot use it
*/
function () external payable {
revert("No fallback function defined!");
}
/**
* @dev change crowdsale ETH rate
* @param newRate Figure that corresponds to the new ETH rate per token
*/
function setRate(uint256 newRate) external onlyOwner {
require(newRate != 0, "ETH rate must be more than 0");
emit TokenRateChanged(rate, newRate);
rate = newRate;
}
/**
* @dev change crowdsale STAR rate
* @param newStarRate Figure that corresponds to the new STAR rate per token
*/
function setStarRate(uint256 newStarRate) external onlyOwner {
require(newStarRate != 0, "Star rate must be more than 0!");
emit TokenStarRateChanged(starRate, newStarRate);
starRate = newStarRate;
}
/**
* @dev allows sale to receive wei or not
*/
function setIsWeiAccepted(bool _isWeiAccepted) external onlyOwner {
require(rate != 0, "When accepting Wei you need to set a conversion rate!");
isWeiAccepted = _isWeiAccepted;
}
/**
* @dev function that allows token purchases with STAR
* @param beneficiary Address of the purchaser
*/
function buyTokens(address beneficiary)
public
payable
whenNotPaused
isWhitelisted(beneficiary)
crowdsaleIsTokenOwner
{
require(beneficiary != address(0));
require(validPurchase() && tokenOnSale.totalSupply() < crowdsaleCap);
if (!isWeiAccepted) {
require(msg.value == 0);
} else if (msg.value > 0) {
buyTokensWithWei(beneficiary);
}
// beneficiary must allow TokenSale address to transfer star tokens on its behalf
uint256 starAllocationToTokenSale = starToken.allowance(beneficiary, this);
if (starAllocationToTokenSale > 0) {
// calculate token amount to be created
uint256 tokens = starAllocationToTokenSale.mul(starRate);
//remainder logic
if (tokenOnSale.totalSupply().add(tokens) > crowdsaleCap) {
tokens = crowdsaleCap.sub(tokenOnSale.totalSupply());
starAllocationToTokenSale = tokens.div(starRate);
}
// update state
starRaised = starRaised.add(starAllocationToTokenSale);
tokenOnSale.mint(beneficiary, tokens);
emit TokenPurchaseWithStar(msg.sender, beneficiary, starAllocationToTokenSale, tokens);
// forward funds
starToken.transferFrom(beneficiary, wallet, starAllocationToTokenSale);
}
}
/**
* @dev function that allows token purchases with Wei
* @param beneficiary Address of the purchaser
*/
function buyTokensWithWei(address beneficiary)
internal
{
uint256 weiAmount = msg.value;
uint256 weiRefund = 0;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
//remainder logic
if (tokenOnSale.totalSupply().add(tokens) > crowdsaleCap) {
tokens = crowdsaleCap.sub(tokenOnSale.totalSupply());
weiAmount = tokens.div(rate);
weiRefund = msg.value.sub(weiAmount);
}
// update state
weiRaised = weiRaised.add(weiAmount);
tokenOnSale.mint(beneficiary, tokens);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
wallet.transfer(weiAmount);
if (weiRefund > 0) {
msg.sender.transfer(weiRefund);
}
}
// override Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
if (tokenOnSale.totalSupply() >= crowdsaleCap) {
return true;
}
return super.hasEnded();
}
/**
* @dev override Crowdsale#validPurchase
* @return true if the transaction can buy tokens
*/
function validPurchase() internal view returns (bool) {
return now >= startTime && now <= endTime;
}
/**
* @dev finalizes crowdsale
*/
function finalization() internal {
if (crowdsaleCap > tokenOnSale.totalSupply()) {
uint256 remainingTokens = crowdsaleCap.sub(tokenOnSale.totalSupply());
tokenOnSale.mint(wallet, remainingTokens);
}
tokenOnSale.transferOwnership(initialTokenOwner);
super.finalization();
}
} | function that allows token purchases with STAR beneficiary Address of the purchaser/ calculate token amount to be createdremainder logic | function buyTokens(address beneficiary)
public
payable
whenNotPaused
isWhitelisted(beneficiary)
crowdsaleIsTokenOwner
{
require(beneficiary != address(0));
require(validPurchase() && tokenOnSale.totalSupply() < crowdsaleCap);
if (!isWeiAccepted) {
require(msg.value == 0);
buyTokensWithWei(beneficiary);
}
if (starAllocationToTokenSale > 0) {
uint256 tokens = starAllocationToTokenSale.mul(starRate);
if (tokenOnSale.totalSupply().add(tokens) > crowdsaleCap) {
tokens = crowdsaleCap.sub(tokenOnSale.totalSupply());
starAllocationToTokenSale = tokens.div(starRate);
}
tokenOnSale.mint(beneficiary, tokens);
emit TokenPurchaseWithStar(msg.sender, beneficiary, starAllocationToTokenSale, tokens);
}
}
| 953,322 |
pragma solidity ^0.4.11;
import "./SafeMath.sol";
import './Halt.sol';
contract HTLCBase is Halt {
using SafeMath for uint;
/**
*
* ENUMS
*
*/
/// @notice tx info status
/// @notice uninitialized,locked,refunded,revoked
enum TxStatus {None, Locked, Refunded, Revoked}
/// @notice tx direction
enum TxDirection {Coin2Wtoken, Wtoken2Coin}
/**
*
* STRUCTURES
*
*/
/// @notice HTLC(Hashed TimeLock Contract) tx info
struct HTLCTx {
TxDirection direction; // HTLC transfer direction
address source; // HTLC transaction source address
address destination; // HTLC transaction destination address
uint value; // HTLC transfer value of token
TxStatus status; // HTLC transaction status
uint lockedTime; // HTLC transaction locked time
uint beginLockedTime; // HTLC transaction begin locked time
}
/**
*
* VARIABLES
*
*/
/// @notice mapping of hash(x) to HTLCTx
mapping(bytes32 => HTLCTx) public mapXHashHTLCTxs;
/// @notice mapping of hash(x) to shadow address
mapping(bytes32 => address) public mapXHashShadow;
/// @notice atomic tx needed locked time(in seconds)
uint public lockedTime;
/// @notice default locked time(in seconds)
uint public constant DEF_LOCKED_TIME = uint(3600*36);
/// @notice default max UTC time
uint public constant DEF_MAX_TIME = uint(0xffffffffffffffff);
/// @notice the fee ratio of revoking operation
uint public revokeFeeRatio;
/// @notice revoking fee ratio precise
/// @notice for example: revokeFeeRatio is 3, meaning that the revoking fee ratio is 3/10000
uint public constant RATIO_PRECISE = 10000;
/**
*
* MANIPULATIONS
*
*/
/// Constructor
function HTLCBase()
public
{
lockedTime = DEF_LOCKED_TIME;
}
/// @notice default transfer to contract
function ()
public
payable
{
revert();
}
/// @notice destruct SC and transfer balance to owner
function kill()
public
onlyOwner
isHalted
{
selfdestruct(owner);
}
/// @notice set locked time(only owner has the right)
/// @param time the locked timeοΌin seconds
function setLockedTime(uint time)
public
onlyOwner
isHalted
returns (bool)
{
lockedTime = time;
return true;
}
/// @notice get left locked time of the HTLC transaction
/// @param xHash hash of HTLC random number
/// @return time return left locked time, in seconds. return uint(0xffffffffffffffff) if xHash does not exist
function getHTLCLeftLockedTime(bytes32 xHash)
public
view
returns(uint time)
{
HTLCTx storage info = mapXHashHTLCTxs[xHash];
if (info.status == TxStatus.None) {
return DEF_MAX_TIME;
}
if (now >= info.beginLockedTime.add(info.lockedTime)) return 0;
return info.beginLockedTime.add(info.lockedTime).sub(now);
}
/// @notice set revoke fee ratio
function setRevokeFeeRatio(uint ratio)
public
onlyOwner
isHalted
returns (bool)
{
require(ratio <= RATIO_PRECISE);
revokeFeeRatio = ratio;
return true;
}
/// @notice check HTLC transaction exist or not
/// @param xHash hash of HTLC random number
/// @return exist return true if exist
function xHashExist(bytes32 xHash)
public
view
returns(bool exist)
{
return mapXHashHTLCTxs[xHash].status != TxStatus.None;
}
/// @notice add HTLC transaction info
/// @param direction HTLC transaction direction
/// @param src HTLC transaction source address
/// @param des HTLC transaction destination address
/// @param xHash hash of HTLC random number
/// @param value HTLC transfer value of token
/// @param isFirstHand is HTLC first hand trade?
/// @param shadow shadow address. used for receipt coins on opposite block chain
function addHTLCTx(TxDirection direction, address src, address des, bytes32 xHash, uint value, bool isFirstHand, address shadow)
internal
{
require(value != 0);
require(!xHashExist(xHash));
mapXHashHTLCTxs[xHash] = HTLCTx(direction, src, des, value, TxStatus.Locked, isFirstHand ? lockedTime.mul(2) : lockedTime, now);
if (isFirstHand) mapXHashShadow[xHash] = shadow;
}
/// @notice refund coins from HTLC transaction
/// @param xHash hash of HTLC random number
/// @param direction HTLC transaction direction
/// @return xHash return hash of HTLC random number
function refundHTLCTx(bytes32 xHash, TxDirection direction)
internal
{
HTLCTx storage info = mapXHashHTLCTxs[xHash];
require(info.status == TxStatus.Locked);
require(info.direction == direction);
require(info.destination == msg.sender);
require(now < info.beginLockedTime.add(info.lockedTime));
info.status = TxStatus.Refunded;
}
/// @notice revoke HTLC transaction
/// @param xHash hash of HTLC random number
/// @param direction HTLC transaction direction
/// @param loose whether give counterparty revoking right
function revokeHTLCTx(bytes32 xHash, TxDirection direction, bool loose)
internal
{
HTLCTx storage info = mapXHashHTLCTxs[xHash];
require(info.status == TxStatus.Locked);
require(info.direction == direction);
require(now >= info.beginLockedTime.add(info.lockedTime));
if (loose) {
require((info.source == msg.sender) || (info.destination == msg.sender));
} else {
require(info.source == msg.sender);
}
info.status = TxStatus.Revoked;
}
}
| set locked time(only owner has the right) time the locked timeοΌin seconds | function setLockedTime(uint time)
public
onlyOwner
isHalted
returns (bool)
{
lockedTime = time;
return true;
}
| 2,566,383 |
// SPDX-License-Identifier: MIT
// TODO: What license do we release under?
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
@title Fountain
Create a MoneyPool (MP) that'll be used to sustain your project, and specify what its sustainability target is.
Maybe your project is providing a service or public good, maybe it's being a YouTuber, engineer, or artist -- or anything else.
Anyone with your address can help sustain your project, and once you're sustainable any additional contributions are redistributed back your sustainers.
Each MoneyPool is like a tier of the fountain, and the predefined cost to pursue the project is like the bounds of that tier's pool.
An address can only be associated with one active MoneyPool at a time, as well as a mutable one queued up for when the active MoneyPool expires.
If a MoneyPool expires without one queued, the current one will be cloned and sustainments at that time will be allocated to it.
It's impossible for a MoneyPool's sustainability or duration to be changed once there has been a sustainment made to it.
Any attempts to do so will just create/update the message sender's queued MP.
You can collect funds of yours from the sustainers pool (where MoneyPool surplus is distributed) or from the sustainability pool (where MoneyPool sustainments are kept) at anytime.
Future versions will introduce MoneyPool dependencies so that your project's surplus can get redistributed to the MP of projects it is composed of before reaching sustainers.
We also think it may be best to create a governance token WATER and route ~7% of ecosystem surplus to token holders, ~3% to fountain.finance contributors (which can be run through Fountain itself), and the rest to sustainers.
The basin of the Fountain should always be the sustainers of projects.
*/
contract FountainV1 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice Possible states that a MoneyPool may be in
/// @dev immutable once the MoneyPool receives some sustainment.
/// @dev entirely mutable until they become active.
enum MoneyPoolState {Pending, Active, Redistributing}
/// @notice The MoneyPool structure represents a MoneyPool stewarded by an address, and accounts for which addresses have contributed to it.
struct MoneyPool {
// The address who defined this MoneyPool and who has access to its sustainments.
address who;
// The token that this MoneyPool can be funded with.
address want;
// The amount that represents sustainability for this MoneyPool.
uint256 sustainabilityTarget;
// The running amount that's been contributed to sustaining this MoneyPool.
uint256 currentSustainment;
// The time when this MoneyPool will become active.
uint256 start;
// The number of days until this MoneyPool's redistribution is added to the redistributionPool.
uint256 duration;
// Helper to verify this MoneyPool exists.
bool exists;
// ID of the previous MoneyPool
uint256 previousMoneyPoolId;
// Indicates if surplus funds have been redistributed for each sustainer address
mapping(address => bool) redistributed;
// The addresses who have helped to sustain this MoneyPool.
// NOTE: Using arrays may be bad practice and/or expensive
address[] sustainers;
// The amount each address has contributed to the sustaining of this MoneyPool.
mapping(address => uint256) sustainmentTracker;
// The amount that will be redistributed to each address as a
// consequence of abundant sustainment of this MoneyPool once it resolves.
mapping(address => uint256) redistributionTracker;
}
enum Pool {REDISTRIBUTION, SUSTAINABILITY}
/// @notice The official record of all MoneyPools ever created
mapping(uint256 => MoneyPool) public moneyPools;
/// @notice The latest MoneyPool for each creator address
mapping(address => uint256) public latestMoneyPoolIds;
/// @notice List of addresses sustained by each sustainer
mapping(address => address[]) public sustainedAddressesBySustainer;
// The amount that has been redistributed to each address as a consequence of surplus.
mapping(address => uint256) public redistributionPool;
// The funds that have accumulated to sustain each address's MoneyPools.
mapping(address => uint256) public sustainabilityPool;
// The total number of MoneyPools created, which is used for issuing MoneyPool IDs.
// MoneyPools should have an id > 0, 0 should not be a moneyPoolId.
uint256 public moneyPoolCount;
// The contract currently only supports sustainments in DAI.
address public DAI;
event CreateMoneyPool(
uint256 indexed id,
address indexed by,
uint256 sustainabilityTarget,
uint256 duration,
address want
);
event UpdateMoneyPool(
uint256 indexed id,
address indexed by,
uint256 sustainabilityTarget,
uint256 duration,
address want
);
event SustainMoneyPool(
uint256 indexed id,
address indexed sustainer,
uint256 amount
);
event Collect(address indexed by, Pool indexed from, uint256 amount);
// --- External getters --- //
function getSustainerCount(address who)
external
view
returns (uint256 count)
{
require(
latestMoneyPoolIds[who] > 0,
"No MoneyPool found at this address"
);
require(
moneyPools[latestMoneyPoolIds[who]].exists,
"No MoneyPool found at this address"
);
return moneyPools[latestMoneyPoolIds[who]].sustainers.length;
}
function getSustainmentTrackerAmount(address who, address by)
external
view
returns (uint256 amount)
{
require(
latestMoneyPoolIds[who] > 0,
"No MoneyPool found at this address"
);
require(
moneyPools[latestMoneyPoolIds[who]].exists,
"No MoneyPool found at this address"
);
return moneyPools[latestMoneyPoolIds[who]].sustainmentTracker[by];
}
function getRedistributionTrackerAmount(address who, address by)
external
view
returns (uint256 amount)
{
require(
latestMoneyPoolIds[who] > 0,
"No MoneyPool found at this address"
);
require(
moneyPools[latestMoneyPoolIds[who]].exists,
"No MoneyPool found at this address"
);
return moneyPools[latestMoneyPoolIds[who]].redistributionTracker[by];
}
constructor(address dai) public {
DAI = dai;
moneyPoolCount = 0;
}
/// @notice Creates a MoneyPool to be sustained for the sending address.
/// @param target The sustainability target for the MoneyPool, in DAI.
/// @param duration The duration of the MoneyPool, which starts once this is created.
/// @param want The ERC20 token desired, currently only DAI is supported.
/// @return success If the creation was successful.
function createMoneyPool(
uint256 target,
uint256 duration,
address want
) external returns (bool success) {
require(
latestMoneyPoolIds[msg.sender] == 0,
"Fountain::createMoneyPool: Address already has a MoneyPool, call `update` instead"
);
require(
duration >= 1,
"Fountain::createMoneyPool: A MoneyPool must be at least one day long"
);
require(
want == DAI,
"Fountain::createMoneyPool: For now, a MoneyPool can only be funded with DAI"
);
moneyPoolCount++;
// Must create structs that have mappings using this approach to avoid
// the RHS creating a memory-struct that contains a mapping.
// See https://ethereum.stackexchange.com/a/72310
MoneyPool storage newMoneyPool = moneyPools[moneyPoolCount];
newMoneyPool.who = msg.sender;
newMoneyPool.sustainabilityTarget = target;
newMoneyPool.currentSustainment = 0;
newMoneyPool.start = now;
newMoneyPool.duration = duration;
newMoneyPool.want = want;
newMoneyPool.exists = true;
newMoneyPool.previousMoneyPoolId = 0;
latestMoneyPoolIds[msg.sender] = moneyPoolCount;
emit CreateMoneyPool(
moneyPoolCount,
msg.sender,
target,
duration,
want
);
return true;
}
/// @notice Contribute a specified amount to the sustainability of the specified address's active MoneyPool.
/// @notice If the amount results in surplus, redistribute the surplus proportionally to sustainers of the MoneyPool.
/// @param who Address to sustain.
/// @param amount Amount of sustainment.
/// @return success If the sustainment was successful.
function sustain(address who, uint256 amount)
external
returns (bool success)
{
require(
amount > 0,
"Fountain::sustain: The sustainment amount should be positive"
);
uint256 moneyPoolId = _moneyPoolIdToSustain(who);
MoneyPool storage currentMoneyPool = moneyPools[moneyPoolId];
require(
currentMoneyPool.exists,
"Fountain::sustain: MoneyPool not found"
);
// The amount that should be reserved for the sustainability of the MoneyPool.
// If the MoneyPool is already sustainable, set to 0.
// If the MoneyPool is not yet sustainable even with the amount, set to the amount.
// Otherwise set to the portion of the amount it'll take for sustainability to be reached
uint256 sustainabilityAmount;
if (
currentMoneyPool.currentSustainment.add(amount) <=
currentMoneyPool.sustainabilityTarget
) {
sustainabilityAmount = amount;
} else if (
currentMoneyPool.currentSustainment >=
currentMoneyPool.sustainabilityTarget
) {
sustainabilityAmount = 0;
} else {
sustainabilityAmount = currentMoneyPool.sustainabilityTarget.sub(
currentMoneyPool.currentSustainment
);
}
// Save if the message sender is contributing to this MoneyPool for the first time.
bool isNewSustainer = currentMoneyPool.sustainmentTracker[msg.sender] ==
0;
// TODO: Not working.`Returned error: VM Exception while processing transaction: revert`
//https://ethereum.stackexchange.com/questions/60028/testing-transfer-of-tokens-with-truffle
// Got it working in tests using MockContract, but need to verify it works in testnet.
// Move the full sustainment amount to this address.
require(
IERC20(currentMoneyPool.want).transferFrom(
msg.sender,
address(this),
amount
),
"ERC20 transfer failed"
);
// Increment the funds that can be collected from sustainability.
sustainabilityPool[who] = sustainabilityPool[who].add(
sustainabilityAmount
);
// Increment the sustainments to the MoneyPool made by the message sender.
currentMoneyPool.sustainmentTracker[msg.sender] = currentMoneyPool
.sustainmentTracker[msg.sender]
.add(amount);
// Increment the total amount contributed to the sustainment of the MoneyPool.
currentMoneyPool.currentSustainment = currentMoneyPool
.currentSustainment
.add(amount);
// Add the message sender as a sustainer of the MoneyPool if this is the first sustainment it's making to it.
if (isNewSustainer) currentMoneyPool.sustainers.push(msg.sender);
// Add this address to the sustainer's list of sustained addresses
sustainedAddressesBySustainer[msg.sender].push(who);
// Redistribution amounts may have changed for the current MoneyPool.
_updateTrackedRedistribution(currentMoneyPool);
// Emit events.
emit SustainMoneyPool(moneyPoolId, msg.sender, amount);
return true;
}
/// @notice A message sender can collect what's been redistributed to it by MoneyPools once they have expired.
/// @param amount The amount to collect.
/// @return success If the collecting was a success.
function collectRedistributions(uint256 amount)
external
returns (bool success)
{
// Iterate over all of sender's sustained addresses to make sure
// redistribution has completed for all redistributable MoneyPools
address[] storage sustainedAddresses = sustainedAddressesBySustainer[msg
.sender];
for (uint256 i = 0; i < sustainedAddresses.length; i++) {
_redistributeMoneyPool(sustainedAddresses[i]);
}
_performCollectRedistributions(amount);
return true;
}
/// @notice A message sender can collect what's been redistributed to it by a specific MoneyPool once it's expired.
/// @param amount The amount to collect.
/// @param from The MoneyPool to collect from.
/// @return success If the collecting was a success.
function collectRedistributionsFromAddress(uint256 amount, address from)
external
returns (bool success)
{
_redistributeMoneyPool(from);
_performCollectRedistributions(amount);
return true;
}
/// @notice A message sender can collect what's been redistributed to it by specific MoneyPools once they have expired.
/// @param amount The amount to collect.
/// @param from The MoneyPools to collect from.
/// @return success If the collecting was a success.
function collectRedistributionsFromAddresses(
uint256 amount,
address[] calldata from
) external returns (bool success) {
for (uint256 i = 0; i < from.length; i++) {
_redistributeMoneyPool(from[i]);
}
_performCollectRedistributions(amount);
return true;
}
/// @notice A message sender can collect funds that have been used to sustain it's MoneyPools.
/// @param amount The amount to collect.
/// @return success If the collecting was a success.
function collectSustainments(uint256 amount)
external
returns (bool success)
{
require(
sustainabilityPool[msg.sender] >= amount,
"This address doesn't have enough to collect this much."
);
IERC20(DAI).safeTransferFrom(address(this), msg.sender, amount);
sustainabilityPool[msg.sender] = sustainabilityPool[msg.sender].sub(
amount
);
emit Collect(msg.sender, Pool.SUSTAINABILITY, amount);
return true;
}
/// @notice Updates the sustainability target and duration of the sender's current MoneyPool if it hasn't yet received sustainments, or
/// @notice sets the properties of the MoneyPool that will take effect once the current MoneyPool expires.
/// @param target The sustainability target to set.
/// @param duration The duration to set.
/// @param want The token that the MoneyPool wants.
/// @return success If the update was successful.
function updateMoneyPool(
uint256 target,
uint256 duration,
address want
) external returns (bool success) {
require(
latestMoneyPoolIds[msg.sender] > 0,
"You don't yet have a MoneyPool."
);
require(
want == DAI,
"Fountain::updateMoneyPool: For now, a MoneyPool can only be funded with DAI"
);
uint256 moneyPoolId = _moneyPoolIdToUpdate(msg.sender);
MoneyPool storage moneyPool = moneyPools[moneyPoolId];
if (target > 0) moneyPool.sustainabilityTarget = target;
if (duration > 0) moneyPool.duration = duration;
moneyPool.want = want;
emit UpdateMoneyPool(
moneyPoolId,
moneyPool.who,
moneyPool.sustainabilityTarget,
moneyPool.duration,
moneyPool.want
);
return true;
}
// --- private --- //
/// @dev Executes the collection of redistributed funds.
/// @param amount The amount to collect.
function _performCollectRedistributions(uint256 amount) private {
require(
redistributionPool[msg.sender] >= amount,
"This address doesn't have enough to collect this much."
);
IERC20(DAI).safeTransferFrom(address(this), msg.sender, amount);
redistributionPool[msg.sender] = redistributionPool[msg.sender].sub(
amount
);
emit Collect(msg.sender, Pool.SUSTAINABILITY, amount);
}
/// @dev The sustainability of a MoneyPool cannot be updated if there have been sustainments made to it.
/// @param who The address to find a MoneyPool for.
/// @return id The resulting id.
function _moneyPoolIdToUpdate(address who) private returns (uint256 id) {
// Check if there is an active moneyPool
uint256 moneyPoolId = _getActiveMoneyPoolId(who);
if (
moneyPoolId != 0 && moneyPools[moneyPoolId].currentSustainment == 0
) {
// Allow active moneyPool to be updated if it has no sustainments
return moneyPoolId;
}
// Cannot update active moneyPool, check if there is a pending moneyPool
moneyPoolId = _getPendingMoneyPoolId(who);
if (moneyPoolId != 0) {
return moneyPoolId;
}
// No pending moneyPool found, clone the latest moneyPool
moneyPoolId = _getLatestMoneyPoolId(who);
return _createMoneyPoolFromId(moneyPoolId, now);
}
/// @dev Only active MoneyPools can be sustained.
/// @param who The address to find a MoneyPool for.
/// @return id The resulting id.
function _moneyPoolIdToSustain(address who) private returns (uint256 id) {
// Check if there is an active moneyPool
uint256 moneyPoolId = _getActiveMoneyPoolId(who);
if (moneyPoolId != 0) {
return moneyPoolId;
}
// No active moneyPool found, check if there is a pending moneyPool
moneyPoolId = _getPendingMoneyPoolId(who);
if (moneyPoolId != 0) {
return moneyPoolId;
}
// No pending moneyPool found, clone the latest moneyPool
moneyPoolId = _getLatestMoneyPoolId(who);
MoneyPool storage latestMoneyPool = moneyPools[moneyPoolId];
// Use a start date that's a multiple of the duration.
// This creates the effect that there have been scheduled MoneyPools ever since the `latest`, even if `latest` is a long time in the past.
uint256 start = _determineModuloStart(
latestMoneyPool.start.add(latestMoneyPool.duration),
latestMoneyPool.duration
);
return _createMoneyPoolFromId(moneyPoolId, start);
}
/// @dev Proportionally allocate the specified amount to the contributors of the specified MoneyPool,
/// @dev meaning each sustainer will receive a portion of the specified amount equivalent to the portion of the total
/// @dev amount contributed to the sustainment of the MoneyPool that they are responsible for.
/// @param mp The MoneyPool to update.
function _updateTrackedRedistribution(MoneyPool storage mp) private {
// Return if there's no surplus.
if (mp.sustainabilityTarget >= mp.currentSustainment) return;
uint256 surplus = mp.currentSustainment.sub(mp.sustainabilityTarget);
// For each sustainer, calculate their share of the sustainment and
// allocate a proportional share of the surplus, overwriting any previous value.
for (uint256 i = 0; i < mp.sustainers.length; i++) {
address sustainer = mp.sustainers[i];
uint256 currentSustainmentProportion = mp
.sustainmentTracker[sustainer]
.div(mp.currentSustainment);
uint256 sustainerSurplusShare = surplus.mul(
currentSustainmentProportion
);
//Store the updated redistribution in the MoneyPool.
mp.redistributionTracker[sustainer] = sustainerSurplusShare;
}
}
/// @dev Check to see if the given MoneyPool has started.
/// @param mp The MoneyPool to check.
/// @return isStarted The boolean result.
function _isMoneyPoolStarted(MoneyPool storage mp)
private
view
returns (bool isStarted)
{
return now >= mp.start;
}
/// @dev Check to see if the given MoneyPool has expired.
/// @param mp The MoneyPool to check.
/// @return isExpired The boolean result.
function _isMoneyPoolExpired(MoneyPool storage mp)
private
view
returns (bool isExpired)
{
return now > mp.start.add(mp.duration.mul(1 days));
}
/// @dev Take any tracked redistribution in the given moneyPool and
/// @dev add them to the redistribution pool.
/// @param mpAddress The MoneyPool address to redistribute.
function _redistributeMoneyPool(address mpAddress) private {
uint256 moneyPoolId = latestMoneyPoolIds[mpAddress];
require(
moneyPoolId > 0,
"Fountain::redistributeMoneyPool: MoneyPool not found"
);
MoneyPool storage moneyPool = moneyPools[moneyPoolId];
// Iterate through all MoneyPools for this address. For each iteration,
// if the MoneyPool has a state of redistributing and it has not yet
// been redistributed for the current sustainer, then process the
// redistribution. Iterate until a MoneyPool is found that has already
// been redistributed for this sustainer. This logic should skip Active
// and Pending MoneyPools.
// Short circuits by testing `moneyPool.redistributed` to limit number
// of iterations since all previous MoneyPools must have already been
// redistributed.
address sustainer = msg.sender;
while (moneyPoolId > 0 && !moneyPool.redistributed[sustainer]) {
if (_state(moneyPoolId) == MoneyPoolState.Redistributing) {
redistributionPool[sustainer] = redistributionPool[sustainer]
.add(moneyPool.redistributionTracker[sustainer]);
moneyPool.redistributed[sustainer] = true;
}
moneyPoolId = moneyPool.previousMoneyPoolId;
moneyPool = moneyPools[moneyPoolId];
}
}
/// @dev Returns a copy of the given MoneyPool with reset sustainments.
/// @param moneyPoolId The id of the MoneyPool to base the new MoneyPool on.
/// @param start The start date to use for the new MoneyPool.
/// @return newMoneyPoolId The new MoneyPool ID.
function _createMoneyPoolFromId(uint256 moneyPoolId, uint256 start)
private
returns (uint256 newMoneyPoolId)
{
MoneyPool storage currentMoneyPool = moneyPools[moneyPoolId];
require(
currentMoneyPool.exists,
"Fountain::createMoneyPoolFromId: Invalid moneyPool"
);
moneyPoolCount++;
// Must create structs that have mappings using this approach to avoid
// the RHS creating a memory-struct that contains a mapping.
// See https://ethereum.stackexchange.com/a/72310
MoneyPool storage moneyPool = moneyPools[moneyPoolCount];
moneyPool.who = currentMoneyPool.who;
moneyPool.sustainabilityTarget = currentMoneyPool.sustainabilityTarget;
moneyPool.currentSustainment = 0;
moneyPool.start = start;
moneyPool.duration = currentMoneyPool.duration;
moneyPool.want = currentMoneyPool.want;
moneyPool.exists = true;
moneyPool.previousMoneyPoolId = moneyPoolId;
latestMoneyPoolIds[currentMoneyPool.who] = moneyPoolCount;
emit UpdateMoneyPool(
moneyPoolCount,
moneyPool.who,
moneyPool.sustainabilityTarget,
moneyPool.duration,
moneyPool.want
);
return moneyPoolCount;
}
/// @dev Returns a copy of the gi
/// @dev that starts when the given MoneyPool expired.
function _determineModuloStart(uint256 oldEnd, uint256 duration)
private
view
returns (uint256)
{
// Use the old end if the current time is still within the duration.
if (oldEnd.add(duration) > now) return oldEnd;
// Otherwise, use the closest multiple of the duration from the old end.
uint256 distanceToStart = (now.sub(oldEnd)).mod(duration);
return now.sub(distanceToStart);
}
function _state(uint256 moneyPoolId) private view returns (MoneyPoolState) {
require(
moneyPoolCount >= moneyPoolId && moneyPoolId > 0,
"Fountain::state: Invalid moneyPoolId"
);
MoneyPool storage moneyPool = moneyPools[moneyPoolId];
require(moneyPool.exists, "Fountain::state: Invalid MoneyPool");
if (_isMoneyPoolExpired(moneyPool)) {
return MoneyPoolState.Redistributing;
}
if (_isMoneyPoolStarted(moneyPool) && !_isMoneyPoolExpired(moneyPool)) {
return MoneyPoolState.Active;
}
return MoneyPoolState.Pending;
}
function _getLatestMoneyPoolId(address moneyPoolAddress)
private
view
returns (uint256 id)
{
uint256 moneyPoolId = latestMoneyPoolIds[moneyPoolAddress];
require(
moneyPoolId > 0,
"Fountain::getLatestMoneyPoolId: MoneyPool not found"
);
return moneyPoolId;
}
function _getPendingMoneyPoolId(address moneyPoolAddress)
private
view
returns (uint256 id)
{
uint256 moneyPoolId = latestMoneyPoolIds[moneyPoolAddress];
require(
moneyPoolId > 0,
"Fountain::getPendingMoneyPoolId: MoneyPool not found"
);
if (_state(moneyPoolId) != MoneyPoolState.Pending) {
// There is no pending moneyPool if the latest MoneyPool is not pending
return 0;
}
return moneyPoolId;
}
function _getActiveMoneyPoolId(address moneyPoolAddress)
private
view
returns (uint256 id)
{
uint256 moneyPoolId = latestMoneyPoolIds[moneyPoolAddress];
require(
moneyPoolId > 0,
"Fountain::getActiveMoneyPoolId: MoneyPool not found"
);
// An Active moneyPool must be either the latest moneyPool or the
// moneyPool immediately before it.
if (_state(moneyPoolId) == MoneyPoolState.Active) {
return moneyPoolId;
}
MoneyPool storage moneyPool = moneyPools[moneyPoolId];
require(
moneyPool.exists,
"Fountain::getActiveMoneyPoolId: Invalid MoneyPool"
);
moneyPoolId = moneyPool.previousMoneyPoolId;
if (moneyPoolId > 0 && _state(moneyPoolId) == MoneyPoolState.Active) {
return moneyPoolId;
}
return 0;
}
}
| Proportionally allocate the specified amount to the contributors of the specified MoneyPool, meaning each sustainer will receive a portion of the specified amount equivalent to the portion of the total amount contributed to the sustainment of the MoneyPool that they are responsible for. mp The MoneyPool to update. Return if there's no surplus. For each sustainer, calculate their share of the sustainment and allocate a proportional share of the surplus, overwriting any previous value.Store the updated redistribution in the MoneyPool. | function _updateTrackedRedistribution(MoneyPool storage mp) private {
if (mp.sustainabilityTarget >= mp.currentSustainment) return;
uint256 surplus = mp.currentSustainment.sub(mp.sustainabilityTarget);
for (uint256 i = 0; i < mp.sustainers.length; i++) {
address sustainer = mp.sustainers[i];
uint256 currentSustainmentProportion = mp
.sustainmentTracker[sustainer]
.div(mp.currentSustainment);
uint256 sustainerSurplusShare = surplus.mul(
currentSustainmentProportion
);
mp.redistributionTracker[sustainer] = sustainerSurplusShare;
}
}
| 13,081,331 |
pragma solidity ^0.5.16;
import "./CToken.sol";
/**
* @title Compound's CErc20Delegator Contract
* @notice CTokens which wrap an EIP-20 underlying and delegate to an implementation
* @author Compound
*/
contract CErc20Delegator is CTokenInterface, CErc20Interface, CDelegatorInterface {
/**
* @notice Construct a new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address implementation_,
bytes memory becomeImplementationData) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)",
underlying_,
comptroller_,
interestRateModel_,
initialExchangeRateMantissa_,
name_,
symbol_,
decimals_));
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
// Set the proper admin now that initialization is done
admin = tx.origin;
}
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == admin, "CErc20Delegator::_setImplementation: Caller must be admin");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount, bool enterMarket) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("mint(uint256,bool)", mintAmount, enterMarket));
return abi.decode(data, (uint));
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("redeem(uint256)", redeemTokens));
return abi.decode(data, (uint));
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("redeemUnderlying(uint256)", redeemAmount));
return abi.decode(data, (uint));
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("borrow(uint256)", borrowAmount));
return abi.decode(data, (uint));
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("repayBorrow(uint256)", repayAmount));
return abi.decode(data, (uint));
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("repayBorrowBehalf(address,uint256)", borrower, repayAmount));
return abi.decode(data, (uint));
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("liquidateBorrow(address,uint256,address)", borrower, repayAmount, cTokenCollateral));
return abi.decode(data, (uint));
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint amount) external returns (bool) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("transfer(address,uint256)", dst, amount));
return abi.decode(data, (bool));
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("transferFrom(address,address,uint256)", src, dst, amount));
return abi.decode(data, (bool));
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("approve(address,uint256)", spender, amount));
return abi.decode(data, (bool));
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("allowance(address,address)", owner, spender));
return abi.decode(data, (uint));
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("balanceOf(address)", owner));
return abi.decode(data, (uint));
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("balanceOfUnderlying(address)", owner));
return abi.decode(data, (uint));
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("getAccountSnapshot(address)", account));
return abi.decode(data, (uint, uint, uint, uint));
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("borrowRatePerBlock()"));
return abi.decode(data, (uint));
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("supplyRatePerBlock()"));
return abi.decode(data, (uint));
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("totalBorrowsCurrent()"));
return abi.decode(data, (uint));
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("borrowBalanceCurrent(address)", account));
return abi.decode(data, (uint));
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("borrowBalanceStored(address)", account));
return abi.decode(data, (uint));
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("exchangeRateCurrent()"));
return abi.decode(data, (uint));
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("exchangeRateStored()"));
return abi.decode(data, (uint));
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("getCash()"));
return abi.decode(data, (uint));
}
/**
* @notice Applies accrued interest to total borrows and reserves.
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("accrueInterest()"));
return abi.decode(data, (uint));
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("seize(address,address,uint256)", liquidator, borrower, seizeTokens));
return abi.decode(data, (uint));
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setPendingAdmin(address)", newPendingAdmin));
return abi.decode(data, (uint));
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setComptroller(address)", newComptroller));
return abi.decode(data, (uint));
}
/**
* @notice Sets a new protocol seize share (when liquidating) for the protocol
* @dev Admin function to set a new protocol seize share
* @return uint 0=success, otherwise revert
*/
function _setProtocolSeizeShare(uint newProtocolSeizeShareMantissa) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setProtocolSeizeShare(uint256)", newProtocolSeizeShareMantissa));
return abi.decode(data, (uint));
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setReserveFactor(uint256)", newReserveFactorMantissa));
return abi.decode(data, (uint));
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_acceptAdmin()"));
return abi.decode(data, (uint));
}
/**
* @notice Accrues interest and adds reserves by transferring from admin
* @param addAmount Amount of reserves to add
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_addReserves(uint256)", addAmount));
return abi.decode(data, (uint));
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_reduceReserves(uint256)", reduceAmount));
return abi.decode(data, (uint));
}
/**
* @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setInterestRateModel(address)", newInterestRateModel));
return abi.decode(data, (uint));
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"CErc20Delegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
import "../Utils/ErrorReporter.sol";
import "../Utils/FixedPointMathLib.sol";
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
/**
* @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 amount 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 amount 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);
}
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
/**
* @notice Share of seized collateral that is added to reserves
*/
uint public protocolSeizeShareMantissa = 2.8e16; //2.8%
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the protocol seize share is changed
*/
event NewProtocolSeizeShare(uint oldProtocolSeizeShareMantissa, uint newProtocolSeizeShareMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
function _setProtocolSeizeShare(uint newProtocolSeizeShareMantissa) external returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount, bool enterMarket) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens, address borrower) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
using FixedPointMathLib for uint256;
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
struct SeizeInternalLocalVars {
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
uint liquidatorSeizeTokens;
uint protocolSeizeTokens;
uint protocolSeizeAmount;
uint exchangeRateMantissa;
uint totalReservesNew;
uint totalSupplyNew;
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
SeizeInternalLocalVars memory vars;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(vars.mathErr, vars.borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(vars.mathErr));
}
vars.protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa}));
vars.liquidatorSeizeTokens = sub_(seizeTokens, vars.protocolSeizeTokens);
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
require(vars.mathErr == MathError.NO_ERROR, "exchange rate math error");
vars.protocolSeizeAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), vars.protocolSeizeTokens);
vars.totalReservesNew = add_(totalReserves, vars.protocolSeizeAmount);
vars.totalSupplyNew = sub_(totalSupply, vars.protocolSeizeTokens);
(vars.mathErr, vars.liquidatorTokensNew) = addUInt(accountTokens[liquidator], vars.liquidatorSeizeTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
totalReserves = vars.totalReservesNew;
totalSupply = vars.totalSupplyNew;
accountTokens[borrower] = vars.borrowerTokensNew;
accountTokens[liquidator] = vars.liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, vars.liquidatorSeizeTokens);
emit Transfer(borrower, address(this), vars.protocolSeizeTokens);
emit ReservesAdded(address(this), vars.protocolSeizeAmount, vars.totalReservesNew);
/* We call the defense hook */
// unused function
// comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin β address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new protocol seize share (when liquidating) for the protocol
* @dev Admin function to set a new protocol seize share
* @return uint 0=success, otherwise revert
*/
function _setProtocolSeizeShare(uint newProtocolSeizeShareMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "Caller is not Admin");
require(newProtocolSeizeShareMantissa <= 1e18, "Protocol seize share must be < 100%");
uint oldProtocolSeizeShareMantissa = protocolSeizeShareMantissa;
protocolSeizeShareMantissa = newProtocolSeizeShareMantissa;
emit NewProtocolSeizeShare(oldProtocolSeizeShareMantissa, newProtocolSeizeShareMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor β€ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount β€ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.5.16;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*///////////////////////////////////////////////////////////////
COMMON BASE UNITS
//////////////////////////////////////////////////////////////*/
uint256 internal constant YAD = 1e8;
uint256 internal constant WAD = 1e18;
uint256 internal constant RAY = 1e27;
uint256 internal constant RAD = 1e45;
/*///////////////////////////////////////////////////////////////
FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function fmul(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(x == 0 || (x * y) / x == y)
if iszero(or(iszero(x), eq(div(z, x), y))) {
revert(0, 0)
}
// If baseUnit is zero this will return zero instead of reverting.
z := div(z, baseUnit)
}
}
function fdiv(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * baseUnit in z for now.
z := mul(x, baseUnit)
// Equivalent to require(y != 0 && (x == 0 || (x * baseUnit) / x == baseUnit))
if iszero(and(iszero(iszero(y)), or(iszero(x), eq(div(z, x), baseUnit)))) {
revert(0, 0)
}
// We ensure y is not zero above, so there is never division by zero here.
z := div(z, y)
}
}
function fpow(
uint256 x,
uint256 n,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := baseUnit
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store baseUnit in z for now.
z := baseUnit
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, baseUnit)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, baseUnit)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, baseUnit)
}
}
}
}
}
/*///////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
assembly {
// Start off with z at 1.
z := 1
// Used below to help find a nearby power of 2.
let y := x
// Find the lowest power of 2 that is at least sqrt(x).
if iszero(lt(y, 0x100000000000000000000000000000000)) {
y := shr(128, y) // Like dividing by 2 ** 128.
z := shl(64, z)
}
if iszero(lt(y, 0x10000000000000000)) {
y := shr(64, y) // Like dividing by 2 ** 64.
z := shl(32, z)
}
if iszero(lt(y, 0x100000000)) {
y := shr(32, y) // Like dividing by 2 ** 32.
z := shl(16, z)
}
if iszero(lt(y, 0x10000)) {
y := shr(16, y) // Like dividing by 2 ** 16.
z := shl(8, z)
}
if iszero(lt(y, 0x100)) {
y := shr(8, y) // Like dividing by 2 ** 8.
z := shl(4, z)
}
if iszero(lt(y, 0x10)) {
y := shr(4, y) // Like dividing by 2 ** 4.
z := shl(2, z)
}
if iszero(lt(y, 0x8)) {
// Equivalent to 2 ** z.
z := shl(1, z)
}
// Shifting right by 1 is like dividing by 2.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// Compute a rounded down version of z.
let zRoundDown := div(x, z)
// If zRoundDown is smaller, use it.
if lt(zRoundDown, z) {
z := zRoundDown
}
}
}
} | Approve `spender` to transfer up to `amount` from `src` This will overwrite the approval amount for `spender` spender The address of the account which may transfer tokens amount The number of tokens that are approved (-1 means infinite) return Whether or not the approval succeeded/ | function approve(address spender, uint256 amount) external returns (bool) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("approve(address,uint256)", spender, amount));
return abi.decode(data, (bool));
}
| 249,833 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title: MinteVipTicket
/// @authors: manifold.xyz & Collector
import "./ERC721Creator.sol";
contract MVIP is ERC721Creator {
uint256 public price = 40000000000000000; //0.04 ETH
bool public saleIsActive = true;
uint private rand;
constructor(string memory tokenName, string memory symbol) ERC721Creator(tokenName, symbol) {}
/* claim multiple tokens */
function claimBatch(address to, uint256 _qty) public nonReentrant payable {
require(_qty > 0, "Quantity must be more than 0");
require(saleIsActive, "Sale must be active to mint");
require(msg.value >= price*_qty, "Price is not correct.");
string memory uri;
for (uint i = 0; i < _qty; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
rand = (pseudo_rand()%100)+1;
uri = getVIPUri(rand);
_mintBase(to, uri);
}
}
function getVIPUri(uint r) private pure returns (string memory) {
string memory uri;
if (r < 41 ){
uri = "ipfs://QmTfFj2d8oXRRhmFG9h82zkSdTjzEiqk3ZCiotFp2XLtfg"; //DYNASTY
} else if (r >= 41 && r < 69){
uri = "ipfs://QmYXwKTQRutEgMyjP35kcSqvZ6mZnB92Q4Hgu7LnVvLD4j"; //RELICS
} else if (r >= 69 && r < 86){
uri = "ipfs://QmW7us4Zmk9ZcZQVgR17QijKCXFMFCXvtLxwSL9gFFFL6y"; //ROYALS
} else if (r >= 86 && r < 96){
uri = "ipfs://QmR2LJjd7hCm95FFtVvgxz8f98LKLTQeXgHdWqHiwnToQR"; //LEGENDS
} else if (r >= 96 && r < 100){
uri = "ipfs://QmYtD7m8mUb3JHwQCEaskjW9KPwrr2XgQNnFEwjLnnEzkC"; //COSMOS
} else {
uri = "ipfs://QmQDAGCT5ux1Fc6zTKjbVNF18KofYpLDTK7AiRN3P5dP4C"; //GENESIS
}
return uri;
}
function pseudo_rand() private view returns (uint) {
return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _tokenCount)));
}
function withdraw() public payable adminRequired {
require(payable(_msgSender()).send(address(this).balance));
}
function changeSaleState() public adminRequired {
saleIsActive = !saleIsActive;
}
function changePrice(uint256 newPrice) public adminRequired {
price = newPrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./access/AdminControl.sol";
import "./core/ERC721CreatorCore.sol";
/**
* @dev ERC721Creator implementation
*/
contract ERC721Creator is AdminControl, ERC721, ERC721CreatorCore {
constructor (string memory _name, string memory _symbol) ERC721(_name, _symbol) {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721CreatorCore, AdminControl) returns (bool) {
return ERC721CreatorCore.supportsInterface(interfaceId) || ERC721.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
_approveTransfer(from, to, tokenId);
}
/**
* @dev See {ICreatorCore-registerExtension}.
*/
function registerExtension(address extension, string calldata baseURI) external override adminRequired nonBlacklistRequired(extension) {
_registerExtension(extension, baseURI, false);
}
/**
* @dev See {ICreatorCore-registerExtension}.
*/
function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external override adminRequired nonBlacklistRequired(extension) {
_registerExtension(extension, baseURI, baseURIIdentical);
}
/**
* @dev See {ICreatorCore-unregisterExtension}.
*/
function unregisterExtension(address extension) external override adminRequired {
_unregisterExtension(extension);
}
/**
* @dev See {ICreatorCore-blacklistExtension}.
*/
function blacklistExtension(address extension) external override adminRequired {
_blacklistExtension(extension);
}
/**
* @dev See {ICreatorCore-setBaseTokenURIExtension}.
*/
function setBaseTokenURIExtension(string calldata uri) external override extensionRequired {
_setBaseTokenURIExtension(uri, false);
}
/**
* @dev See {ICreatorCore-setBaseTokenURIExtension}.
*/
function setBaseTokenURIExtension(string calldata uri, bool identical) external override extensionRequired {
_setBaseTokenURIExtension(uri, identical);
}
/**
* @dev See {ICreatorCore-setTokenURIPrefixExtension}.
*/
function setTokenURIPrefixExtension(string calldata prefix) external override extensionRequired {
_setTokenURIPrefixExtension(prefix);
}
/**
* @dev See {ICreatorCore-setTokenURIExtension}.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri) external override extensionRequired {
_setTokenURIExtension(tokenId, uri);
}
/**
* @dev See {ICreatorCore-setTokenURIExtension}.
*/
function setTokenURIExtension(uint256[] memory tokenIds, string[] calldata uris) external override extensionRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint i = 0; i < tokenIds.length; i++) {
_setTokenURIExtension(tokenIds[i], uris[i]);
}
}
/**
* @dev See {ICreatorCore-setBaseTokenURI}.
*/
function setBaseTokenURI(string calldata uri) external override adminRequired {
_setBaseTokenURI(uri);
}
/**
* @dev See {ICreatorCore-setTokenURIPrefix}.
*/
function setTokenURIPrefix(string calldata prefix) external override adminRequired {
_setTokenURIPrefix(prefix);
}
/**
* @dev See {ICreatorCore-setTokenURI}.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired {
_setTokenURI(tokenId, uri);
}
/**
* @dev See {ICreatorCore-setTokenURI}.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external override adminRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint i = 0; i < tokenIds.length; i++) {
_setTokenURI(tokenIds[i], uris[i]);
}
}
/**
* @dev See {ICreatorCore-setMintPermissions}.
*/
function setMintPermissions(address extension, address permissions) external override adminRequired {
_setMintPermissions(extension, permissions);
}
/**
* @dev See {IERC721CreatorCore-mintBase}.
*/
function mintBase(address to) public virtual override nonReentrant adminRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintBase(to, "");
}
/**
* @dev See {IERC721CreatorCore-mintBase}.
*/
function mintBase(address to, string calldata uri) public virtual override nonReentrant adminRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintBase(to, uri);
}
/**
* @dev See {IERC721CreatorCore-mintBaseBatch}.
*/
function mintBaseBatch(address to, uint16 count) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintBase(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721CreatorCore-mintBaseBatch}.
*/
function mintBaseBatch(address to, string[] calldata uris) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](uris.length);
for (uint i = 0; i < uris.length; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintBase(to, uris[i]);
}
return tokenIds;
}
/**
* @dev Mint token with no extension
*/
function _mintBase(address to, string memory uri) internal virtual returns(uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
// Track the extension that minted the token
_tokensExtension[tokenId] = address(this);
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintBase(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721CreatorCore-mintExtension}.
*/
function mintExtension(address to) public virtual override nonReentrant extensionRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintExtension(to, "");
}
/**
* @dev See {IERC721CreatorCore-mintExtension}.
*/
function mintExtension(address to, string calldata uri) public virtual override nonReentrant extensionRequired returns(uint256) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
return _mintExtension(to, uri);
}
/**
* @dev See {IERC721CreatorCore-mintExtensionBatch}.
*/
function mintExtensionBatch(address to, uint16 count) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintExtension(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721CreatorCore-mintExtensionBatch}.
*/
function mintExtensionBatch(address to, string[] calldata uris) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) {
tokenIds = new uint256[](uris.length);
for (uint i = 0; i < uris.length; i++) {
require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." );
tokenIds[i] = _mintExtension(to, uris[i]);
}
}
/**
* @dev Mint token via extension
*/
function _mintExtension(address to, string memory uri) internal virtual returns(uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
_checkMintPermissions(to, tokenId);
// Track the extension that minted the token
_tokensExtension[tokenId] = msg.sender;
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintExtension(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721CreatorCore-tokenExtension}.
*/
function tokenExtension(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "Nonexistent token");
return _tokenExtension(tokenId);
}
/**
* @dev See {IERC721CreatorCore-burn}.
*/
function burn(uint256 tokenId) public virtual override nonReentrant {
require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved");
address owner = ownerOf(tokenId);
_burn(tokenId);
_postBurn(owner, tokenId);
}
/**
* @dev See {ICreatorCore-setRoyalties}.
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
_setRoyaltiesExtension(address(this), receivers, basisPoints);
}
/**
* @dev See {ICreatorCore-setRoyalties}.
*/
function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
require(_exists(tokenId), "Nonexistent token");
_setRoyalties(tokenId, receivers, basisPoints);
}
/**
* @dev See {ICreatorCore-setRoyaltiesExtension}.
*/
function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired {
_setRoyaltiesExtension(extension, receivers, basisPoints);
}
/**
* @dev {See ICreatorCore-getRoyalties}.
*/
function getRoyalties(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See ICreatorCore-getFees}.
*/
function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See ICreatorCore-getFeeRecipients}.
*/
function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyReceivers(tokenId);
}
/**
* @dev {See ICreatorCore-getFeeBps}.
*/
function getFeeBps(uint256 tokenId) external view virtual override returns (uint[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyBPS(tokenId);
}
/**
* @dev {See ICreatorCore-royaltyInfo}.
*/
function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata) external view virtual override returns (address, uint256, bytes memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyInfo(tokenId, value);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "Nonexistent token");
return _tokenURI(tokenId);
}
}
// 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}. 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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IAdminControl.sol";
abstract contract AdminControl is Ownable, IAdminControl, ERC165 {
using EnumerableSet for EnumerableSet.AddressSet;
// Track registered admins
EnumerableSet.AddressSet private _admins;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IAdminControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Only allows approved admins to call the specified function
*/
modifier adminRequired() {
require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin");
_;
}
/**
* @dev See {IAdminControl-getAdmins}.
*/
function getAdmins() external view override returns (address[] memory admins) {
admins = new address[](_admins.length());
for (uint i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
return admins;
}
/**
* @dev See {IAdminControl-approveAdmin}.
*/
function approveAdmin(address admin) external override onlyOwner {
if (!_admins.contains(admin)) {
emit AdminApproved(admin, msg.sender);
_admins.add(admin);
}
}
/**
* @dev See {IAdminControl-revokeAdmin}.
*/
function revokeAdmin(address admin) external override onlyOwner {
if (_admins.contains(admin)) {
emit AdminRevoked(admin, msg.sender);
_admins.remove(admin);
}
}
/**
* @dev See {IAdminControl-isAdmin}.
*/
function isAdmin(address admin) public override view returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../extensions/ERC721/IERC721CreatorExtensionApproveTransfer.sol";
import "../extensions/ERC721/IERC721CreatorExtensionBurnable.sol";
import "../permissions/ERC721/IERC721CreatorMintPermissions.sol";
import "./IERC721CreatorCore.sol";
import "./CreatorCore.sol";
/**
* @dev Core ERC721 creator implementation
*/
abstract contract ERC721CreatorCore is CreatorCore, IERC721CreatorCore {
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorCore, IERC165) returns (bool) {
return interfaceId == type(IERC721CreatorCore).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {ICreatorCore-setApproveTransferExtension}.
*/
function setApproveTransferExtension(bool enabled) external override extensionRequired {
require(!enabled || ERC165Checker.supportsInterface(msg.sender, type(IERC721CreatorExtensionApproveTransfer).interfaceId), "Extension must implement IERC721CreatorExtensionApproveTransfer");
if (_extensionApproveTransfers[msg.sender] != enabled) {
_extensionApproveTransfers[msg.sender] = enabled;
emit ExtensionApproveTransferUpdated(msg.sender, enabled);
}
}
/**
* @dev Set mint permissions for an extension
*/
function _setMintPermissions(address extension, address permissions) internal {
require(_extensions.contains(extension), "CreatorCore: Invalid extension");
require(permissions == address(0x0) || ERC165Checker.supportsInterface(permissions, type(IERC721CreatorMintPermissions).interfaceId), "Invalid address");
if (_extensionPermissions[extension] != permissions) {
_extensionPermissions[extension] = permissions;
emit MintPermissionsUpdated(extension, permissions, msg.sender);
}
}
/**
* Check if an extension can mint
*/
function _checkMintPermissions(address to, uint256 tokenId) internal {
if (_extensionPermissions[msg.sender] != address(0x0)) {
IERC721CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenId);
}
}
/**
* Override for post mint actions
*/
function _postMintBase(address, uint256) internal virtual {}
/**
* Override for post mint actions
*/
function _postMintExtension(address, uint256) internal virtual {}
/**
* Post-burning callback and metadata cleanup
*/
function _postBurn(address owner, uint256 tokenId) internal virtual {
// Callback to originating extension if needed
if (_tokensExtension[tokenId] != address(this)) {
if (ERC165Checker.supportsInterface(_tokensExtension[tokenId], type(IERC721CreatorExtensionBurnable).interfaceId)) {
IERC721CreatorExtensionBurnable(_tokensExtension[tokenId]).onBurn(owner, tokenId);
}
}
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
// Delete token origin extension tracking
delete _tokensExtension[tokenId];
}
/**
* Approve a transfer
*/
function _approveTransfer(address from, address to, uint256 tokenId) internal {
if (_extensionApproveTransfers[_tokensExtension[tokenId]]) {
require(IERC721CreatorExtensionApproveTransfer(_tokensExtension[tokenId]).approveTransfer(from, to, tokenId), "ERC721Creator: Extension approval failure");
}
}
}
// 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;
// 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.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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^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] = valueIndex; // Replace lastvalue's index to valueIndex
// 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.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 () {
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.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Interface for admin control
*/
interface IAdminControl is IERC165 {
event AdminApproved(address indexed account, address indexed sender);
event AdminRevoked(address indexed account, address indexed sender);
/**
* @dev gets address of all admins
*/
function getAdmins() external view returns (address[] memory);
/**
* @dev add an admin. Can only be called by contract owner.
*/
function approveAdmin(address admin) external;
/**
* @dev remove an admin. Can only be called by contract owner.
*/
function revokeAdmin(address admin) external;
/**
* @dev checks whether or not given address is an admin
* Returns True if they are
*/
function isAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* Implement this if you want your extension to approve a transfer
*/
interface IERC721CreatorExtensionApproveTransfer is IERC165 {
/**
* @dev Set whether or not the creator will check the extension for approval of token transfer
*/
function setApproveTransfer(address creator, bool enabled) external;
/**
* @dev Called by creator contract to approve a transfer
*/
function approveTransfer(address from, address to, uint256 tokenId) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Your extension is required to implement this interface if it wishes
* to receive the onBurn callback whenever a token the extension created is
* burned
*/
interface IERC721CreatorExtensionBurnable is IERC165 {
/**
* @dev callback handler for burn events
*/
function onBurn(address owner, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721Creator compliant extension contracts.
*/
interface IERC721CreatorMintPermissions is IERC165 {
/**
* @dev get approval to mint
*/
function approveMint(address extension, address to, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "./ICreatorCore.sol";
/**
* @dev Core ERC721 creator interface
*/
interface IERC721CreatorCore is ICreatorCore {
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to) external returns (uint256);
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to) external returns (uint256);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenIds minted
*/
function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev burn a token. Can only be called by token owner or approved address.
* On burn, calls back to the registered extension's onBurn method
*/
function burn(uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../extensions/ICreatorExtensionTokenURI.sol";
import "./ICreatorCore.sol";
/**
* @dev Core creator implementation
*/
abstract contract CreatorCore is ReentrancyGuard, ICreatorCore, ERC165 {
using Strings for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
using AddressUpgradeable for address;
uint256 public _tokenCount = 0;
uint256 public MAX_TICKETS = 25000; // max number of tokens to mint
// Track registered extensions data
EnumerableSet.AddressSet internal _extensions;
EnumerableSet.AddressSet internal _blacklistedExtensions;
mapping (address => address) internal _extensionPermissions;
mapping (address => bool) internal _extensionApproveTransfers;
// For tracking which extension a token was minted by
mapping (uint256 => address) internal _tokensExtension;
// The baseURI for a given extension
mapping (address => string) private _extensionBaseURI;
mapping (address => bool) private _extensionBaseURIIdentical;
// The prefix for any tokens with a uri configured
mapping (address => string) private _extensionURIPrefix;
// Mapping for individual token URIs
mapping (uint256 => string) internal _tokenURIs;
// Royalty configurations
mapping (address => address payable[]) internal _extensionRoyaltyReceivers;
mapping (address => uint256[]) internal _extensionRoyaltyBPS;
mapping (uint256 => address payable[]) internal _tokenRoyaltyReceivers;
mapping (uint256 => uint256[]) internal _tokenRoyaltyBPS;
/**
* External interface identifiers for royalties
*/
/**
* @dev CreatorCore
*
* bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6
*
* => 0xbb3bafd6 = 0xbb3bafd6
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6;
/**
* @dev Rarible: RoyaltiesV1
*
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
*
* => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584;
/**
* @dev Foundation
*
* bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c
*
* => 0xd5a06d4c = 0xd5a06d4c
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c;
/**
* @dev EIP-2981
*
* bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d
*
* => 0x6057361d = 0x6057361d
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId)
|| interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE
|| interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981;
}
/**
* @dev Only allows registered extensions to call the specified function
*/
modifier extensionRequired() {
require(_extensions.contains(msg.sender), "Must be registered extension");
_;
}
/**
* @dev Only allows non-blacklisted extensions
*/
modifier nonBlacklistRequired(address extension) {
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
_;
}
/**
* @dev See {ICreatorCore-getExtensions}.
*/
function getExtensions() external view override returns (address[] memory extensions) {
extensions = new address[](_extensions.length());
for (uint i = 0; i < _extensions.length(); i++) {
extensions[i] = _extensions.at(i);
}
return extensions;
}
/**
* @dev Register an extension
*/
function _registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) internal {
require(extension != address(this), "Creator: Invalid");
require(extension.isContract(), "Creator: Extension must be a contract");
if (!_extensions.contains(extension)) {
_extensionBaseURI[extension] = baseURI;
_extensionBaseURIIdentical[extension] = baseURIIdentical;
emit ExtensionRegistered(extension, msg.sender);
_extensions.add(extension);
}
}
/**
* @dev Unregister an extension
*/
function _unregisterExtension(address extension) internal {
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
}
/**
* @dev Blacklist an extension
*/
function _blacklistExtension(address extension) internal {
require(extension != address(this), "Cannot blacklist yourself");
if (_extensions.contains(extension)) {
emit ExtensionUnregistered(extension, msg.sender);
_extensions.remove(extension);
}
if (!_blacklistedExtensions.contains(extension)) {
emit ExtensionBlacklisted(extension, msg.sender);
_blacklistedExtensions.add(extension);
}
}
/**
* @dev Set base token uri for an extension
*/
function _setBaseTokenURIExtension(string calldata uri, bool identical) internal {
_extensionBaseURI[msg.sender] = uri;
_extensionBaseURIIdentical[msg.sender] = identical;
}
/**
* @dev Set token uri prefix for an extension
*/
function _setTokenURIPrefixExtension(string calldata prefix) internal {
_extensionURIPrefix[msg.sender] = prefix;
}
/**
* @dev Set token uri for a token of an extension
*/
function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal {
require(_tokensExtension[tokenId] == msg.sender, "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Set base token uri for tokens with no extension
*/
function _setBaseTokenURI(string memory uri) internal {
_extensionBaseURI[address(this)] = uri;
}
/**
* @dev Set token uri prefix for tokens with no extension
*/
function _setTokenURIPrefix(string calldata prefix) internal {
_extensionURIPrefix[address(this)] = prefix;
}
/**
* @dev Set token uri for a token with no extension
*/
function _setTokenURI(uint256 tokenId, string calldata uri) internal {
require(_tokensExtension[tokenId] == address(this), "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Retrieve a token's URI
*/
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
address extension = _tokensExtension[tokenId];
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
if (bytes(_tokenURIs[tokenId]).length != 0) {
if (bytes(_extensionURIPrefix[extension]).length != 0) {
return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId]));
}
return _tokenURIs[tokenId];
}
if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) {
return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId);
}
if (!_extensionBaseURIIdentical[extension]) {
return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString()));
} else {
return _extensionBaseURI[extension];
}
}
/**
* Get token extension
*/
function _tokenExtension(uint256 tokenId) internal view returns (address extension) {
extension = _tokensExtension[tokenId];
require(extension != address(this), "No extension for token");
require(!_blacklistedExtensions.contains(extension), "Extension blacklisted");
return extension;
}
/**
* Helper to get royalties for a token
*/
function _getRoyalties(uint256 tokenId) view internal returns (address payable[] storage, uint256[] storage) {
return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId));
}
/**
* Helper to get royalty receivers for a token
*/
function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) {
if (_tokenRoyaltyReceivers[tokenId].length > 0) {
return _tokenRoyaltyReceivers[tokenId];
} else if (_extensionRoyaltyReceivers[_tokensExtension[tokenId]].length > 0) {
return _extensionRoyaltyReceivers[_tokensExtension[tokenId]];
}
return _extensionRoyaltyReceivers[address(this)];
}
/**
* Helper to get royalty basis points for a token
*/
function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) {
if (_tokenRoyaltyBPS[tokenId].length > 0) {
return _tokenRoyaltyBPS[tokenId];
} else if (_extensionRoyaltyBPS[_tokensExtension[tokenId]].length > 0) {
return _extensionRoyaltyBPS[_tokensExtension[tokenId]];
}
return _extensionRoyaltyBPS[address(this)];
}
function _getRoyaltyInfo(uint256 tokenId, uint256 value) view internal returns (address receiver, uint256 amount, bytes memory data){
address payable[] storage receivers = _getRoyaltyReceivers(tokenId);
require(receivers.length <= 1, "More than 1 royalty receiver");
if (receivers.length == 0) {
return (address(this), 0, data);
}
return (receivers[0], _getRoyaltyBPS(tokenId)[0]*value/10000, data);
}
/**
* Set royalties for a token
*/
function _setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_tokenRoyaltyReceivers[tokenId] = receivers;
_tokenRoyaltyBPS[tokenId] = basisPoints;
emit RoyaltiesUpdated(tokenId, receivers, basisPoints);
}
/**
* Set royalties for all tokens of an extension
*/
function _setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_extensionRoyaltyReceivers[extension] = receivers;
_extensionRoyaltyBPS[extension] = basisPoints;
if (extension == address(this)) {
emit DefaultRoyaltiesUpdated(receivers, basisPoints);
} else {
emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Core creator interface
*/
interface ICreatorCore is IERC165 {
event ExtensionRegistered(address indexed extension, address indexed sender);
event ExtensionUnregistered(address indexed extension, address indexed sender);
event ExtensionBlacklisted(address indexed extension, address indexed sender);
event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender);
event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints);
event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints);
event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints);
event ExtensionApproveTransferUpdated(address indexed extension, bool enabled);
/**
* @dev gets address of all extensions
*/
function getExtensions() external view returns (address[] memory);
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* Returns True if removed, False if already removed.
*/
function unregisterExtension(address extension) external;
/**
* @dev blacklist an extension. Can only be called by contract owner or admin.
* This function will destroy all ability to reference the metadata of any tokens created
* by the specified extension. It will also unregister the extension if needed.
* Returns True if removed, False if already removed.
*/
function blacklistExtension(address extension) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
*/
function setBaseTokenURIExtension(string calldata uri) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURIExtension(string calldata uri, bool identical) external;
/**
* @dev set the common prefix of an extension. Can only be called by extension.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefixExtension(string calldata prefix) external;
/**
* @dev set the tokenURI of a token extension. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external;
/**
* @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURI(string calldata uri) external;
/**
* @dev set the common prefix for tokens with no extension. Can only be called by owner/admin.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external;
/**
* @dev set a permissions contract for an extension. Used to control minting.
*/
function setMintPermissions(address extension, address permissions) external;
/**
* @dev Configure so transfers of tokens created by the caller (must be extension) gets approval
* from the extension before transferring
*/
function setApproveTransferExtension(bool enabled) external;
/**
* @dev get the extension of a given token
*/
function tokenExtension(uint256 tokenId) external view returns (address);
/**
* @dev Set default royalties
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of a token
*/
function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of an extension
*/
function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Get royalites of a token. Returns list of receivers and basisPoints
*/
function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
// Royalty support for various other standards
function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory);
function getFeeBps(uint256 tokenId) external view returns (uint[] memory);
function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata data) external view returns (address, uint256, bytes memory);
}
// 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;
import "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, type(IERC165).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165(account).supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^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.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Implement this if you want your extension to have overloadable URI's
*/
interface ICreatorExtensionTokenURI is IERC165 {
/**
* Get the uri for a given creator/tokenId
*/
function tokenURI(address creator, uint256 tokenId) external view returns (string memory);
}
| Set token uri prefix for an extension/ | function _setTokenURIPrefixExtension(string calldata prefix) internal {
_extensionURIPrefix[msg.sender] = prefix;
}
| 6,447 |
// Sources flattened with hardhat v2.3.0 https://hardhat.org
// File contracts/shared/interfaces/IDiamondCut.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
/******************************************************************************/
interface IDiamondCut {
enum FacetCutAction {
Add,
Replace,
Remove
}
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}
// File contracts/shared/interfaces/IDiamondLoupe.sol
pragma solidity 0.8.1;
// A loupe is a small magnifying glass used to look at diamonds.
// These functions look at diamonds
interface IDiamondLoupe {
/// These functions are expected to be called frequently
/// by tools.
struct Facet {
address facetAddress;
bytes4[] functionSelectors;
}
/// @notice Gets all facet addresses and their four byte function selectors.
/// @return facets_ Facet
function facets() external view returns (Facet[] memory facets_);
/// @notice Gets all the function selectors supported by a specific facet.
/// @param _facet The facet address.
/// @return facetFunctionSelectors_
function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_);
/// @notice Get all the facet addresses used by a diamond.
/// @return facetAddresses_
function facetAddresses() external view returns (address[] memory facetAddresses_);
/// @notice Gets the facet that supports the given selector.
/// @dev If facet is not found return address(0).
/// @param _functionSelector The function selector.
/// @return facetAddress_ The facet address.
function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
}
// File contracts/shared/interfaces/IERC165.sol
pragma solidity 0.8.1;
interface IERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File contracts/shared/interfaces/IERC173.sol
pragma solidity 0.8.1;
/// @title ERC-173 Contract Ownership Standard
/// Note: the ERC-165 identifier for this interface is 0x7f5828d0
/* is ERC165 */
interface IERC173 {
/// @notice Get the address of the owner
/// @return owner_ The address of the owner.
function owner() external view returns (address owner_);
/// @notice Set the address of the new owner of the contract
/// @dev Set _newOwner to address(0) to renounce any ownership.
/// @param _newOwner The address of the new owner of the contract
function transferOwnership(address _newOwner) external;
}
// File contracts/shared/libraries/LibMeta.sol
pragma solidity 0.8.1;
library LibMeta {
bytes32 internal constant EIP712_DOMAIN_TYPEHASH =
keccak256(bytes("EIP712Domain(string name,string version,uint256 salt,address verifyingContract)"));
function domainSeparator(string memory name, string memory version) internal view returns (bytes32 domainSeparator_) {
domainSeparator_ = keccak256(
abi.encode(EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(version)), getChainID(), address(this))
);
}
function getChainID() internal view returns (uint256 id) {
assembly {
id := chainid()
}
}
function msgSender() internal view returns (address sender_) {
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender_ := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
} else {
sender_ = msg.sender;
}
}
}
// File contracts/shared/libraries/LibDiamond.sol
pragma solidity 0.8.1;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/
library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct FacetAddressAndPosition {
address facetAddress;
uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array
}
struct FacetFunctionSelectors {
bytes4[] functionSelectors;
uint16 facetAddressPosition; // position of facetAddress in facetAddresses array
}
struct DiamondStorage {
// maps function selector to the facet address and
// the position of the selector in the facetFunctionSelectors.selectors array
mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;
// maps facet addresses to function selectors
mapping(address => FacetFunctionSelectors) facetFunctionSelectors;
// facet addresses
address[] facetAddresses;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// owner of the contract
address contractOwner;
}
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function setContractOwner(address _newOwner) internal {
DiamondStorage storage ds = diamondStorage();
address previousOwner = ds.contractOwner;
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = diamondStorage().contractOwner;
}
function enforceIsContractOwner() internal view {
require(LibMeta.msgSender() == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
}
event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);
function addDiamondFunctions(
address _diamondCutFacet,
address _diamondLoupeFacet,
address _ownershipFacet
) internal {
IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](3);
bytes4[] memory functionSelectors = new bytes4[](1);
functionSelectors[0] = IDiamondCut.diamondCut.selector;
cut[0] = IDiamondCut.FacetCut({facetAddress: _diamondCutFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors});
functionSelectors = new bytes4[](5);
functionSelectors[0] = IDiamondLoupe.facets.selector;
functionSelectors[1] = IDiamondLoupe.facetFunctionSelectors.selector;
functionSelectors[2] = IDiamondLoupe.facetAddresses.selector;
functionSelectors[3] = IDiamondLoupe.facetAddress.selector;
functionSelectors[4] = IERC165.supportsInterface.selector;
cut[1] = IDiamondCut.FacetCut({
facetAddress: _diamondLoupeFacet,
action: IDiamondCut.FacetCutAction.Add,
functionSelectors: functionSelectors
});
functionSelectors = new bytes4[](2);
functionSelectors[0] = IERC173.transferOwnership.selector;
functionSelectors[1] = IERC173.owner.selector;
cut[2] = IDiamondCut.FacetCut({facetAddress: _ownershipFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors});
diamondCut(cut, address(0), "");
}
// Internal function version of diamondCut
function diamondCut(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata
) internal {
for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action;
if (action == IDiamondCut.FacetCutAction.Add) {
addFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else if (action == IDiamondCut.FacetCutAction.Replace) {
replaceFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else if (action == IDiamondCut.FacetCutAction.Remove) {
removeFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
// uint16 selectorCount = uint16(diamondStorage().selectors.length);
require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
uint16 selectorPosition = uint16(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length);
// add new facet address if it does not exist
if (selectorPosition == 0) {
enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code");
ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = uint16(ds.facetAddresses.length);
ds.facetAddresses.push(_facetAddress);
}
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists");
ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(selector);
ds.selectorToFacetAndPosition[selector].facetAddress = _facetAddress;
ds.selectorToFacetAndPosition[selector].functionSelectorPosition = selectorPosition;
selectorPosition++;
}
}
function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
uint16 selectorPosition = uint16(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length);
// add new facet address if it does not exist
if (selectorPosition == 0) {
enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code");
ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = uint16(ds.facetAddresses.length);
ds.facetAddresses.push(_facetAddress);
}
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
require(oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function");
removeFunction(oldFacetAddress, selector);
// add function
ds.selectorToFacetAndPosition[selector].functionSelectorPosition = selectorPosition;
ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(selector);
ds.selectorToFacetAndPosition[selector].facetAddress = _facetAddress;
selectorPosition++;
}
}
function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
// if function does not exist then do nothing and return
require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
removeFunction(oldFacetAddress, selector);
}
}
function removeFunction(address _facetAddress, bytes4 _selector) internal {
DiamondStorage storage ds = diamondStorage();
require(_facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
// an immutable function is a function defined directly in a diamond
require(_facetAddress != address(this), "LibDiamondCut: Can't remove immutable function");
// replace selector with last selector, then delete last selector
uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition;
uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1;
// if not the same then replace _selector with lastSelector
if (selectorPosition != lastSelectorPosition) {
bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[lastSelectorPosition];
ds.facetFunctionSelectors[_facetAddress].functionSelectors[selectorPosition] = lastSelector;
ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint16(selectorPosition);
}
// delete the last selector
ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop();
delete ds.selectorToFacetAndPosition[_selector];
// if no more selectors for facet address then delete the facet address
if (lastSelectorPosition == 0) {
// replace facet address with last facet address and delete last facet address
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;
uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;
if (facetAddressPosition != lastFacetAddressPosition) {
address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition];
ds.facetAddresses[facetAddressPosition] = lastFacetAddress;
ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = uint16(facetAddressPosition);
}
ds.facetAddresses.pop();
delete ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;
}
}
function initializeDiamondCut(address _init, bytes memory _calldata) internal {
if (_init == address(0)) {
require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty");
} else {
require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
if (_init != address(this)) {
enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
}
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (success == false) {
if (error.length > 0) {
// bubble up the error
revert(string(error));
} else {
revert("LibDiamondCut: _init function reverted");
}
}
}
}
function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
require(contractSize != 0, _errorMessage);
}
}
// File contracts/Aavegotchi/interfaces/ILink.sol
pragma solidity 0.8.1;
interface ILink {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
// File contracts/Aavegotchi/libraries/LibAppStorage.sol
pragma solidity 0.8.1;
//import "../interfaces/IERC20.sol";
// import "hardhat/console.sol";
uint256 constant EQUIPPED_WEARABLE_SLOTS = 16;
uint256 constant NUMERIC_TRAITS_NUM = 6;
uint256 constant TRAIT_BONUSES_NUM = 5;
uint256 constant PORTAL_AAVEGOTCHIS_NUM = 10;
// switch (traitType) {
// case 0:
// return energy(value);
// case 1:
// return aggressiveness(value);
// case 2:
// return spookiness(value);
// case 3:
// return brain(value);
// case 4:
// return eyeShape(value);
// case 5:
// return eyeColor(value);
struct Aavegotchi {
uint16[EQUIPPED_WEARABLE_SLOTS] equippedWearables; //The currently equipped wearables of the Aavegotchi
// [Experience, Rarity Score, Kinship, Eye Color, Eye Shape, Brain Size, Spookiness, Aggressiveness, Energy]
int8[NUMERIC_TRAITS_NUM] temporaryTraitBoosts;
int16[NUMERIC_TRAITS_NUM] numericTraits; // Sixteen 16 bit ints. [Eye Color, Eye Shape, Brain Size, Spookiness, Aggressiveness, Energy]
string name;
uint256 randomNumber;
uint256 experience; //How much XP this Aavegotchi has accrued. Begins at 0.
uint256 minimumStake; //The minimum amount of collateral that must be staked. Set upon creation.
uint256 usedSkillPoints; //The number of skill points this aavegotchi has already used
uint256 interactionCount; //How many times the owner of this Aavegotchi has interacted with it.
address collateralType;
uint40 claimTime; //The block timestamp when this Aavegotchi was claimed
uint40 lastTemporaryBoost;
uint16 hauntId;
address owner;
uint8 status; // 0 == portal, 1 == VRF_PENDING, 2 == open portal, 3 == Aavegotchi
uint40 lastInteracted; //The last time this Aavegotchi was interacted with
bool locked;
address escrow; //The escrow address this Aavegotchi manages.
}
struct Dimensions {
uint8 x;
uint8 y;
uint8 width;
uint8 height;
}
struct ItemType {
string name; //The name of the item
string description;
string author;
// treated as int8s array
// [Experience, Rarity Score, Kinship, Eye Color, Eye Shape, Brain Size, Spookiness, Aggressiveness, Energy]
int8[NUMERIC_TRAITS_NUM] traitModifiers; //[WEARABLE ONLY] How much the wearable modifies each trait. Should not be more than +-5 total
//[WEARABLE ONLY] The slots that this wearable can be added to.
bool[EQUIPPED_WEARABLE_SLOTS] slotPositions;
// this is an array of uint indexes into the collateralTypes array
uint8[] allowedCollaterals; //[WEARABLE ONLY] The collaterals this wearable can be equipped to. An empty array is "any"
// SVG x,y,width,height
Dimensions dimensions;
uint256 ghstPrice; //How much GHST this item costs
uint256 maxQuantity; //Total number that can be minted of this item.
uint256 totalQuantity; //The total quantity of this item minted so far
uint32 svgId; //The svgId of the item
uint8 rarityScoreModifier; //Number from 1-50.
// Each bit is a slot position. 1 is true, 0 is false
bool canPurchaseWithGhst;
uint16 minLevel; //The minimum Aavegotchi level required to use this item. Default is 1.
bool canBeTransferred;
uint8 category; // 0 is wearable, 1 is badge, 2 is consumable
int16 kinshipBonus; //[CONSUMABLE ONLY] How much this consumable boosts (or reduces) kinship score
uint32 experienceBonus; //[CONSUMABLE ONLY]
}
struct WearableSet {
string name;
uint8[] allowedCollaterals;
uint16[] wearableIds; // The tokenIdS of each piece of the set
int8[TRAIT_BONUSES_NUM] traitsBonuses;
}
struct Haunt {
uint256 hauntMaxSize; //The max size of the Haunt
uint256 portalPrice;
bytes3 bodyColor;
uint24 totalCount;
}
struct SvgLayer {
address svgLayersContract;
uint16 offset;
uint16 size;
}
struct AavegotchiCollateralTypeInfo {
// treated as an arary of int8
int16[NUMERIC_TRAITS_NUM] modifiers; //Trait modifiers for each collateral. Can be 2, 1, -1, or -2
bytes3 primaryColor;
bytes3 secondaryColor;
bytes3 cheekColor;
uint8 svgId;
uint8 eyeShapeSvgId;
uint16 conversionRate; //Current conversionRate for the price of this collateral in relation to 1 USD. Can be updated by the DAO
bool delisted;
}
struct ERC1155Listing {
uint256 listingId;
address seller;
address erc1155TokenAddress;
uint256 erc1155TypeId;
uint256 category; // 0 is wearable, 1 is badge, 2 is consumable, 3 is tickets
uint256 quantity;
uint256 priceInWei;
uint256 timeCreated;
uint256 timeLastPurchased;
uint256 sourceListingId;
bool sold;
bool cancelled;
}
struct ERC721Listing {
uint256 listingId;
address seller;
address erc721TokenAddress;
uint256 erc721TokenId;
uint256 category; // 0 is closed portal, 1 is vrf pending, 2 is open portal, 3 is Aavegotchi
uint256 priceInWei;
uint256 timeCreated;
uint256 timePurchased;
bool cancelled;
}
struct ListingListItem {
uint256 parentListingId;
uint256 listingId;
uint256 childListingId;
}
struct GameManager {
uint256 limit;
uint256 balance;
uint256 refreshTime;
}
struct AppStorage {
mapping(address => AavegotchiCollateralTypeInfo) collateralTypeInfo;
mapping(address => uint256) collateralTypeIndexes;
mapping(bytes32 => SvgLayer[]) svgLayers;
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) nftItemBalances;
mapping(address => mapping(uint256 => uint256[])) nftItems;
// indexes are stored 1 higher so that 0 means no items in items array
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) nftItemIndexes;
ItemType[] itemTypes;
WearableSet[] wearableSets;
mapping(uint256 => Haunt) haunts;
mapping(address => mapping(uint256 => uint256)) ownerItemBalances;
mapping(address => uint256[]) ownerItems;
// indexes are stored 1 higher so that 0 means no items in items array
mapping(address => mapping(uint256 => uint256)) ownerItemIndexes;
mapping(uint256 => uint256) tokenIdToRandomNumber;
mapping(uint256 => Aavegotchi) aavegotchis;
mapping(address => uint32[]) ownerTokenIds;
mapping(address => mapping(uint256 => uint256)) ownerTokenIdIndexes;
uint32[] tokenIds;
mapping(uint256 => uint256) tokenIdIndexes;
mapping(address => mapping(address => bool)) operators;
mapping(uint256 => address) approved;
mapping(string => bool) aavegotchiNamesUsed;
mapping(address => uint256) metaNonces;
uint32 tokenIdCounter;
uint16 currentHauntId;
string name;
string symbol;
//Addresses
address[] collateralTypes;
address ghstContract;
address childChainManager;
address gameManager;
address dao;
address daoTreasury;
address pixelCraft;
address rarityFarming;
string itemsBaseUri;
bytes32 domainSeparator;
//VRF
mapping(bytes32 => uint256) vrfRequestIdToTokenId;
mapping(bytes32 => uint256) vrfNonces;
bytes32 keyHash;
uint144 fee;
address vrfCoordinator;
ILink link;
// Marketplace
uint256 nextERC1155ListingId;
// erc1155 category => erc1155Order
//ERC1155Order[] erc1155MarketOrders;
mapping(uint256 => ERC1155Listing) erc1155Listings;
// category => ("listed" or purchased => first listingId)
//mapping(uint256 => mapping(string => bytes32[])) erc1155MarketListingIds;
mapping(uint256 => mapping(string => uint256)) erc1155ListingHead;
// "listed" or purchased => (listingId => ListingListItem)
mapping(string => mapping(uint256 => ListingListItem)) erc1155ListingListItem;
mapping(address => mapping(uint256 => mapping(string => uint256))) erc1155OwnerListingHead;
// "listed" or purchased => (listingId => ListingListItem)
mapping(string => mapping(uint256 => ListingListItem)) erc1155OwnerListingListItem;
mapping(address => mapping(uint256 => mapping(address => uint256))) erc1155TokenToListingId;
uint256 listingFeeInWei;
// erc1155Token => (erc1155TypeId => category)
mapping(address => mapping(uint256 => uint256)) erc1155Categories;
uint256 nextERC721ListingId;
//ERC1155Order[] erc1155MarketOrders;
mapping(uint256 => ERC721Listing) erc721Listings;
// listingId => ListingListItem
mapping(uint256 => ListingListItem) erc721ListingListItem;
//mapping(uint256 => mapping(string => bytes32[])) erc1155MarketListingIds;
mapping(uint256 => mapping(string => uint256)) erc721ListingHead;
// user address => category => sort => listingId => ListingListItem
mapping(uint256 => ListingListItem) erc721OwnerListingListItem;
//mapping(uint256 => mapping(string => bytes32[])) erc1155MarketListingIds;
mapping(address => mapping(uint256 => mapping(string => uint256))) erc721OwnerListingHead;
// erc1155Token => (erc1155TypeId => category)
// not really in use now, for the future
mapping(address => mapping(uint256 => uint256)) erc721Categories;
// erc721 token address, erc721 tokenId, user address => listingId
mapping(address => mapping(uint256 => mapping(address => uint256))) erc721TokenToListingId;
// body wearableId => sleevesId
mapping(uint256 => uint256) sleeves;
// mapping(address => mapping(uint256 => address)) petOperators;
// mapping(address => uint256[]) petOperatorTokenIds;
mapping(address => bool) itemManagers;
mapping(address => GameManager) gameManagers;
}
library LibAppStorage {
function diamondStorage() internal pure returns (AppStorage storage ds) {
assembly {
ds.slot := 0
}
}
function abs(int256 x) internal pure returns (uint256) {
return uint256(x >= 0 ? x : -x);
}
}
contract Modifiers {
AppStorage internal s;
modifier onlyAavegotchiOwner(uint256 _tokenId) {
require(LibMeta.msgSender() == s.aavegotchis[_tokenId].owner, "LibAppStorage: Only aavegotchi owner can call this function");
_;
}
modifier onlyUnlocked(uint256 _tokenId) {
require(s.aavegotchis[_tokenId].locked == false, "LibAppStorage: Only callable on unlocked Aavegotchis");
_;
}
modifier onlyOwner {
LibDiamond.enforceIsContractOwner();
_;
}
modifier onlyDao {
address sender = LibMeta.msgSender();
require(sender == s.dao, "Only DAO can call this function");
_;
}
modifier onlyDaoOrOwner {
address sender = LibMeta.msgSender();
require(sender == s.dao || sender == LibDiamond.contractOwner(), "LibAppStorage: Do not have access");
_;
}
modifier onlyOwnerOrDaoOrGameManager {
address sender = LibMeta.msgSender();
bool isGameManager = s.gameManagers[sender].limit != 0;
require(sender == s.dao || sender == LibDiamond.contractOwner() || isGameManager, "LibAppStorage: Do not have access");
_;
}
modifier onlyItemManager {
address sender = LibMeta.msgSender();
require(s.itemManagers[sender] == true, "LibAppStorage: only an ItemManager can call this function");
_;
}
}
// File contracts/shared/interfaces/IERC1155TokenReceiver.sol
pragma solidity 0.8.1;
/**
Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface IERC1155TokenReceiver {
/**
@notice Handle the receipt of a single ERC1155 token type.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
This function MUST revert if it rejects the transfer.
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@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)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _value,
bytes calldata _data
) external returns (bytes4);
/**
@notice Handle the receipt of multiple ERC1155 token types.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated.
This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s).
This function MUST revert if it rejects the transfer(s).
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@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)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external returns (bytes4);
}
// File contracts/shared/libraries/LibERC1155.sol
pragma solidity 0.8.1;
library LibERC1155 {
bytes4 internal constant ERC1155_ACCEPTED = 0xf23a6e61; // Return value from `onERC1155Received` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`).
bytes4 internal constant ERC1155_BATCH_ACCEPTED = 0xbc197c81; // Return value from `onERC1155BatchReceived` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`).
event TransferToParent(address indexed _toContract, uint256 indexed _toTokenId, uint256 indexed _tokenTypeId, uint256 _value);
event TransferFromParent(address indexed _fromContract, uint256 indexed _fromTokenId, uint256 indexed _tokenTypeId, uint256 _value);
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be LibMeta.msgSender()).
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_id` argument MUST be the token type being transferred.
The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be LibMeta.msgSender()).
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_ids` argument MUST be the list of tokens being transferred.
The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);
/**
@dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absence of an event assumes disabled).
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
@dev MUST emit when the URI is updated for a token ID.
URIs are defined in RFC 3986.
The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
*/
event URI(string _value, uint256 indexed _id);
function onERC1155Received(
address _operator,
address _from,
address _to,
uint256 _id,
uint256 _value,
bytes memory _data
) internal {
uint256 size;
assembly {
size := extcodesize(_to)
}
if (size > 0) {
require(
ERC1155_ACCEPTED == IERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _id, _value, _data),
"Wearables: Transfer rejected/failed by _to"
);
}
}
function onERC1155BatchReceived(
address _operator,
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes memory _data
) internal {
uint256 size;
assembly {
size := extcodesize(_to)
}
if (size > 0) {
require(
ERC1155_BATCH_ACCEPTED == IERC1155TokenReceiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _values, _data),
"Wearables: Transfer rejected/failed by _to"
);
}
}
}
// File contracts/Aavegotchi/libraries/LibItems.sol
pragma solidity 0.8.1;
struct ItemTypeIO {
uint256 balance;
uint256 itemId;
ItemType itemType;
}
library LibItems {
//Wearables
uint8 internal constant WEARABLE_SLOT_BODY = 0;
uint8 internal constant WEARABLE_SLOT_FACE = 1;
uint8 internal constant WEARABLE_SLOT_EYES = 2;
uint8 internal constant WEARABLE_SLOT_HEAD = 3;
uint8 internal constant WEARABLE_SLOT_HAND_LEFT = 4;
uint8 internal constant WEARABLE_SLOT_HAND_RIGHT = 5;
uint8 internal constant WEARABLE_SLOT_PET = 6;
uint8 internal constant WEARABLE_SLOT_BG = 7;
uint256 internal constant ITEM_CATEGORY_WEARABLE = 0;
uint256 internal constant ITEM_CATEGORY_BADGE = 1;
uint256 internal constant ITEM_CATEGORY_CONSUMABLE = 2;
uint8 internal constant WEARABLE_SLOTS_TOTAL = 11;
function itemBalancesOfTokenWithTypes(address _tokenContract, uint256 _tokenId)
internal
view
returns (ItemTypeIO[] memory itemBalancesOfTokenWithTypes_)
{
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 count = s.nftItems[_tokenContract][_tokenId].length;
itemBalancesOfTokenWithTypes_ = new ItemTypeIO[](count);
for (uint256 i; i < count; i++) {
uint256 itemId = s.nftItems[_tokenContract][_tokenId][i];
uint256 bal = s.nftItemBalances[_tokenContract][_tokenId][itemId];
itemBalancesOfTokenWithTypes_[i].itemId = itemId;
itemBalancesOfTokenWithTypes_[i].balance = bal;
itemBalancesOfTokenWithTypes_[i].itemType = s.itemTypes[itemId];
}
}
function addToParent(
address _toContract,
uint256 _toTokenId,
uint256 _id,
uint256 _value
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
s.nftItemBalances[_toContract][_toTokenId][_id] += _value;
if (s.nftItemIndexes[_toContract][_toTokenId][_id] == 0) {
s.nftItems[_toContract][_toTokenId].push(uint16(_id));
s.nftItemIndexes[_toContract][_toTokenId][_id] = s.nftItems[_toContract][_toTokenId].length;
}
}
function addToOwner(
address _to,
uint256 _id,
uint256 _value
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
s.ownerItemBalances[_to][_id] += _value;
if (s.ownerItemIndexes[_to][_id] == 0) {
s.ownerItems[_to].push(uint16(_id));
s.ownerItemIndexes[_to][_id] = s.ownerItems[_to].length;
}
}
function removeFromOwner(
address _from,
uint256 _id,
uint256 _value
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 bal = s.ownerItemBalances[_from][_id];
require(_value <= bal, "LibItems: Doesn't have that many to transfer");
bal -= _value;
s.ownerItemBalances[_from][_id] = bal;
if (bal == 0) {
uint256 index = s.ownerItemIndexes[_from][_id] - 1;
uint256 lastIndex = s.ownerItems[_from].length - 1;
if (index != lastIndex) {
uint256 lastId = s.ownerItems[_from][lastIndex];
s.ownerItems[_from][index] = uint16(lastId);
s.ownerItemIndexes[_from][lastId] = index + 1;
}
s.ownerItems[_from].pop();
delete s.ownerItemIndexes[_from][_id];
}
}
function removeFromParent(
address _fromContract,
uint256 _fromTokenId,
uint256 _id,
uint256 _value
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 bal = s.nftItemBalances[_fromContract][_fromTokenId][_id];
require(_value <= bal, "Items: Doesn't have that many to transfer");
bal -= _value;
s.nftItemBalances[_fromContract][_fromTokenId][_id] = bal;
if (bal == 0) {
uint256 index = s.nftItemIndexes[_fromContract][_fromTokenId][_id] - 1;
uint256 lastIndex = s.nftItems[_fromContract][_fromTokenId].length - 1;
if (index != lastIndex) {
uint256 lastId = s.nftItems[_fromContract][_fromTokenId][lastIndex];
s.nftItems[_fromContract][_fromTokenId][index] = uint16(lastId);
s.nftItemIndexes[_fromContract][_fromTokenId][lastId] = index + 1;
}
s.nftItems[_fromContract][_fromTokenId].pop();
delete s.nftItemIndexes[_fromContract][_fromTokenId][_id];
if (_fromContract == address(this)) {
checkWearableIsEquipped(_fromTokenId, _id);
}
}
if (_fromContract == address(this) && bal == 1) {
Aavegotchi storage aavegotchi = s.aavegotchis[_fromTokenId];
if (
aavegotchi.equippedWearables[LibItems.WEARABLE_SLOT_HAND_LEFT] == _id &&
aavegotchi.equippedWearables[LibItems.WEARABLE_SLOT_HAND_RIGHT] == _id
) {
revert("LibItems: Can't hold 1 item in both hands");
}
}
}
function checkWearableIsEquipped(uint256 _fromTokenId, uint256 _id) internal view {
AppStorage storage s = LibAppStorage.diamondStorage();
for (uint256 i; i < EQUIPPED_WEARABLE_SLOTS; i++) {
require(s.aavegotchis[_fromTokenId].equippedWearables[i] != _id, "Items: Cannot transfer wearable that is equipped");
}
}
}
// File contracts/shared/interfaces/IERC20.sol
pragma solidity 0.8.1;
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256 balance);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function transfer(address _to, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
}
// File contracts/shared/libraries/LibERC20.sol
pragma solidity 0.8.1;
/******************************************************************************\
* Author: Nick Mudge
*
/******************************************************************************/
library LibERC20 {
function transferFrom(
address _token,
address _from,
address _to,
uint256 _value
) internal {
uint256 size;
assembly {
size := extcodesize(_token)
}
require(size > 0, "LibERC20: ERC20 token address has no code");
(bool success, bytes memory result) = _token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, _from, _to, _value));
handleReturn(success, result);
}
function transfer(
address _token,
address _to,
uint256 _value
) internal {
uint256 size;
assembly {
size := extcodesize(_token)
}
require(size > 0, "LibERC20: ERC20 token address has no code");
(bool success, bytes memory result) = _token.call(abi.encodeWithSelector(IERC20.transfer.selector, _to, _value));
handleReturn(success, result);
}
function handleReturn(bool _success, bytes memory _result) internal pure {
if (_success) {
if (_result.length > 0) {
require(abi.decode(_result, (bool)), "LibERC20: transfer or transferFrom returned false");
}
} else {
if (_result.length > 0) {
// bubble up any reason for revert
revert(string(_result));
} else {
revert("LibERC20: transfer or transferFrom reverted");
}
}
}
}
// File contracts/shared/interfaces/IERC721.sol
pragma solidity 0.8.1;
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
/* is ERC165 */
interface IERC721 {
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata data
) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
// File contracts/shared/interfaces/IERC721TokenReceiver.sol
pragma solidity 0.8.1;
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface IERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
) external returns (bytes4);
}
// File contracts/shared/libraries/LibERC721.sol
pragma solidity 0.8.1;
library LibERC721 {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
function checkOnERC721Received(
address _operator,
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
) internal {
uint256 size;
assembly {
size := extcodesize(_to)
}
if (size > 0) {
require(
ERC721_RECEIVED == IERC721TokenReceiver(_to).onERC721Received(_operator, _from, _tokenId, _data),
"AavegotchiFacet: Transfer rejected/failed by _to"
);
}
}
}
// File contracts/Aavegotchi/libraries/LibAavegotchi.sol
pragma solidity 0.8.1;
struct AavegotchiCollateralTypeIO {
address collateralType;
AavegotchiCollateralTypeInfo collateralTypeInfo;
}
struct AavegotchiInfo {
uint256 tokenId;
string name;
address owner;
uint256 randomNumber;
uint256 status;
int16[NUMERIC_TRAITS_NUM] numericTraits;
int16[NUMERIC_TRAITS_NUM] modifiedNumericTraits;
uint16[EQUIPPED_WEARABLE_SLOTS] equippedWearables;
address collateral;
address escrow;
uint256 stakedAmount;
uint256 minimumStake;
uint256 kinship; //The kinship value of this Aavegotchi. Default is 50.
uint256 lastInteracted;
uint256 experience; //How much XP this Aavegotchi has accrued. Begins at 0.
uint256 toNextLevel;
uint256 usedSkillPoints; //number of skill points used
uint256 level; //the current aavegotchi level
uint256 hauntId;
uint256 baseRarityScore;
uint256 modifiedRarityScore;
bool locked;
ItemTypeIO[] items;
}
struct PortalAavegotchiTraitsIO {
uint256 randomNumber;
int16[NUMERIC_TRAITS_NUM] numericTraits;
address collateralType;
uint256 minimumStake;
}
struct InternalPortalAavegotchiTraitsIO {
uint256 randomNumber;
int16[NUMERIC_TRAITS_NUM] numericTraits;
address collateralType;
uint256 minimumStake;
}
library LibAavegotchi {
uint8 constant STATUS_CLOSED_PORTAL = 0;
uint8 constant STATUS_VRF_PENDING = 1;
uint8 constant STATUS_OPEN_PORTAL = 2;
uint8 constant STATUS_AAVEGOTCHI = 3;
event AavegotchiInteract(uint256 indexed _tokenId, uint256 kinship);
function toNumericTraits(uint256 _randomNumber, int16[NUMERIC_TRAITS_NUM] memory _modifiers)
internal
pure
returns (int16[NUMERIC_TRAITS_NUM] memory numericTraits_)
{
for (uint256 i; i < NUMERIC_TRAITS_NUM; i++) {
uint256 value = uint8(uint256(_randomNumber >> (i * 8)));
if (value > 99) {
value /= 2;
if (value > 99) {
value = uint256(keccak256(abi.encodePacked(_randomNumber, i))) % 100;
}
}
numericTraits_[i] = int16(int256(value)) + _modifiers[i];
}
}
function rarityMultiplier(int16[NUMERIC_TRAITS_NUM] memory _numericTraits) internal pure returns (uint256 multiplier) {
uint256 rarityScore = LibAavegotchi.baseRarityScore(_numericTraits);
if (rarityScore < 300) return 10;
else if (rarityScore >= 300 && rarityScore < 450) return 10;
else if (rarityScore >= 450 && rarityScore <= 525) return 25;
else if (rarityScore >= 526 && rarityScore <= 580) return 100;
else if (rarityScore >= 581) return 1000;
}
function singlePortalAavegotchiTraits(uint256 _randomNumber, uint256 _option)
internal
view
returns (InternalPortalAavegotchiTraitsIO memory singlePortalAavegotchiTraits_)
{
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 randomNumberN = uint256(keccak256(abi.encodePacked(_randomNumber, _option)));
singlePortalAavegotchiTraits_.randomNumber = randomNumberN;
address collateralType = s.collateralTypes[randomNumberN % s.collateralTypes.length];
singlePortalAavegotchiTraits_.numericTraits = toNumericTraits(randomNumberN, s.collateralTypeInfo[collateralType].modifiers);
singlePortalAavegotchiTraits_.collateralType = collateralType;
AavegotchiCollateralTypeInfo memory collateralInfo = s.collateralTypeInfo[collateralType];
uint256 conversionRate = collateralInfo.conversionRate;
//Get rarity multiplier
uint256 multiplier = rarityMultiplier(singlePortalAavegotchiTraits_.numericTraits);
//First we get the base price of our collateral in terms of DAI
uint256 collateralDAIPrice = ((10**IERC20(collateralType).decimals()) / conversionRate);
//Then multiply by the rarity multiplier
singlePortalAavegotchiTraits_.minimumStake = collateralDAIPrice * multiplier;
}
function portalAavegotchiTraits(uint256 _tokenId)
internal
view
returns (PortalAavegotchiTraitsIO[PORTAL_AAVEGOTCHIS_NUM] memory portalAavegotchiTraits_)
{
AppStorage storage s = LibAppStorage.diamondStorage();
require(s.aavegotchis[_tokenId].status == LibAavegotchi.STATUS_OPEN_PORTAL, "AavegotchiFacet: Portal not open");
uint256 randomNumber = s.tokenIdToRandomNumber[_tokenId];
for (uint256 i; i < portalAavegotchiTraits_.length; i++) {
InternalPortalAavegotchiTraitsIO memory single = singlePortalAavegotchiTraits(randomNumber, i);
portalAavegotchiTraits_[i].randomNumber = single.randomNumber;
portalAavegotchiTraits_[i].collateralType = single.collateralType;
portalAavegotchiTraits_[i].minimumStake = single.minimumStake;
portalAavegotchiTraits_[i].numericTraits = single.numericTraits;
}
}
function getAavegotchi(uint256 _tokenId) internal view returns (AavegotchiInfo memory aavegotchiInfo_) {
AppStorage storage s = LibAppStorage.diamondStorage();
aavegotchiInfo_.tokenId = _tokenId;
aavegotchiInfo_.owner = s.aavegotchis[_tokenId].owner;
aavegotchiInfo_.randomNumber = s.aavegotchis[_tokenId].randomNumber;
aavegotchiInfo_.status = s.aavegotchis[_tokenId].status;
aavegotchiInfo_.hauntId = s.aavegotchis[_tokenId].hauntId;
if (aavegotchiInfo_.status == STATUS_AAVEGOTCHI) {
aavegotchiInfo_.name = s.aavegotchis[_tokenId].name;
aavegotchiInfo_.equippedWearables = s.aavegotchis[_tokenId].equippedWearables;
aavegotchiInfo_.collateral = s.aavegotchis[_tokenId].collateralType;
aavegotchiInfo_.escrow = s.aavegotchis[_tokenId].escrow;
aavegotchiInfo_.stakedAmount = IERC20(aavegotchiInfo_.collateral).balanceOf(aavegotchiInfo_.escrow);
aavegotchiInfo_.minimumStake = s.aavegotchis[_tokenId].minimumStake;
aavegotchiInfo_.kinship = kinship(_tokenId);
aavegotchiInfo_.lastInteracted = s.aavegotchis[_tokenId].lastInteracted;
aavegotchiInfo_.experience = s.aavegotchis[_tokenId].experience;
aavegotchiInfo_.toNextLevel = xpUntilNextLevel(s.aavegotchis[_tokenId].experience);
aavegotchiInfo_.level = aavegotchiLevel(s.aavegotchis[_tokenId].experience);
aavegotchiInfo_.usedSkillPoints = s.aavegotchis[_tokenId].usedSkillPoints;
aavegotchiInfo_.numericTraits = s.aavegotchis[_tokenId].numericTraits;
aavegotchiInfo_.baseRarityScore = baseRarityScore(aavegotchiInfo_.numericTraits);
(aavegotchiInfo_.modifiedNumericTraits, aavegotchiInfo_.modifiedRarityScore) = modifiedTraitsAndRarityScore(_tokenId);
aavegotchiInfo_.locked = s.aavegotchis[_tokenId].locked;
aavegotchiInfo_.items = LibItems.itemBalancesOfTokenWithTypes(address(this), _tokenId);
}
}
//Only valid for claimed Aavegotchis
function modifiedTraitsAndRarityScore(uint256 _tokenId)
internal
view
returns (int16[NUMERIC_TRAITS_NUM] memory numericTraits_, uint256 rarityScore_)
{
AppStorage storage s = LibAppStorage.diamondStorage();
require(s.aavegotchis[_tokenId].status == STATUS_AAVEGOTCHI, "AavegotchiFacet: Must be claimed");
Aavegotchi storage aavegotchi = s.aavegotchis[_tokenId];
numericTraits_ = getNumericTraits(_tokenId);
uint256 wearableBonus;
for (uint256 slot; slot < EQUIPPED_WEARABLE_SLOTS; slot++) {
uint256 wearableId = aavegotchi.equippedWearables[slot];
if (wearableId == 0) {
continue;
}
ItemType storage itemType = s.itemTypes[wearableId];
//Add on trait modifiers
for (uint256 j; j < NUMERIC_TRAITS_NUM; j++) {
numericTraits_[j] += itemType.traitModifiers[j];
}
wearableBonus += itemType.rarityScoreModifier;
}
uint256 baseRarity = baseRarityScore(numericTraits_);
rarityScore_ = baseRarity + wearableBonus;
}
function getNumericTraits(uint256 _tokenId) internal view returns (int16[NUMERIC_TRAITS_NUM] memory numericTraits_) {
AppStorage storage s = LibAppStorage.diamondStorage();
//Check if trait boosts from consumables are still valid
int256 boostDecay = int256((block.timestamp - s.aavegotchis[_tokenId].lastTemporaryBoost) / 24 hours);
for (uint256 i; i < NUMERIC_TRAITS_NUM; i++) {
int256 number = s.aavegotchis[_tokenId].numericTraits[i];
int256 boost = s.aavegotchis[_tokenId].temporaryTraitBoosts[i];
if (boost > 0 && boost > boostDecay) {
number += boost - boostDecay;
} else if ((boost * -1) > boostDecay) {
number += boost + boostDecay;
}
numericTraits_[i] = int16(number);
}
}
function kinship(uint256 _tokenId) internal view returns (uint256 score_) {
AppStorage storage s = LibAppStorage.diamondStorage();
Aavegotchi storage aavegotchi = s.aavegotchis[_tokenId];
uint256 lastInteracted = aavegotchi.lastInteracted;
uint256 interactionCount = aavegotchi.interactionCount;
uint256 interval = block.timestamp - lastInteracted;
uint256 daysSinceInteraction = interval / 24 hours;
if (interactionCount > daysSinceInteraction) {
score_ = interactionCount - daysSinceInteraction;
}
}
function xpUntilNextLevel(uint256 _experience) internal pure returns (uint256 requiredXp_) {
uint256 currentLevel = aavegotchiLevel(_experience);
requiredXp_ = ((currentLevel**2) * 50) - _experience;
}
function aavegotchiLevel(uint256 _experience) internal pure returns (uint256 level_) {
if (_experience > 490050) {
return 99;
}
level_ = (sqrt(2 * _experience) / 10);
return level_ + 1;
}
function interact(uint256 _tokenId) internal returns (bool) {
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 lastInteracted = s.aavegotchis[_tokenId].lastInteracted;
// if interacted less than 12 hours ago
if (block.timestamp < lastInteracted + 12 hours) {
return false;
}
uint256 interactionCount = s.aavegotchis[_tokenId].interactionCount;
uint256 interval = block.timestamp - lastInteracted;
uint256 daysSinceInteraction = interval / 1 days;
uint256 l_kinship;
if (interactionCount > daysSinceInteraction) {
l_kinship = interactionCount - daysSinceInteraction;
}
uint256 hateBonus;
if (l_kinship < 40) {
hateBonus = 2;
}
l_kinship += 1 + hateBonus;
s.aavegotchis[_tokenId].interactionCount = l_kinship;
s.aavegotchis[_tokenId].lastInteracted = uint40(block.timestamp);
emit AavegotchiInteract(_tokenId, l_kinship);
return true;
}
//Calculates the base rarity score, including collateral modifier
function baseRarityScore(int16[NUMERIC_TRAITS_NUM] memory _numericTraits) internal pure returns (uint256 _rarityScore) {
for (uint256 i; i < NUMERIC_TRAITS_NUM; i++) {
int256 number = _numericTraits[i];
if (number >= 50) {
_rarityScore += uint256(number) + 1;
} else {
_rarityScore += uint256(int256(100) - number);
}
}
}
// Need to ensure there is no overflow of _ghst
function purchase(address _from, uint256 _ghst) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
//33% to burn address
uint256 burnShare = (_ghst * 33) / 100;
//17% to Pixelcraft wallet
uint256 companyShare = (_ghst * 17) / 100;
//40% to rarity farming rewards
uint256 rarityFarmShare = (_ghst * 2) / 5;
//10% to DAO
uint256 daoShare = (_ghst - burnShare - companyShare - rarityFarmShare);
// Using 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF as burn address.
// GHST token contract does not allow transferring to address(0) address: https://etherscan.io/address/0x3F382DbD960E3a9bbCeaE22651E88158d2791550#code
address ghstContract = s.ghstContract;
LibERC20.transferFrom(ghstContract, _from, address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF), burnShare);
LibERC20.transferFrom(ghstContract, _from, s.pixelCraft, companyShare);
LibERC20.transferFrom(ghstContract, _from, s.rarityFarming, rarityFarmShare);
LibERC20.transferFrom(ghstContract, _from, s.dao, daoShare);
}
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function validateAndLowerName(string memory _name) internal pure returns (string memory) {
bytes memory name = abi.encodePacked(_name);
uint256 len = name.length;
require(len != 0, "LibAavegotchi: name can't be 0 chars");
require(len < 26, "LibAavegotchi: name can't be greater than 25 characters");
uint256 char = uint256(uint8(name[0]));
require(char != 32, "LibAavegotchi: first char of name can't be a space");
char = uint256(uint8(name[len - 1]));
require(char != 32, "LibAavegotchi: last char of name can't be a space");
for (uint256 i; i < len; i++) {
char = uint256(uint8(name[i]));
require(char > 31 && char < 127, "LibAavegotchi: invalid character in Aavegotchi name.");
if (char < 91 && char > 64) {
name[i] = bytes1(uint8(char + 32));
}
}
return string(name);
}
// function addTokenToUser(address _to, uint256 _tokenId) internal {}
// function removeTokenFromUser(address _from, uint256 _tokenId) internal {}
function transfer(
address _from,
address _to,
uint256 _tokenId
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
// remove
uint256 index = s.ownerTokenIdIndexes[_from][_tokenId];
uint256 lastIndex = s.ownerTokenIds[_from].length - 1;
if (index != lastIndex) {
uint32 lastTokenId = s.ownerTokenIds[_from][lastIndex];
s.ownerTokenIds[_from][index] = lastTokenId;
s.ownerTokenIdIndexes[_from][lastTokenId] = index;
}
s.ownerTokenIds[_from].pop();
delete s.ownerTokenIdIndexes[_from][_tokenId];
if (s.approved[_tokenId] != address(0)) {
delete s.approved[_tokenId];
emit LibERC721.Approval(_from, address(0), _tokenId);
}
// add
s.aavegotchis[_tokenId].owner = _to;
s.ownerTokenIdIndexes[_to][_tokenId] = s.ownerTokenIds[_to].length;
s.ownerTokenIds[_to].push(uint32(_tokenId));
emit LibERC721.Transfer(_from, _to, _tokenId);
}
/* function verify(uint256 _tokenId) internal pure {
// if (_tokenId < 10) {}
// revert("Not verified");
}
*/
}
// File contracts/shared/libraries/LibStrings.sol
pragma solidity 0.8.1;
// From Open Zeppelin contracts: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol
/**
* @dev String operations.
*/
library LibStrings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function strWithUint(string memory _str, 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
bytes memory buffer;
unchecked {
if (value == 0) {
return string(abi.encodePacked(_str, "0"));
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
}
return string(abi.encodePacked(_str, buffer));
}
}
// File contracts/shared/interfaces/IERC1155.sol
pragma solidity 0.8.1;
/**
@title ERC-1155 Multi Token Standard
@dev See https://eips.ethereum.org/EIPS/eip-1155
Note: The ERC-165 identifier for this interface is 0xd9b67a26.
*/
/* is ERC165 */
interface IERC1155 {
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _value,
bytes calldata _data
) external;
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external;
/**
@notice Get the balance of an account's tokens.
@param _owner The address of the token holder
@param _id ID of the token
@return The _owner's balance of the token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the tokens
@return The _owner's balance of the token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
// File contracts/Aavegotchi/libraries/LibERC1155Marketplace.sol
pragma solidity 0.8.1;
// import "hardhat/console.sol";
library LibERC1155Marketplace {
event ERC1155ListingCancelled(uint256 indexed listingId, uint256 category, uint256 time);
event ERC1155ListingRemoved(uint256 indexed listingId, uint256 category, uint256 time);
event UpdateERC1155Listing(uint256 indexed listingId, uint256 quantity, uint256 priceInWei, uint256 time);
function cancelERC1155Listing(uint256 _listingId, address _owner) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
ListingListItem storage listingItem = s.erc1155ListingListItem["listed"][_listingId];
if (listingItem.listingId == 0) {
return;
}
ERC1155Listing storage listing = s.erc1155Listings[_listingId];
if (listing.cancelled == true || listing.sold == true) {
return;
}
require(listing.seller == _owner, "Marketplace: owner not seller");
listing.cancelled = true;
emit ERC1155ListingCancelled(_listingId, listing.category, block.number);
removeERC1155ListingItem(_listingId, _owner);
}
function addERC1155ListingItem(
address _owner,
uint256 _category,
string memory _sort,
uint256 _listingId
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 headListingId = s.erc1155OwnerListingHead[_owner][_category][_sort];
if (headListingId != 0) {
ListingListItem storage headListingItem = s.erc1155OwnerListingListItem[_sort][headListingId];
headListingItem.parentListingId = _listingId;
}
ListingListItem storage listingItem = s.erc1155OwnerListingListItem[_sort][_listingId];
listingItem.childListingId = headListingId;
s.erc1155OwnerListingHead[_owner][_category][_sort] = _listingId;
listingItem.listingId = _listingId;
headListingId = s.erc1155ListingHead[_category][_sort];
if (headListingId != 0) {
ListingListItem storage headListingItem = s.erc1155ListingListItem[_sort][headListingId];
headListingItem.parentListingId = _listingId;
}
listingItem = s.erc1155ListingListItem[_sort][_listingId];
listingItem.childListingId = headListingId;
s.erc1155ListingHead[_category][_sort] = _listingId;
listingItem.listingId = _listingId;
}
function removeERC1155ListingItem(uint256 _listingId, address _owner) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
ListingListItem storage listingItem = s.erc1155ListingListItem["listed"][_listingId];
if (listingItem.listingId == 0) {
return;
}
uint256 parentListingId = listingItem.parentListingId;
if (parentListingId != 0) {
ListingListItem storage parentListingItem = s.erc1155ListingListItem["listed"][parentListingId];
parentListingItem.childListingId = listingItem.childListingId;
}
uint256 childListingId = listingItem.childListingId;
if (childListingId != 0) {
ListingListItem storage childListingItem = s.erc1155ListingListItem["listed"][childListingId];
childListingItem.parentListingId = listingItem.parentListingId;
}
ERC1155Listing storage listing = s.erc1155Listings[_listingId];
if (s.erc1155ListingHead[listing.category]["listed"] == _listingId) {
s.erc1155ListingHead[listing.category]["listed"] = listingItem.childListingId;
}
listingItem.listingId = 0;
listingItem.parentListingId = 0;
listingItem.childListingId = 0;
listingItem = s.erc1155OwnerListingListItem["listed"][_listingId];
parentListingId = listingItem.parentListingId;
if (parentListingId != 0) {
ListingListItem storage parentListingItem = s.erc1155OwnerListingListItem["listed"][parentListingId];
parentListingItem.childListingId = listingItem.childListingId;
}
childListingId = listingItem.childListingId;
if (childListingId != 0) {
ListingListItem storage childListingItem = s.erc1155OwnerListingListItem["listed"][childListingId];
childListingItem.parentListingId = listingItem.parentListingId;
}
listing = s.erc1155Listings[_listingId];
if (s.erc1155OwnerListingHead[_owner][listing.category]["listed"] == _listingId) {
s.erc1155OwnerListingHead[_owner][listing.category]["listed"] = listingItem.childListingId;
}
listingItem.listingId = 0;
listingItem.parentListingId = 0;
listingItem.childListingId = 0;
s.erc1155TokenToListingId[listing.erc1155TokenAddress][listing.erc1155TypeId][_owner] = 0;
emit ERC1155ListingRemoved(_listingId, listing.category, block.timestamp);
}
function updateERC1155Listing(
address _erc1155TokenAddress,
uint256 _erc1155TypeId,
address _owner
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 listingId = s.erc1155TokenToListingId[_erc1155TokenAddress][_erc1155TypeId][_owner];
if (listingId == 0) {
return;
}
ERC1155Listing storage listing = s.erc1155Listings[listingId];
if (listing.timeCreated == 0 || listing.cancelled == true || listing.sold == true) {
return;
}
uint256 quantity = listing.quantity;
if (quantity > 0) {
quantity = IERC1155(listing.erc1155TokenAddress).balanceOf(listing.seller, listing.erc1155TypeId);
if (quantity < listing.quantity) {
listing.quantity = quantity;
emit UpdateERC1155Listing(listingId, quantity, listing.priceInWei, block.timestamp);
}
}
if (quantity == 0) {
cancelERC1155Listing(listingId, listing.seller);
}
}
}
// File contracts/Aavegotchi/facets/ItemsFacet.sol
pragma solidity 0.8.1;
// import "hardhat/console.sol";
contract ItemsFacet is Modifiers {
//using LibAppStorage for AppStorage;
event TransferToParent(address indexed _toContract, uint256 indexed _toTokenId, uint256 indexed _tokenTypeId, uint256 _value);
event EquipWearables(uint256 indexed _tokenId, uint16[EQUIPPED_WEARABLE_SLOTS] _oldWearables, uint16[EQUIPPED_WEARABLE_SLOTS] _newWearables);
event UseConsumables(uint256 indexed _tokenId, uint256[] _itemIds, uint256[] _quantities);
/***********************************|
| Read Functions |
|__________________________________*/
struct ItemIdIO {
uint256 itemId;
uint256 balance;
}
// Returns balance for each item that exists for an account
function itemBalances(address _account) external view returns (ItemIdIO[] memory bals_) {
uint256 count = s.ownerItems[_account].length;
bals_ = new ItemIdIO[](count);
for (uint256 i; i < count; i++) {
uint256 itemId = s.ownerItems[_account][i];
bals_[i].balance = s.ownerItemBalances[_account][itemId];
bals_[i].itemId = itemId;
}
}
function itemBalancesWithTypes(address _owner) external view returns (ItemTypeIO[] memory output_) {
uint256 count = s.ownerItems[_owner].length;
output_ = new ItemTypeIO[](count);
for (uint256 i; i < count; i++) {
uint256 itemId = s.ownerItems[_owner][i];
output_[i].balance = s.ownerItemBalances[_owner][itemId];
output_[i].itemId = itemId;
output_[i].itemType = s.itemTypes[itemId];
}
}
/**
@notice Get the balance of an account's tokens.
@param _owner The address of the token holder
@param _id ID of the token
@return bal_ The _owner's balance of the token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256 bal_) {
bal_ = s.ownerItemBalances[_owner][_id];
}
/// @notice Get the balance of a non-fungible parent token
/// @param _tokenContract The contract tracking the parent token
/// @param _tokenId The ID of the parent token
/// @param _id ID of the token
/// @return value The balance of the token
function balanceOfToken(
address _tokenContract,
uint256 _tokenId,
uint256 _id
) external view returns (uint256 value) {
value = s.nftItemBalances[_tokenContract][_tokenId][_id];
}
// returns the balances for all items for a token
function itemBalancesOfToken(address _tokenContract, uint256 _tokenId) external view returns (ItemIdIO[] memory bals_) {
uint256 count = s.nftItems[_tokenContract][_tokenId].length;
bals_ = new ItemIdIO[](count);
for (uint256 i; i < count; i++) {
uint256 itemId = s.nftItems[_tokenContract][_tokenId][i];
bals_[i].itemId = itemId;
bals_[i].balance = s.nftItemBalances[_tokenContract][_tokenId][itemId];
}
}
function itemBalancesOfTokenWithTypes(address _tokenContract, uint256 _tokenId)
external
view
returns (ItemTypeIO[] memory itemBalancesOfTokenWithTypes_)
{
itemBalancesOfTokenWithTypes_ = LibItems.itemBalancesOfTokenWithTypes(_tokenContract, _tokenId);
}
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the tokens
@return bals The _owner's balance of the token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory bals) {
require(_owners.length == _ids.length, "ItemsFacet: _owners length not same as _ids length");
bals = new uint256[](_owners.length);
for (uint256 i; i < _owners.length; i++) {
uint256 id = _ids[i];
address owner = _owners[i];
bals[i] = s.ownerItemBalances[owner][id];
}
}
function equippedWearables(uint256 _tokenId) external view returns (uint16[EQUIPPED_WEARABLE_SLOTS] memory wearableIds_) {
wearableIds_ = s.aavegotchis[_tokenId].equippedWearables;
}
// Called by off chain software so not too concerned about gas costs
function getWearableSets() external view returns (WearableSet[] memory wearableSets_) {
wearableSets_ = s.wearableSets;
}
function getWearableSet(uint256 _index) public view returns (WearableSet memory wearableSet_) {
uint256 length = s.wearableSets.length;
require(_index < length, "ItemsFacet: Wearable set does not exist");
wearableSet_ = s.wearableSets[_index];
}
function totalWearableSets() external view returns (uint256) {
return s.wearableSets.length;
}
function findWearableSets(uint256[] calldata _wearableIds) external view returns (uint256[] memory wearableSetIds_) {
unchecked {
uint256 length = s.wearableSets.length;
wearableSetIds_ = new uint256[](length);
uint256 count;
for (uint256 i; i < length; i++) {
uint16[] memory setWearableIds = s.wearableSets[i].wearableIds;
bool foundSet = true;
for (uint256 j; j < setWearableIds.length; j++) {
uint256 setWearableId = setWearableIds[j];
bool foundWearableId = false;
for (uint256 k; k < _wearableIds.length; k++) {
if (_wearableIds[k] == setWearableId) {
foundWearableId = true;
break;
}
}
if (foundWearableId == false) {
foundSet = false;
break;
}
}
if (foundSet) {
wearableSetIds_[count] = i;
count++;
}
}
assembly {
mstore(wearableSetIds_, count)
}
}
}
function getItemType(uint256 _itemId) public view returns (ItemType memory itemType_) {
require(_itemId < s.itemTypes.length, "ItemsFacet: Item type doesn't exist");
itemType_ = s.itemTypes[_itemId];
}
function getItemTypes(uint256[] calldata _itemIds) external view returns (ItemType[] memory itemTypes_) {
if (_itemIds.length == 0) {
itemTypes_ = s.itemTypes;
} else {
itemTypes_ = new ItemType[](_itemIds.length);
for (uint256 i; i < _itemIds.length; i++) {
itemTypes_[i] = s.itemTypes[_itemIds[i]];
}
}
}
/**
@notice Get the URI for a voucher type
@return URI for token type
*/
function uri(uint256 _id) external view returns (string memory) {
require(_id < s.itemTypes.length, "ItemsFacet: _id not found for item");
return LibStrings.strWithUint(s.itemsBaseUri, _id);
}
/**
@notice Set the base url for all voucher types
@param _value The new base url
*/
function setBaseURI(string memory _value) external onlyDaoOrOwner {
// require(LibMeta.msgSender() == s.contractOwner, "ItemsFacet: Must be contract owner");
s.itemsBaseUri = _value;
for (uint256 i; i < s.itemTypes.length; i++) {
emit LibERC1155.URI(LibStrings.strWithUint(_value, i), i);
}
}
/***********************************|
| Write Functions |
|__________________________________*/
function equipWearables(uint256 _tokenId, uint16[EQUIPPED_WEARABLE_SLOTS] calldata _equippedWearables) external onlyAavegotchiOwner(_tokenId) {
Aavegotchi storage aavegotchi = s.aavegotchis[_tokenId];
require(aavegotchi.status == LibAavegotchi.STATUS_AAVEGOTCHI, "LibAavegotchi: Only valid for Aavegotchi");
address sender = LibMeta.msgSender();
uint256 aavegotchiLevel = LibAavegotchi.aavegotchiLevel(aavegotchi.experience);
for (uint256 slot; slot < EQUIPPED_WEARABLE_SLOTS; slot++) {
uint256 wearableId = _equippedWearables[slot];
if (wearableId == 0) {
continue;
}
ItemType storage itemType = s.itemTypes[wearableId];
require(aavegotchiLevel >= itemType.minLevel, "ItemsFacet: Aavegotchi level lower than minLevel");
require(itemType.category == LibItems.ITEM_CATEGORY_WEARABLE, "ItemsFacet: Only wearables can be equippped");
require(itemType.slotPositions[slot] == true, "ItemsFacet: Wearable cannot be equipped in this slot");
{
bool canBeEquipped;
uint8[] memory allowedCollaterals = itemType.allowedCollaterals;
if (allowedCollaterals.length > 0) {
uint256 collateralIndex = s.collateralTypeIndexes[aavegotchi.collateralType];
for (uint256 i; i < allowedCollaterals.length; i++) {
if (collateralIndex == allowedCollaterals[i]) {
canBeEquipped = true;
break;
}
}
require(canBeEquipped, "ItemsFacet: Wearable cannot be equipped in this collateral type");
}
}
//Then check if this wearable is in the Aavegotchis inventory
uint256 nftBalance = s.nftItemBalances[address(this)][_tokenId][wearableId];
uint256 neededBalance = 1;
if (slot == LibItems.WEARABLE_SLOT_HAND_LEFT) {
if (_equippedWearables[LibItems.WEARABLE_SLOT_HAND_RIGHT] == wearableId) {
neededBalance = 2;
}
}
if (nftBalance < neededBalance) {
uint256 ownerBalance = s.ownerItemBalances[sender][wearableId];
require(nftBalance + ownerBalance >= neededBalance, "ItemsFacet: Wearable is not in inventories");
uint256 balToTransfer = neededBalance - nftBalance;
//Transfer to Aavegotchi
LibItems.removeFromOwner(sender, wearableId, balToTransfer);
LibItems.addToParent(address(this), _tokenId, wearableId, balToTransfer);
emit TransferToParent(address(this), _tokenId, wearableId, balToTransfer);
emit LibERC1155.TransferSingle(sender, sender, address(this), wearableId, balToTransfer);
LibERC1155Marketplace.updateERC1155Listing(address(this), wearableId, sender);
}
}
emit EquipWearables(_tokenId, aavegotchi.equippedWearables, _equippedWearables);
aavegotchi.equippedWearables = _equippedWearables;
LibAavegotchi.interact(_tokenId);
}
function useConsumables(
uint256 _tokenId,
uint256[] calldata _itemIds,
uint256[] calldata _quantities
) external onlyUnlocked(_tokenId) onlyAavegotchiOwner(_tokenId) {
require(_itemIds.length == _quantities.length, "ItemsFacet: _itemIds length does not match _quantities length");
require(s.aavegotchis[_tokenId].status == LibAavegotchi.STATUS_AAVEGOTCHI, "LibAavegotchi: Only valid for Aavegotchi");
address sender = LibMeta.msgSender();
for (uint256 i; i < _itemIds.length; i++) {
uint256 itemId = _itemIds[i];
uint256 quantity = _quantities[i];
ItemType memory itemType = s.itemTypes[itemId];
require(itemType.category == LibItems.ITEM_CATEGORY_CONSUMABLE, "ItemsFacet: Item must be consumable");
LibItems.removeFromOwner(sender, itemId, quantity);
//Increase kinship
if (itemType.kinshipBonus > 0) {
uint256 kinship = (uint256(int256(itemType.kinshipBonus)) * quantity) + s.aavegotchis[_tokenId].interactionCount;
s.aavegotchis[_tokenId].interactionCount = kinship;
} else if (itemType.kinshipBonus < 0) {
uint256 kinshipBonus = LibAppStorage.abs(itemType.kinshipBonus) * quantity;
if (s.aavegotchis[_tokenId].interactionCount > kinshipBonus) {
s.aavegotchis[_tokenId].interactionCount -= kinshipBonus;
} else {
s.aavegotchis[_tokenId].interactionCount = 0;
}
}
{
// prevent stack too deep error with braces here
//Boost traits and reset clock
bool boost = false;
for (uint256 j; j < NUMERIC_TRAITS_NUM; j++) {
if (itemType.traitModifiers[j] != 0) {
boost = true;
break;
}
}
if (boost) {
s.aavegotchis[_tokenId].lastTemporaryBoost = uint40(block.timestamp);
s.aavegotchis[_tokenId].temporaryTraitBoosts = itemType.traitModifiers;
}
}
//Increase experience
if (itemType.experienceBonus > 0) {
uint256 experience = (uint256(itemType.experienceBonus) * quantity) + s.aavegotchis[_tokenId].experience;
s.aavegotchis[_tokenId].experience = experience;
}
itemType.totalQuantity -= quantity;
LibAavegotchi.interact(_tokenId);
LibERC1155Marketplace.updateERC1155Listing(address(this), itemId, sender);
}
emit UseConsumables(_tokenId, _itemIds, _quantities);
emit LibERC1155.TransferBatch(sender, sender, address(0), _itemIds, _quantities);
}
function setWearableSlotPositions(uint256 _wearableId, bool[EQUIPPED_WEARABLE_SLOTS] calldata _slotPositions) external onlyDaoOrOwner {
require(_wearableId < s.itemTypes.length, "DAOFacet: _wearableId not found for item");
s.itemTypes[_wearableId].slotPositions = _slotPositions;
}
}
| Calculates the base rarity score, including collateral modifier | function baseRarityScore(int16[NUMERIC_TRAITS_NUM] memory _numericTraits) internal pure returns (uint256 _rarityScore) {
for (uint256 i; i < NUMERIC_TRAITS_NUM; i++) {
int256 number = _numericTraits[i];
if (number >= 50) {
_rarityScore += uint256(number) + 1;
_rarityScore += uint256(int256(100) - number);
}
}
}
| 2,501,944 |
pragma solidity ^0.4.24;
// Amis Dex OnChainOrderBook follows ERC20 Standards
contract ERC20 {
function totalSupply() constant returns (uint);
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
// Amis Dex on-chain order book matching engine Version 0.1.2.
// https://github.com/amisolution/ERC20-AMIS/contracts/OnChainOrderBookV012b.sol
// This smart contract is a variation of a neat ERC20 token as base, ETH as quoted,
// and standard fees with incentivized reward token.
// This contract allows minPriceExponent, baseMinInitialSize, and baseMinRemainingSize
// to be set at init() time appropriately for the token decimals and likely value.
//
contract OnChainOrderBookV012b {
enum BookType {
ERC20EthV1
}
enum Direction {
Invalid,
Buy,
Sell
}
enum Status {
Unknown,
Rejected,
Open,
Done,
NeedsGas,
Sending, // not used by contract - web UI only
FailedSend, // not used by contract - web UI only
FailedTxn // not used by contract - web UI only
}
enum ReasonCode {
None,
InvalidPrice,
InvalidSize,
InvalidTerms,
InsufficientFunds,
WouldTake,
Unmatched,
TooManyMatches,
ClientCancel
}
enum Terms {
GTCNoGasTopup,
GTCWithGasTopup,
ImmediateOrCancel,
MakerOnly
}
struct Order {
// these are immutable once placed:
address client;
uint16 price; // packed representation of side + price
uint sizeBase;
Terms terms;
// these are mutable until Done or Rejected:
Status status;
ReasonCode reasonCode;
uint128 executedBase; // gross amount executed in base currency (before fee deduction)
uint128 executedCntr; // gross amount executed in quoted currency (before fee deduction)
uint128 feesBaseOrCntr; // base for buy, cntr for sell
uint128 feesRwrd;
}
struct OrderChain {
uint128 firstOrderId;
uint128 lastOrderId;
}
struct OrderChainNode {
uint128 nextOrderId;
uint128 prevOrderId;
}
// Rebuild the expected state of the contract given:
// - ClientPaymentEvent log history
// - ClientOrderEvent log history
// - Calling getOrder for the other immutable order fields of orders referenced by ClientOrderEvent
enum ClientPaymentEventType {
Deposit,
Withdraw,
TransferFrom,
Transfer
}
enum BalanceType {
Base,
Cntr,
Rwrd
}
event ClientPaymentEvent(
address indexed client,
ClientPaymentEventType clientPaymentEventType,
BalanceType balanceType,
int clientBalanceDelta
);
enum ClientOrderEventType {
Create,
Continue,
Cancel
}
event ClientOrderEvent(
address indexed client,
ClientOrderEventType clientOrderEventType,
uint128 orderId,
uint maxMatches
);
enum MarketOrderEventType {
// orderCount++, depth += depthBase
Add,
// orderCount--, depth -= depthBase
Remove,
// orderCount--, depth -= depthBase, traded += tradeBase
// (depth change and traded change differ when tiny remaining amount refunded)
CompleteFill,
// orderCount unchanged, depth -= depthBase, traded += tradeBase
PartialFill
}
// Technically not needed but these events can be used to maintain an order book or
// watch for fills. Note that the orderId and price are those of the maker.
event MarketOrderEvent(
uint256 indexed eventTimestamp,
uint128 indexed orderId,
MarketOrderEventType marketOrderEventType,
uint16 price,
uint depthBase,
uint tradeBase
);
// the base token (e.g. AMIS)
ERC20 baseToken;
// minimum order size (inclusive)
uint baseMinInitialSize; // set at init
// if following partial match, the remaining gets smaller than this, remove from Order Book and refund:
// generally we make this 10% of baseMinInitialSize
uint baseMinRemainingSize; // set at init
// maximum order size (exclusive)
// chosen so that even multiplied by the max price (or divided by the min price),
// and then multiplied by ethRwrdRate, it still fits in 2^127, allowing us to save
// some gas by storing executed + fee fields as uint128.
// even with 18 decimals, this still allows order sizes up to 1,000,000,000.
// if we encounter a token with e.g. 36 decimals we'll have to revisit ...
uint constant baseMaxSize = 10 ** 30;
// the counter currency or ETH traded pair
// (no address because it is ETH)
// avoid the book getting cluttered up with tiny amounts not worth the gas
uint constant cntrMinInitialSize = 10 finney;
// see comments for baseMaxSize
uint constant cntrMaxSize = 10 ** 30;
// the reward token that can be used to pay fees (AMIS / ORA / CRSW)
ERC20 rwrdToken; // set at init
// used to convert ETH amount to reward tokens when paying fee with reward tokens
uint constant ethRwrdRate = 1000;
// funds that belong to clients (base, counter, and reward)
mapping (address => uint) balanceBaseForClient;
mapping (address => uint) balanceCntrForClient;
mapping (address => uint) balanceRwrdForClient;
// fee charged on liquidity taken, expressed as a divisor
// (e.g. 2000 means 1/2000, or 0.05%)
uint constant feeDivisor = 2000;
// fees charged are given to:
address feeCollector; // set at init
// all orders ever created
mapping (uint128 => Order) orderForOrderId;
// Effectively a compact mapping from price to whether there are any open orders at that price.
// See "Price Calculation Constants" below as to why 85.
uint256[85] occupiedPriceBitmaps;
// These allow us to walk over the orders in the book at a given price level (and add more).
mapping (uint16 => OrderChain) orderChainForOccupiedPrice;
mapping (uint128 => OrderChainNode) orderChainNodeForOpenOrderId;
// These allow a client to (reasonably) efficiently find their own orders
// without relying on events (which even indexed are a bit expensive to search
// and cannot be accessed from smart contracts). See walkOrders.
mapping (address => uint128) mostRecentOrderIdForClient;
mapping (uint128 => uint128) clientPreviousOrderIdBeforeOrderId;
// Price Calculation Constants.
//
// We pack direction and price into a crafty decimal floating point representation
// for efficient indexing by price, the main thing we lose by doing so is precision -
// we only have 3 significant figures in our prices.
//
// An unpacked price consists of:
//
// direction - invalid / buy / sell
// mantissa - ranges from 100 to 999 representing 0.100 to 0.999
// exponent - ranges from minimumPriceExponent to minimumPriceExponent + 11
// (e.g. -5 to +6 for a typical pair where minPriceExponent = -5)
//
// The packed representation has 21601 different price values:
//
// 0 = invalid (can be used as marker value)
// 1 = buy at maximum price (0.999 * 10 ** 6)
// ... = other buy prices in descending order
// 5400 = buy at 1.00
// ... = other buy prices in descending order
// 10800 = buy at minimum price (0.100 * 10 ** -5)
// 10801 = sell at minimum price (0.100 * 10 ** -5)
// ... = other sell prices in descending order
// 16201 = sell at 1.00
// ... = other sell prices in descending order
// 21600 = sell at maximum price (0.999 * 10 ** 6)
// 21601+ = do not use
//
// If we want to map each packed price to a boolean value (which we do),
// we require 85 256-bit words. Or 42.5 for each side of the book.
int8 minPriceExponent; // set at init
uint constant invalidPrice = 0;
// careful: max = largest unpacked value, not largest packed value
uint constant maxBuyPrice = 1;
uint constant minBuyPrice = 10800;
uint constant minSellPrice = 10801;
uint constant maxSellPrice = 21600;
// Constructor.
//
// Sets feeCollector to the creator. Creator needs to call init() to finish setup.
//
function OnChainOrderBookV012b() {
address creator = msg.sender;
feeCollector = creator;
}
// "Public" Management - set address of base and reward tokens.
//
// Can only be done once (normally immediately after creation) by the fee collector.
//
// Used instead of a constructor to make deployment easier.
//
// baseMinInitialSize is the minimum order size in token-wei;
// the minimum resting size will be one tenth of that.
//
// minPriceExponent controls the range of prices supported by the contract;
// the range will be 0.100*10**minPriceExponent to 0.999*10**(minPriceExponent + 11)
// but careful; this is in token-wei : wei, ignoring the number of decimals of the token
// e.g. -5 implies 1 token-wei worth between 0.100e-5 to 0.999e+6 wei
// which implies same token:eth exchange rate if token decimals are 18 like eth,
// but if token decimals are 8, that would imply 1 token worth 10 wei to 0.000999 ETH.
//
function init(ERC20 _baseToken, ERC20 _rwrdToken, uint _baseMinInitialSize, int8 _minPriceExponent) public {
require(msg.sender == feeCollector);
require(address(baseToken) == 0);
require(address(_baseToken) != 0);
require(address(rwrdToken) == 0);
require(address(_rwrdToken) != 0);
require(_baseMinInitialSize >= 10);
require(_baseMinInitialSize < baseMaxSize / 1000000);
require(_minPriceExponent >= -20 && _minPriceExponent <= 20);
if (_minPriceExponent < 2) {
require(_baseMinInitialSize >= 10 ** uint(3-int(minPriceExponent)));
}
baseMinInitialSize = _baseMinInitialSize;
// dust prevention. truncation ok, know >= 10
baseMinRemainingSize = _baseMinInitialSize / 10;
minPriceExponent = _minPriceExponent;
// attempt to catch bad tokens:
require(_baseToken.totalSupply() > 0);
baseToken = _baseToken;
require(_rwrdToken.totalSupply() > 0);
rwrdToken = _rwrdToken;
}
// "Public" Management - change fee collector
//
// The new fee collector only gets fees charged after this point.
//
function changeFeeCollector(address newFeeCollector) public {
address oldFeeCollector = feeCollector;
require(msg.sender == oldFeeCollector);
require(newFeeCollector != oldFeeCollector);
feeCollector = newFeeCollector;
}
// Public Info View - what is being traded here, what are the limits?
//
function getBookInfo() public constant returns (
BookType _bookType, address _baseToken, address _rwrdToken,
uint _baseMinInitialSize, uint _cntrMinInitialSize, int8 _minPriceExponent,
uint _feeDivisor, address _feeCollector
) {
return (
BookType.ERC20EthV1,
address(baseToken),
address(rwrdToken),
baseMinInitialSize, // can assume min resting size is one tenth of this
cntrMinInitialSize,
minPriceExponent,
feeDivisor,
feeCollector
);
}
// Public Funds View - get balances held by contract on behalf of the client,
// or balances approved for deposit but not yet claimed by the contract.
//
// Excludes funds in open orders.
//
// Helps a web ui get a consistent snapshot of balances.
//
// It would be nice to return the off-exchange ETH balance too but there's a
// bizarre bug in geth (and apparently as a result via MetaMask) that leads
// to unpredictable behaviour when looking up client balances in constant
// functions - see e.g. https://github.com/ethereum/solidity/issues/2325 .
//
function getClientBalances(address client) public constant returns (
uint bookBalanceBase,
uint bookBalanceCntr,
uint bookBalanceRwrd,
uint approvedBalanceBase,
uint approvedBalanceRwrd,
uint ownBalanceBase,
uint ownBalanceRwrd
) {
bookBalanceBase = balanceBaseForClient[client];
bookBalanceCntr = balanceCntrForClient[client];
bookBalanceRwrd = balanceRwrdForClient[client];
approvedBalanceBase = baseToken.allowance(client, address(this));
approvedBalanceRwrd = rwrdToken.allowance(client, address(this));
ownBalanceBase = baseToken.balanceOf(client);
ownBalanceRwrd = rwrdToken.balanceOf(client);
}
// Public Funds moves - deposit previously-approved base tokens.
//
function transferFromBase() public {
address client = msg.sender;
address book = address(this);
// we trust the ERC20 token contract not to do nasty things like call back into us -
// if we cannot trust the token then why are we allowing it to be traded?
uint amountBase = baseToken.allowance(client, book);
require(amountBase > 0);
// NB: needs change for older ERC20 tokens that don't return bool
require(baseToken.transferFrom(client, book, amountBase));
// belt and braces
assert(baseToken.allowance(client, book) == 0);
balanceBaseForClient[client] += amountBase;
ClientPaymentEvent(client, ClientPaymentEventType.TransferFrom, BalanceType.Base, int(amountBase));
}
// Public Funds moves - withdraw base tokens (as a transfer).
//
function transferBase(uint amountBase) public {
address client = msg.sender;
require(amountBase > 0);
require(amountBase <= balanceBaseForClient[client]);
// overflow safe since we checked less than balance above
balanceBaseForClient[client] -= amountBase;
// we trust the ERC20 token contract not to do nasty things like call back into us -
require(baseToken.transfer(client, amountBase));
ClientPaymentEvent(client, ClientPaymentEventType.Transfer, BalanceType.Base, -int(amountBase));
}
// Public Funds moves - deposit counter quoted currency (ETH or DAI).
//
function depositCntr() public payable {
address client = msg.sender;
uint amountCntr = msg.value;
require(amountCntr > 0);
// overflow safe - if someone owns pow(2,255) ETH we have bigger problems
balanceCntrForClient[client] += amountCntr;
ClientPaymentEvent(client, ClientPaymentEventType.Deposit, BalanceType.Cntr, int(amountCntr));
}
// Public Funds Move - withdraw counter quoted currency (ETH or DAI).
//
function withdrawCntr(uint amountCntr) public {
address client = msg.sender;
require(amountCntr > 0);
require(amountCntr <= balanceCntrForClient[client]);
// overflow safe - checked less than balance above
balanceCntrForClient[client] -= amountCntr;
// safe - not enough gas to do anything interesting in fallback, already adjusted balance
client.transfer(amountCntr);
ClientPaymentEvent(client, ClientPaymentEventType.Withdraw, BalanceType.Cntr, -int(amountCntr));
}
// Public Funds Move - deposit previously-approved incentivized reward tokens.
//
function transferFromRwrd() public {
address client = msg.sender;
address book = address(this);
uint amountRwrd = rwrdToken.allowance(client, book);
require(amountRwrd > 0);
// we created the incentivized reward token so we know it supports ERC20 properly and is not evil
require(rwrdToken.transferFrom(client, book, amountRwrd));
// belt and braces
assert(rwrdToken.allowance(client, book) == 0);
balanceRwrdForClient[client] += amountRwrd;
ClientPaymentEvent(client, ClientPaymentEventType.TransferFrom, BalanceType.Rwrd, int(amountRwrd));
}
// Public Funds Manipulation - withdraw base tokens (as a transfer).
//
function transferRwrd(uint amountRwrd) public {
address client = msg.sender;
require(amountRwrd > 0);
require(amountRwrd <= balanceRwrdForClient[client]);
// overflow safe - checked less than balance above
balanceRwrdForClient[client] -= amountRwrd;
// we created the incentivized reward token so we know it supports ERC20 properly and is not evil
require(rwrdToken.transfer(client, amountRwrd));
ClientPaymentEvent(client, ClientPaymentEventType.Transfer, BalanceType.Rwrd, -int(amountRwrd));
}
// Public Order View - get full details of an order.
//
// If the orderId does not exist, status will be Unknown.
//
function getOrder(uint128 orderId) public constant returns (
address client, uint16 price, uint sizeBase, Terms terms,
Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr,
uint feesBaseOrCntr, uint feesRwrd) {
Order storage order = orderForOrderId[orderId];
return (order.client, order.price, order.sizeBase, order.terms,
order.status, order.reasonCode, order.executedBase, order.executedCntr,
order.feesBaseOrCntr, order.feesRwrd);
}
// Public Order View - get mutable details of an order.
//
// If the orderId does not exist, status will be Unknown.
//
function getOrderState(uint128 orderId) public constant returns (
Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr,
uint feesBaseOrCntr, uint feesRwrd) {
Order storage order = orderForOrderId[orderId];
return (order.status, order.reasonCode, order.executedBase, order.executedCntr,
order.feesBaseOrCntr, order.feesRwrd);
}
// Public Order View - enumerate all recent orders + all open orders for one client.
//
// Not really designed for use from a smart contract transaction.
// Baseline concept:
// - client ensures order ids are generated so that most-signficant part is time-based;
// - client decides they want all orders after a certain point-in-time,
// and chooses minClosedOrderIdCutoff accordingly;
// - before that point-in-time they just get open and needs gas orders
// - client calls walkClientOrders with maybeLastOrderIdReturned = 0 initially;
// - then repeats with the orderId returned by walkClientOrders;
// - (and stops if it returns a zero orderId);
//
// Note that client is only used when maybeLastOrderIdReturned = 0.
//
function walkClientOrders(
address client, uint128 maybeLastOrderIdReturned, uint128 minClosedOrderIdCutoff
) public constant returns (
uint128 orderId, uint16 price, uint sizeBase, Terms terms,
Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr,
uint feesBaseOrCntr, uint feesRwrd) {
if (maybeLastOrderIdReturned == 0) {
orderId = mostRecentOrderIdForClient[client];
} else {
orderId = clientPreviousOrderIdBeforeOrderId[maybeLastOrderIdReturned];
}
while (true) {
if (orderId == 0) return;
Order storage order = orderForOrderId[orderId];
if (orderId >= minClosedOrderIdCutoff) break;
if (order.status == Status.Open || order.status == Status.NeedsGas) break;
orderId = clientPreviousOrderIdBeforeOrderId[orderId];
}
return (orderId, order.price, order.sizeBase, order.terms,
order.status, order.reasonCode, order.executedBase, order.executedCntr,
order.feesBaseOrCntr, order.feesRwrd);
}
// Internal Price Calculation - turn packed price into a friendlier unpacked price.
//
function unpackPrice(uint16 price) internal constant returns (
Direction direction, uint16 mantissa, int8 exponent
) {
uint sidedPriceIndex = uint(price);
uint priceIndex;
if (sidedPriceIndex < 1 || sidedPriceIndex > maxSellPrice) {
direction = Direction.Invalid;
mantissa = 0;
exponent = 0;
return;
} else if (sidedPriceIndex <= minBuyPrice) {
direction = Direction.Buy;
priceIndex = minBuyPrice - sidedPriceIndex;
} else {
direction = Direction.Sell;
priceIndex = sidedPriceIndex - minSellPrice;
}
uint zeroBasedMantissa = priceIndex % 900;
uint zeroBasedExponent = priceIndex / 900;
mantissa = uint16(zeroBasedMantissa + 100);
exponent = int8(zeroBasedExponent) + minPriceExponent;
return;
}
// Internal Price Calculation - is a packed price on the buy side?
//
// Throws an error if price is invalid.
//
function isBuyPrice(uint16 price) internal constant returns (bool isBuy) {
// yes, this looks odd, but max here is highest _unpacked_ price
return price >= maxBuyPrice && price <= minBuyPrice;
}
// Internal Price Calculation - turn a packed buy price into a packed sell price.
//
// Invalid price remains invalid.
//
function computeOppositePrice(uint16 price) internal constant returns (uint16 opposite) {
if (price < maxBuyPrice || price > maxSellPrice) {
return uint16(invalidPrice);
} else if (price <= minBuyPrice) {
return uint16(maxSellPrice - (price - maxBuyPrice));
} else {
return uint16(maxBuyPrice + (maxSellPrice - price));
}
}
// Internal Price Calculation - compute amount in counter currency that would
// be obtained by selling baseAmount at the given unpacked price (if no fees).
//
// Notes:
// - Does not validate price - caller must ensure valid.
// - Could overflow producing very unexpected results if baseAmount very
// large - caller must check this.
// - This rounds the amount towards zero.
// - May truncate to zero if baseAmount very small - potentially allowing
// zero-cost buys or pointless sales - caller must check this.
//
function computeCntrAmountUsingUnpacked(
uint baseAmount, uint16 mantissa, int8 exponent
) internal constant returns (uint cntrAmount) {
if (exponent < 0) {
return baseAmount * uint(mantissa) / 1000 / 10 ** uint(-exponent);
} else {
return baseAmount * uint(mantissa) / 1000 * 10 ** uint(exponent);
}
}
// Internal Price Calculation - compute amount in counter currency that would
// be obtained by selling baseAmount at the given packed price (if no fees).
//
// Notes:
// - Does not validate price - caller must ensure valid.
// - Direction of the packed price is ignored.
// - Could overflow producing very unexpected results if baseAmount very
// large - caller must check this.
// - This rounds the amount towards zero (regardless of Buy or Sell).
// - May truncate to zero if baseAmount very small - potentially allowing
// zero-cost buys or pointless sales - caller must check this.
//
function computeCntrAmountUsingPacked(
uint baseAmount, uint16 price
) internal constant returns (uint) {
var (, mantissa, exponent) = unpackPrice(price);
return computeCntrAmountUsingUnpacked(baseAmount, mantissa, exponent);
}
// Public Order Placement - create order and try to match it and/or add it to the book.
//
function createOrder(
uint128 orderId, uint16 price, uint sizeBase, Terms terms, uint maxMatches
) public {
address client = msg.sender;
require(orderId != 0 && orderForOrderId[orderId].client == 0);
ClientOrderEvent(client, ClientOrderEventType.Create, orderId, maxMatches);
orderForOrderId[orderId] =
Order(client, price, sizeBase, terms, Status.Unknown, ReasonCode.None, 0, 0, 0, 0);
uint128 previousMostRecentOrderIdForClient = mostRecentOrderIdForClient[client];
mostRecentOrderIdForClient[client] = orderId;
clientPreviousOrderIdBeforeOrderId[orderId] = previousMostRecentOrderIdForClient;
Order storage order = orderForOrderId[orderId];
var (direction, mantissa, exponent) = unpackPrice(price);
if (direction == Direction.Invalid) {
order.status = Status.Rejected;
order.reasonCode = ReasonCode.InvalidPrice;
return;
}
if (sizeBase < baseMinInitialSize || sizeBase > baseMaxSize) {
order.status = Status.Rejected;
order.reasonCode = ReasonCode.InvalidSize;
return;
}
uint sizeCntr = computeCntrAmountUsingUnpacked(sizeBase, mantissa, exponent);
if (sizeCntr < cntrMinInitialSize || sizeCntr > cntrMaxSize) {
order.status = Status.Rejected;
order.reasonCode = ReasonCode.InvalidSize;
return;
}
if (terms == Terms.MakerOnly && maxMatches != 0) {
order.status = Status.Rejected;
order.reasonCode = ReasonCode.InvalidTerms;
return;
}
if (!debitFunds(client, direction, sizeBase, sizeCntr)) {
order.status = Status.Rejected;
order.reasonCode = ReasonCode.InsufficientFunds;
return;
}
processOrder(orderId, maxMatches);
}
// Public Order Placement - cancel order
//
function cancelOrder(uint128 orderId) public {
address client = msg.sender;
Order storage order = orderForOrderId[orderId];
require(order.client == client);
Status status = order.status;
if (status != Status.Open && status != Status.NeedsGas) {
return;
}
ClientOrderEvent(client, ClientOrderEventType.Cancel, orderId, 0);
if (status == Status.Open) {
removeOpenOrderFromBook(orderId);
MarketOrderEvent(block.timestamp, orderId, MarketOrderEventType.Remove, order.price,
order.sizeBase - order.executedBase, 0);
}
refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.ClientCancel);
}
// Public Order Placement - continue placing an order in 'NeedsGas' state
//
function continueOrder(uint128 orderId, uint maxMatches) public {
address client = msg.sender;
Order storage order = orderForOrderId[orderId];
require(order.client == client);
if (order.status != Status.NeedsGas) {
return;
}
ClientOrderEvent(client, ClientOrderEventType.Continue, orderId, maxMatches);
order.status = Status.Unknown;
processOrder(orderId, maxMatches);
}
// Internal Order Placement - remove a still-open order from the book.
//
// Caller's job to update/refund the order + raise event, this just
// updates the order chain and bitmask.
//
// Too expensive to do on each resting order match - we only do this for an
// order being cancelled. See matchWithOccupiedPrice for similar logic.
//
function removeOpenOrderFromBook(uint128 orderId) internal {
Order storage order = orderForOrderId[orderId];
uint16 price = order.price;
OrderChain storage orderChain = orderChainForOccupiedPrice[price];
OrderChainNode storage orderChainNode = orderChainNodeForOpenOrderId[orderId];
uint128 nextOrderId = orderChainNode.nextOrderId;
uint128 prevOrderId = orderChainNode.prevOrderId;
if (nextOrderId != 0) {
OrderChainNode storage nextOrderChainNode = orderChainNodeForOpenOrderId[nextOrderId];
nextOrderChainNode.prevOrderId = prevOrderId;
} else {
orderChain.lastOrderId = prevOrderId;
}
if (prevOrderId != 0) {
OrderChainNode storage prevOrderChainNode = orderChainNodeForOpenOrderId[prevOrderId];
prevOrderChainNode.nextOrderId = nextOrderId;
} else {
orderChain.firstOrderId = nextOrderId;
}
if (nextOrderId == 0 && prevOrderId == 0) {
uint bmi = price / 256; // index into array of bitmaps
uint bti = price % 256; // bit position within bitmap
// we know was previously occupied so XOR clears
occupiedPriceBitmaps[bmi] ^= 2 ** bti;
}
}
// Internal Order Placement - credit funds received when taking liquidity from book
//
function creditExecutedFundsLessFees(uint128 orderId, uint originalExecutedBase, uint originalExecutedCntr) internal {
Order storage order = orderForOrderId[orderId];
uint liquidityTakenBase = order.executedBase - originalExecutedBase;
uint liquidityTakenCntr = order.executedCntr - originalExecutedCntr;
// Normally we deduct the fee from the currency bought (base for buy, cntr for sell),
// however we also accept reward tokens from the reward balance if it covers the fee,
// with the reward amount converted from the ETH amount (the counter currency here)
// at a fixed exchange rate.
// Overflow safe since we ensure order size < 10^30 in both currencies (see baseMaxSize).
// Can truncate to zero, which is fine.
uint feesRwrd = liquidityTakenCntr / feeDivisor * ethRwrdRate;
uint feesBaseOrCntr;
address client = order.client;
uint availRwrd = balanceRwrdForClient[client];
if (feesRwrd <= availRwrd) {
balanceRwrdForClient[client] = availRwrd - feesRwrd;
balanceRwrdForClient[feeCollector] = feesRwrd;
// Need += rather than = because could have paid some fees earlier in NeedsGas situation.
// Overflow safe since we ensure order size < 10^30 in both currencies (see baseMaxSize).
// Can truncate to zero, which is fine.
order.feesRwrd += uint128(feesRwrd);
if (isBuyPrice(order.price)) {
balanceBaseForClient[client] += liquidityTakenBase;
} else {
balanceCntrForClient[client] += liquidityTakenCntr;
}
} else if (isBuyPrice(order.price)) {
// See comments in branch above re: use of += and overflow safety.
feesBaseOrCntr = liquidityTakenBase / feeDivisor;
balanceBaseForClient[order.client] += (liquidityTakenBase - feesBaseOrCntr);
order.feesBaseOrCntr += uint128(feesBaseOrCntr);
balanceBaseForClient[feeCollector] += feesBaseOrCntr;
} else {
// See comments in branch above re: use of += and overflow safety.
feesBaseOrCntr = liquidityTakenCntr / feeDivisor;
balanceCntrForClient[order.client] += (liquidityTakenCntr - feesBaseOrCntr);
order.feesBaseOrCntr += uint128(feesBaseOrCntr);
balanceCntrForClient[feeCollector] += feesBaseOrCntr;
}
}
// Internal Order Placement - process a created and sanity checked order.
//
// Used both for new orders and for gas topup.
//
function processOrder(uint128 orderId, uint maxMatches) internal {
Order storage order = orderForOrderId[orderId];
uint ourOriginalExecutedBase = order.executedBase;
uint ourOriginalExecutedCntr = order.executedCntr;
var (ourDirection,) = unpackPrice(order.price);
uint theirPriceStart = (ourDirection == Direction.Buy) ? minSellPrice : maxBuyPrice;
uint theirPriceEnd = computeOppositePrice(order.price);
MatchStopReason matchStopReason =
matchAgainstBook(orderId, theirPriceStart, theirPriceEnd, maxMatches);
creditExecutedFundsLessFees(orderId, ourOriginalExecutedBase, ourOriginalExecutedCntr);
if (order.terms == Terms.ImmediateOrCancel) {
if (matchStopReason == MatchStopReason.Satisfied) {
refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.None);
return;
} else if (matchStopReason == MatchStopReason.MaxMatches) {
refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.TooManyMatches);
return;
} else if (matchStopReason == MatchStopReason.BookExhausted) {
refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.Unmatched);
return;
}
} else if (order.terms == Terms.MakerOnly) {
if (matchStopReason == MatchStopReason.MaxMatches) {
refundUnmatchedAndFinish(orderId, Status.Rejected, ReasonCode.WouldTake);
return;
} else if (matchStopReason == MatchStopReason.BookExhausted) {
enterOrder(orderId);
return;
}
} else if (order.terms == Terms.GTCNoGasTopup) {
if (matchStopReason == MatchStopReason.Satisfied) {
refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.None);
return;
} else if (matchStopReason == MatchStopReason.MaxMatches) {
refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.TooManyMatches);
return;
} else if (matchStopReason == MatchStopReason.BookExhausted) {
enterOrder(orderId);
return;
}
} else if (order.terms == Terms.GTCWithGasTopup) {
if (matchStopReason == MatchStopReason.Satisfied) {
refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.None);
return;
} else if (matchStopReason == MatchStopReason.MaxMatches) {
order.status = Status.NeedsGas;
return;
} else if (matchStopReason == MatchStopReason.BookExhausted) {
enterOrder(orderId);
return;
}
}
assert(false); // should not be possible to reach here
}
// Used internally to indicate why we stopped matching an order against the book.
enum MatchStopReason {
None,
MaxMatches,
Satisfied,
PriceExhausted,
BookExhausted
}
// Internal Order Placement - Match the given order against the book.
//
// Resting orders matched will be updated, removed from book and funds credited to their owners.
//
// Only updates the executedBase and executedCntr of the given order - caller is responsible
// for crediting matched funds, charging fees, marking order as done / entering it into the book.
//
// matchStopReason returned will be one of MaxMatches, Satisfied or BookExhausted.
//
// Calling with maxMatches == 0 is ok - and expected when the order is a maker-only order.
//
function matchAgainstBook(
uint128 orderId, uint theirPriceStart, uint theirPriceEnd, uint maxMatches
) internal returns (
MatchStopReason matchStopReason
) {
Order storage order = orderForOrderId[orderId];
uint bmi = theirPriceStart / 256; // index into array of bitmaps
uint bti = theirPriceStart % 256; // bit position within bitmap
uint bmiEnd = theirPriceEnd / 256; // last bitmap to search
uint btiEnd = theirPriceEnd % 256; // stop at this bit in the last bitmap
uint cbm = occupiedPriceBitmaps[bmi]; // original copy of current bitmap
uint dbm = cbm; // dirty version of current bitmap where we may have cleared bits
uint wbm = cbm >> bti; // working copy of current bitmap which we keep shifting
// Optimized loops could render a better matching engine yet!
bool removedLastAtPrice;
matchStopReason = MatchStopReason.None;
while (bmi < bmiEnd) {
if (wbm == 0 || bti == 256) {
if (dbm != cbm) {
occupiedPriceBitmaps[bmi] = dbm;
}
bti = 0;
bmi++;
cbm = occupiedPriceBitmaps[bmi];
wbm = cbm;
dbm = cbm;
} else {
if ((wbm & 1) != 0) {
// careful - copy-and-pasted in loop below ...
(removedLastAtPrice, maxMatches, matchStopReason) =
matchWithOccupiedPrice(order, uint16(bmi * 256 + bti), maxMatches);
if (removedLastAtPrice) {
dbm ^= 2 ** bti;
}
if (matchStopReason == MatchStopReason.PriceExhausted) {
matchStopReason = MatchStopReason.None;
} else if (matchStopReason != MatchStopReason.None) {
// we might still have changes in dbm to write back - see later
break;
}
}
bti += 1;
wbm /= 2;
}
}
if (matchStopReason == MatchStopReason.None) {
// we've reached the last bitmap we need to search,
// we'll stop at btiEnd not 256 this time.
while (bti <= btiEnd && wbm != 0) {
if ((wbm & 1) != 0) {
// careful - copy-and-pasted in loop above ...
(removedLastAtPrice, maxMatches, matchStopReason) =
matchWithOccupiedPrice(order, uint16(bmi * 256 + bti), maxMatches);
if (removedLastAtPrice) {
dbm ^= 2 ** bti;
}
if (matchStopReason == MatchStopReason.PriceExhausted) {
matchStopReason = MatchStopReason.None;
} else if (matchStopReason != MatchStopReason.None) {
break;
}
}
bti += 1;
wbm /= 2;
}
}
// Careful - if we exited the first loop early, or we went into the second loop,
// (luckily can't both happen) then we haven't flushed the dirty bitmap back to
// storage - do that now if we need to.
if (dbm != cbm) {
occupiedPriceBitmaps[bmi] = dbm;
}
if (matchStopReason == MatchStopReason.None) {
matchStopReason = MatchStopReason.BookExhausted;
}
}
// Internal Order Placement.
//
// Match our order against up to maxMatches resting orders at the given price (which
// is known by the caller to have at least one resting order).
//
// The matches (partial or complete) of the resting orders are recorded, and their
// funds are credited.
//
// The on chain orderbook with resting orders is updated, but the occupied price bitmap is NOT -
// the caller must clear the relevant bit if removedLastAtPrice = true is returned.
//
// Only updates the executedBase and executedCntr of our order - caller is responsible
// for e.g. crediting our matched funds, updating status.
//
// Calling with maxMatches == 0 is ok - and expected when the order is a maker-only order.
//
// Returns:
// removedLastAtPrice:
// true iff there are no longer any resting orders at this price - caller will need
// to update the occupied price bitmap.
//
// matchesLeft:
// maxMatches passed in minus the number of matches made by this call
//
// matchStopReason:
// If our order is completely matched, matchStopReason will be Satisfied.
// If our order is not completely matched, matchStopReason will be either:
// MaxMatches (we are not allowed to match any more times)
// or:
// PriceExhausted (nothing left on the book at this exact price)
//
function matchWithOccupiedPrice(
Order storage ourOrder, uint16 theirPrice, uint maxMatches
) internal returns (
bool removedLastAtPrice, uint matchesLeft, MatchStopReason matchStopReason) {
matchesLeft = maxMatches;
uint workingOurExecutedBase = ourOrder.executedBase;
uint workingOurExecutedCntr = ourOrder.executedCntr;
uint128 theirOrderId = orderChainForOccupiedPrice[theirPrice].firstOrderId;
matchStopReason = MatchStopReason.None;
while (true) {
if (matchesLeft == 0) {
matchStopReason = MatchStopReason.MaxMatches;
break;
}
uint matchBase;
uint matchCntr;
(theirOrderId, matchBase, matchCntr, matchStopReason) =
matchWithTheirs((ourOrder.sizeBase - workingOurExecutedBase), theirOrderId, theirPrice);
workingOurExecutedBase += matchBase;
workingOurExecutedCntr += matchCntr;
matchesLeft -= 1;
if (matchStopReason != MatchStopReason.None) {
break;
}
}
ourOrder.executedBase = uint128(workingOurExecutedBase);
ourOrder.executedCntr = uint128(workingOurExecutedCntr);
if (theirOrderId == 0) {
orderChainForOccupiedPrice[theirPrice].firstOrderId = 0;
orderChainForOccupiedPrice[theirPrice].lastOrderId = 0;
removedLastAtPrice = true;
} else {
// NB: in some cases (e.g. maxMatches == 0) this is a no-op.
orderChainForOccupiedPrice[theirPrice].firstOrderId = theirOrderId;
orderChainNodeForOpenOrderId[theirOrderId].prevOrderId = 0;
removedLastAtPrice = false;
}
}
// Internal Order Placement.
//
// Match up to our remaining amount against a resting order in the book.
//
// The match (partial, complete or effectively-complete) of the resting order
// is recorded, and their funds are credited.
//
// Their order is NOT removed from the book by this call - the caller must do that
// if the nextTheirOrderId returned is not equal to the theirOrderId passed in.
//
// Returns:
//
// nextTheirOrderId:
// If we did not completely match their order, will be same as theirOrderId.
// If we completely matched their order, will be orderId of next order at the
// same price - or zero if this was the last order and we've now filled it.
//
// matchStopReason:
// If our order is completely matched, matchStopReason will be Satisfied.
// If our order is not completely matched, matchStopReason will be either
// PriceExhausted (if nothing left at this exact price) or None (if can continue).
//
function matchWithTheirs(
uint ourRemainingBase, uint128 theirOrderId, uint16 theirPrice) internal returns (
uint128 nextTheirOrderId, uint matchBase, uint matchCntr, MatchStopReason matchStopReason) {
Order storage theirOrder = orderForOrderId[theirOrderId];
uint theirRemainingBase = theirOrder.sizeBase - theirOrder.executedBase;
if (ourRemainingBase < theirRemainingBase) {
matchBase = ourRemainingBase;
} else {
matchBase = theirRemainingBase;
}
matchCntr = computeCntrAmountUsingPacked(matchBase, theirPrice);
// It may seem a bit odd to stop here if our remaining amount is very small -
// there could still be resting orders we can match it against. During network congestion gas
// cost of matching each order can become quite high - potentially high enough to
// wipe out the profit the taker hopes for from trading the tiny amount left.
if ((ourRemainingBase - matchBase) < baseMinRemainingSize) {
matchStopReason = MatchStopReason.Satisfied;
} else {
matchStopReason = MatchStopReason.None;
}
bool theirsDead = recordTheirMatch(theirOrder, theirOrderId, theirPrice, matchBase, matchCntr);
if (theirsDead) {
nextTheirOrderId = orderChainNodeForOpenOrderId[theirOrderId].nextOrderId;
if (matchStopReason == MatchStopReason.None && nextTheirOrderId == 0) {
matchStopReason = MatchStopReason.PriceExhausted;
}
} else {
nextTheirOrderId = theirOrderId;
}
}
// Internal Order Placement.
//
// Record match (partial or complete) of resting order, and credit them their funds.
//
// If their order is completely matched, the order is marked as done,
// and "theirsDead" is returned as true.
//
// The order is NOT removed from the book by this call - the caller
// must do that if theirsDead is true.
//
// No sanity checks are made - the caller must be sure the order is
// not already done and has sufficient remaining. (Yes, we'd like to
// check here too but we cannot afford the gas).
//
function recordTheirMatch(
Order storage theirOrder, uint128 theirOrderId, uint16 theirPrice, uint matchBase, uint matchCntr
) internal returns (bool theirsDead) {
// they are a maker so no fees
// overflow safe - see comments about baseMaxSize
// executedBase cannot go > sizeBase due to logic in matchWithTheirs
theirOrder.executedBase += uint128(matchBase);
theirOrder.executedCntr += uint128(matchCntr);
if (isBuyPrice(theirPrice)) {
// they have bought base (using the counter they already paid when creating the order)
balanceBaseForClient[theirOrder.client] += matchBase;
} else {
// they have bought counter (using the base they already paid when creating the order)
balanceCntrForClient[theirOrder.client] += matchCntr;
}
uint stillRemainingBase = theirOrder.sizeBase - theirOrder.executedBase;
// avoid leaving tiny amounts in the book - refund remaining if too small
if (stillRemainingBase < baseMinRemainingSize) {
refundUnmatchedAndFinish(theirOrderId, Status.Done, ReasonCode.None);
// someone building an UI on top needs to know how much was match and how much was refund
MarketOrderEvent(block.timestamp, theirOrderId, MarketOrderEventType.CompleteFill,
theirPrice, matchBase + stillRemainingBase, matchBase);
return true;
} else {
MarketOrderEvent(block.timestamp, theirOrderId, MarketOrderEventType.PartialFill,
theirPrice, matchBase, matchBase);
return false;
}
}
// Internal Order Placement.
//
// Refund any unmatched funds in an order (based on executed vs size) and move to a final state.
//
// The order is NOT removed from the book by this call and no event is raised.
//
// No sanity checks are made - the caller must be sure the order has not already been refunded.
//
function refundUnmatchedAndFinish(uint128 orderId, Status status, ReasonCode reasonCode) internal {
Order storage order = orderForOrderId[orderId];
uint16 price = order.price;
if (isBuyPrice(price)) {
uint sizeCntr = computeCntrAmountUsingPacked(order.sizeBase, price);
balanceCntrForClient[order.client] += sizeCntr - order.executedCntr;
} else {
balanceBaseForClient[order.client] += order.sizeBase - order.executedBase;
}
order.status = status;
order.reasonCode = reasonCode;
}
// Internal Order Placement.
//
// Enter a not completely matched order into the book, marking the order as open.
//
// This updates the occupied price bitmap and chain.
//
// No sanity checks are made - the caller must be sure the order
// has some unmatched amount and has been paid for!
//
function enterOrder(uint128 orderId) internal {
Order storage order = orderForOrderId[orderId];
uint16 price = order.price;
OrderChain storage orderChain = orderChainForOccupiedPrice[price];
OrderChainNode storage orderChainNode = orderChainNodeForOpenOrderId[orderId];
if (orderChain.firstOrderId == 0) {
orderChain.firstOrderId = orderId;
orderChain.lastOrderId = orderId;
orderChainNode.nextOrderId = 0;
orderChainNode.prevOrderId = 0;
uint bitmapIndex = price / 256;
uint bitIndex = price % 256;
occupiedPriceBitmaps[bitmapIndex] |= (2 ** bitIndex);
} else {
uint128 existingLastOrderId = orderChain.lastOrderId;
OrderChainNode storage existingLastOrderChainNode = orderChainNodeForOpenOrderId[existingLastOrderId];
orderChainNode.nextOrderId = 0;
orderChainNode.prevOrderId = existingLastOrderId;
existingLastOrderChainNode.nextOrderId = orderId;
orderChain.lastOrderId = orderId;
}
MarketOrderEvent(block.timestamp, orderId, MarketOrderEventType.Add,
price, order.sizeBase - order.executedBase, 0);
order.status = Status.Open;
}
// Internal Order Placement.
//
// Charge the client for the cost of placing an order in the given direction.
//
// Return true if successful, false otherwise.
//
function debitFunds(
address client, Direction direction, uint sizeBase, uint sizeCntr
) internal returns (bool success) {
if (direction == Direction.Buy) {
uint availableCntr = balanceCntrForClient[client];
if (availableCntr < sizeCntr) {
return false;
}
balanceCntrForClient[client] = availableCntr - sizeCntr;
return true;
} else if (direction == Direction.Sell) {
uint availableBase = balanceBaseForClient[client];
if (availableBase < sizeBase) {
return false;
}
balanceBaseForClient[client] = availableBase - sizeBase;
return true;
} else {
return false;
}
}
// Public Book View
//
// Intended for public book depth enumeration from web3 (or similar).
//
// Not suitable for use from a smart contract transaction - gas usage
// could be very high if we have many orders at the same price.
//
// Start at the given inclusive price (and side) and walk down the book
// (getting less aggressive) until we find some open orders or reach the
// least aggressive price.
//
// Returns the price where we found the order(s), the depth at that price
// (zero if none found), order count there, and the current blockNumber.
//
// (The blockNumber is handy if you're taking a snapshot which you intend
// to keep up-to-date with the market order events).
//
// To walk through the on-chain orderbook, the caller should start by calling walkBook with the
// most aggressive buy price (Buy @ 999000).
// If the price returned is the least aggressive buy price (Buy @ 0.000001),
// the side is complete.
// Otherwise, call walkBook again with the (packed) price returned + 1.
// Then repeat for the sell side, starting with Sell @ 0.000001 and stopping
// when Sell @ 999000 is returned.
//
function walkBook(uint16 fromPrice) public constant returns (
uint16 price, uint depthBase, uint orderCount, uint blockNumber
) {
uint priceStart = fromPrice;
uint priceEnd = (isBuyPrice(fromPrice)) ? minBuyPrice : maxSellPrice;
// See comments in matchAgainstBook re: how these crazy loops work.
uint bmi = priceStart / 256;
uint bti = priceStart % 256;
uint bmiEnd = priceEnd / 256;
uint btiEnd = priceEnd % 256;
uint wbm = occupiedPriceBitmaps[bmi] >> bti;
while (bmi < bmiEnd) {
if (wbm == 0 || bti == 256) {
bti = 0;
bmi++;
wbm = occupiedPriceBitmaps[bmi];
} else {
if ((wbm & 1) != 0) {
// careful - copy-pasted in below loop
price = uint16(bmi * 256 + bti);
(depthBase, orderCount) = sumDepth(orderChainForOccupiedPrice[price].firstOrderId);
return (price, depthBase, orderCount, block.number);
}
bti += 1;
wbm /= 2;
}
}
// we've reached the last bitmap we need to search, stop at btiEnd not 256 this time.
while (bti <= btiEnd && wbm != 0) {
if ((wbm & 1) != 0) {
// careful - copy-pasted in above loop
price = uint16(bmi * 256 + bti);
(depthBase, orderCount) = sumDepth(orderChainForOccupiedPrice[price].firstOrderId);
return (price, depthBase, orderCount, block.number);
}
bti += 1;
wbm /= 2;
}
return (uint16(priceEnd), 0, 0, block.number);
}
// Internal Book View.
//
// See walkBook - adds up open depth at a price starting from an
// order which is assumed to be open. Careful - unlimited gas use.
//
function sumDepth(uint128 orderId) internal constant returns (uint depth, uint orderCount) {
while (true) {
Order storage order = orderForOrderId[orderId];
depth += order.sizeBase - order.executedBase;
orderCount++;
orderId = orderChainNodeForOpenOrderId[orderId].nextOrderId;
if (orderId == 0) {
return (depth, orderCount);
}
}
}
}
// helper for automating book creation
contract OnChainOrderBookV012bFactory {
event BookCreated (address bookAddress);
function OnChainOrderBookV012bFactory() {
}
function createBook(ERC20 _baseToken, ERC20 _rwrdToken, address _feeCollector, uint _baseMinInitialSize, int8 _minPriceExponent) public {
OnChainOrderBookV012b book = new OnChainOrderBookV012b();
book.init(_baseToken, _rwrdToken, _baseMinInitialSize, _minPriceExponent);
book.changeFeeCollector(_feeCollector);
BookCreated(address(book));
}
} | Internal Price Calculation - compute amount in counter currency that would be obtained by selling baseAmount at the given packed price (if no fees). Notes: - Does not validate price - caller must ensure valid. - Direction of the packed price is ignored. - Could overflow producing very unexpected results if baseAmount very large - caller must check this. - This rounds the amount towards zero (regardless of Buy or Sell). - May truncate to zero if baseAmount very small - potentially allowing zero-cost buys or pointless sales - caller must check this. | function computeCntrAmountUsingPacked(
uint baseAmount, uint16 price
) internal constant returns (uint) {
var (, mantissa, exponent) = unpackPrice(price);
return computeCntrAmountUsingUnpacked(baseAmount, mantissa, exponent);
}
| 914,675 |
./full_match/8453/0x74F13914DA24e94B15E12879fA969B345D3a4387/sources/contracts/airdrop/AirdropERC721.sol | Lets contract-owner send ERC721 tokens to a list of addresses. The token-owner should approve target tokens to Airdrop contract, which acts as operator for the tokens. _tokenAddress The contract address of the tokens to transfer. _tokenOwner The owner of the the tokens to transfer. _contents List containing recipient, tokenId to airdrop./ revert if failure is due to unapproved tokens | function airdrop(
address _tokenAddress,
address _tokenOwner,
AirdropContent[] calldata _contents
) external nonReentrant {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Not authorized.");
uint256 len = _contents.length;
for (uint256 i = 0; i < len; ) {
try
IERC721(_tokenAddress).safeTransferFrom(_tokenOwner, _contents[i].recipient, _contents[i].tokenId)
require(
(IERC721(_tokenAddress).ownerOf(_contents[i].tokenId) == _tokenOwner &&
address(this) == IERC721(_tokenAddress).getApproved(_contents[i].tokenId)) ||
IERC721(_tokenAddress).isApprovedForAll(_tokenOwner, address(this)),
"Not owner or approved"
);
emit AirdropFailed(_tokenAddress, _tokenOwner, _contents[i].recipient, _contents[i].tokenId);
}
unchecked {
i += 1;
}
}
| 11,551,432 |
./partial_match/1/0xDfE695026EafAaba6d880d966A4a3694b436c841/sources/GoldBars.sol | Return true if the token id is in the freezelist/ | function isFrozen(uint256 _tokenId) public virtual view returns(bool) {
return freezelist[_tokenId];
}
| 15,493,677 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "./ERC2981.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Pausable.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev {ERC1155} token
* Visit lifeliner.org for more information
*
*/
contract LifeLinerToken is
Context,
AccessControl,
ERC1155Burnable,
ERC1155Pausable,
ERC1155Supply,
ERC2981
{
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
struct TokenSettings {
uint256 tokenId;
uint256 maxAmount;
uint256 price;
}
// Contract name
string public name;
// Contract symbol
string public symbol;
mapping(uint256 => TokenSettings) private _saleRegistry;
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that
* deploys the contract.
*/
constructor(
string memory uri,
string memory _name,
string memory _symbol
) ERC1155(uri) {
name = _name;
symbol = _symbol;
_setDefaultRoyalty(msg.sender, 1000);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`, of token type `id`.
*
* See {ERC1155-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"CharityToken: must have minter role to mint"
);
_mint(to, id, amount, data);
}
function purchase(
uint256 id,
uint256 amount,
bytes memory data
) public payable {
TokenSettings memory saleTokenSettings = _saleRegistry[id];
require(
saleTokenSettings.maxAmount > 0,
"CharityToken: Token is not purchaseable"
);
require(
saleTokenSettings.maxAmount >= totalSupply(id) + amount,
"CharityToken: No tokens left to purchase"
);
require(
msg.value >= amount * saleTokenSettings.price,
"CharityToken: User did not send enough Ether for purchase"
);
_mint(msg.sender, id, amount, data);
}
/**
* @dev Withrawal all Funds sent to the contract to Owner
*
* Requirements:
* - `msg.sender` needs to be Owner and payable
*/
function withdrawalAll() external {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"CharityToken: must have admin role to withdrawal"
);
require(payable(msg.sender).send(address(this).balance));
}
/**
* @dev Withrawal all Funds sent to the contract to Owner
*
* Requirements:
* - `msg.sender` needs to be Owner and payable
*/
function setBaseURI(string memory _uri) external {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"CharityToken: must have role admin to change baseuri"
);
_setURI(_uri);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
*/
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"CharityToken: must have minter role to mint"
);
_mintBatch(to, ids, amounts, data);
}
function registerTokenForSale(
uint256 id,
uint256 maxAmount,
uint256 tokenPrice
) public payable {
require(
hasRole(MINTER_ROLE, _msgSender()),
"CharityToken: must have minter role to register new tokens for sale"
);
_saleRegistry[id] = TokenSettings(id, maxAmount, tokenPrice);
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"CharityToken: must have pauser role to unpause"
);
_unpause();
}
/**
* @dev Pauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"CharityToken: must have pauser role to pause"
);
_pause();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControl, ERC1155, ERC2981)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override(ERC1155, ERC1155Pausable, ERC1155Supply) {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/common/ERC2981.sol)
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
* fee is specified in basis points by default.
*
* _Available since v4.5._
*/
abstract contract ERC2981 is IERC2981, ERC165 {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @inheritdoc IERC2981
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
virtual
override
returns (address, uint256)
{
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, royaltyAmount);
}
/**
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
* override.
*/
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/**
* @dev Sets the royalty information that all ids in this contract will default to.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: invalid receiver");
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Sets the royalty information for a specific token id, overriding the global default.
*
* Requirements:
*
* - `tokenId` must be already minted.
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 feeNumerator
) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: Invalid parameters");
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Resets royalty information for the token id back to the global default.
*/
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
delete _tokenRoyaltyInfo[tokenId];
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^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;
if (lastIndex != toDeleteIndex) {
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] = valueIndex; // Replace lastvalue's index to valueIndex
}
// 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) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values 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));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^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
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Supply.sol)
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev Extension of ERC1155 that adds tracking of total supply per id.
*
* Useful for scenarios where Fungible and Non-fungible tokens have to be
* clearly identified. Note: While a totalSupply of 1 might mean the
* corresponding is an NFT, there is no guarantees that no other token with the
* same id are not going to be minted.
*/
abstract contract ERC1155Supply is ERC1155 {
mapping(uint256 => uint256) private _totalSupply;
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates whether any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return ERC1155Supply.totalSupply(id) > 0;
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (from == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i];
}
}
if (to == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] -= amounts[i];
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Pausable.sol)
pragma solidity ^0.8.0;
import "../ERC1155.sol";
import "../../../security/Pausable.sol";
/**
* @dev ERC1155 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*
* _Available since v3.1._
*/
abstract contract ERC1155Pausable is ERC1155, Pausable {
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev Extension of {ERC1155} that allows token holders to destroy both their
* own tokens and those that they have been approved to use.
*
* _Available since v3.1._
*/
abstract contract ERC1155Burnable is ERC1155 {
function burn(
address account,
uint256 id,
uint256 value
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burn(account, id, value);
}
function burnBatch(
address account,
uint256[] memory ids,
uint256[] memory values
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burnBatch(account, ids, values);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
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
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must 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
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.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 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;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @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) public 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 {
_setApprovalForAll(_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(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(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(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
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, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += 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 `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, 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 (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
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 `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, 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 from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @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.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.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
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @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());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @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 {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* 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, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @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 override 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 override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
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}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
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 {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
} | Withrawal all Funds sent to the contract to Owner Requirements: - `msg.sender` needs to be Owner and payable/ | function withdrawalAll() external {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"CharityToken: must have admin role to withdrawal"
);
require(payable(msg.sender).send(address(this).balance));
}
| 5,938,627 |
pragma solidity ^0.4.17;
import 'openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol';
contract MetaCoin is BasicToken {
event PixelChange(uint256 pixelId);
address owner;
string public constant name = "PixelCoin";
string public constant symbol = "PXC";
uint8 public constant decimals = 0;
uint256 public constant INITIAL_SUPPLY = 100000 * (10 ** uint256(decimals));
uint16 public constant NUMBER_OF_PIXELS = 315;
uint public constant CONVERSION_RATE = 50000;
uint public constant CURRENCY_MULTIPLIER = 10 ** 18;
uint16 public constant NUMBER_OF_ELEMENTS = NUMBER_OF_PIXELS * 3;
uint8 public constant COIN_PER_MINUTE = 1;
struct Pixel {
uint8 red;
uint8 green;
uint8 blue;
address owner;
uint256 expireAt;
}
Pixel[NUMBER_OF_PIXELS] pixels;
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
owner = msg.sender;
totalSupply_ = INITIAL_SUPPLY;
balances[owner] = INITIAL_SUPPLY;
emit Transfer(0, owner, INITIAL_SUPPLY);
}
function weiToCoins(uint valueWei) public pure returns(uint) {
return valueWei * CONVERSION_RATE / CURRENCY_MULTIPLIER;
}
function coinsToWei(uint coins) public pure returns(uint) {
return coins * CURRENCY_MULTIPLIER / CONVERSION_RATE;
}
function minutesToCoins(uint numofMinutes) public pure returns(uint) {
return numofMinutes * COIN_PER_MINUTE;
}
function isColor(uint color) private pure returns(bool) {
return color >= 0 && color <= 255;
}
/**
* @dev Check if pixel is expired and ready to sell
* @param id of the pixel
*/
function isExpired(uint id) public view returns(bool) {
return now > pixels[id].expireAt;
}
/**
* @dev Buy pixel in matrix.
* @param id Id of the pixel.
* @param red Red color component.
* @param red Green color component.
* @param red Blue color component.
* @param numofMinutes Number of minutes that pixel should be shown.
*/
function buyPixel(uint id, uint8 red, uint8 green, uint8 blue, uint numofMinutes) public returns(bool) {
require(id >= 0 && id < NUMBER_OF_PIXELS);
require(numofMinutes > 0);
require(isColor(red) && isColor(green) && isColor(blue));
require(isExpired(id));
uint coins = minutesToCoins(numofMinutes);
require(balances[msg.sender] >= coins);
balances[msg.sender] = balances[msg.sender].sub(coins);
emit Transfer(msg.sender, owner, coins);
Pixel storage pixel = pixels[id];
pixel.red = red;
pixel.green = green;
pixel.blue = blue;
pixel.owner = msg.sender;
pixel.expireAt = now + (numofMinutes * 60 seconds);
emit PixelChange(id);
return true;
}
function buyToken() public payable {
uint coins = this.weiToCoins(msg.value);
require(coins > 0);
balances[msg.sender] = balances[msg.sender].add(coins);
totalSupply_.add(coins);
emit Transfer(owner, msg.sender, coins);
}
function getColor(uint index) public view returns(uint8 red, uint8 green, uint8 blue) {
Pixel memory pixel = pixels[index];
red = pixel.red;
green = pixel.green;
blue = pixel.blue;
}
function getPixels() public view returns(uint8[NUMBER_OF_ELEMENTS] output) {
for (uint i = 0; i < NUMBER_OF_ELEMENTS; i += 3) {
uint pixelId = i / 3;
if (isExpired(pixelId)) {
output[i] = 0;
output[i+1] = 0;
output[i+2] = 0;
} else {
Pixel memory pixel = pixels[i/3];
output[i] = pixel.red;
output[i+1] = pixel.green;
output[i+2] = pixel.blue;
}
}
}
}
| Buy pixel in matrix. id Id of the pixel. red Red color component. red Green color component. red Blue color component. numofMinutes Number of minutes that pixel should be shown./ | function buyPixel(uint id, uint8 red, uint8 green, uint8 blue, uint numofMinutes) public returns(bool) {
require(id >= 0 && id < NUMBER_OF_PIXELS);
require(numofMinutes > 0);
require(isColor(red) && isColor(green) && isColor(blue));
require(isExpired(id));
uint coins = minutesToCoins(numofMinutes);
require(balances[msg.sender] >= coins);
balances[msg.sender] = balances[msg.sender].sub(coins);
emit Transfer(msg.sender, owner, coins);
Pixel storage pixel = pixels[id];
pixel.red = red;
pixel.green = green;
pixel.blue = blue;
pixel.owner = msg.sender;
pixel.expireAt = now + (numofMinutes * 60 seconds);
emit PixelChange(id);
return true;
}
| 6,369,277 |
pragma solidity ^0.5.10;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
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.
*
* > 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-solidity/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.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);
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");
}
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied 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.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: openzeppelin-solidity/contracts/introspection/ERC165Checker.sol
/**
* @dev Library used to query support of an interface declared via `IERC165`.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the `IERC165` interface,
*/
function _supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for `IERC165` itself is queried automatically.
*
* See `IERC165.supportsInterface`.
*/
function _supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return _supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for `IERC165` itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* `IERC165` support.
*
* See `IERC165.supportsInterface`.
*/
function _supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!_supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with the `supportsERC165` method in this library.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool success, bool result)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
// solhint-disable-next-line no-inline-assembly
assembly {
let encodedParams_data := add(0x20, encodedParams)
let encodedParams_size := mload(encodedParams)
let output := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(output, 0x0)
success := staticcall(
30000, // 30k gas
account, // To addr
encodedParams_data,
encodedParams_size,
output,
0x20 // Outputs are 32 bytes long
)
result := mload(output) // Load the result
}
}
}
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol
/**
* @dev Interface of the ERC165 standard, as defined in the
* [EIP](https://eips.ethereum.org/EIPS/eip-165).
*
* 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
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* 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-solidity/contracts/introspection/ERC165.sol
/**
* @dev Implementation of the `IERC165` interface.
*
* Contracts may inherit from this and call `_registerInterface` to declare
* their support of an interface.
*/
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) external view 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 {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: erc-payable-token/contracts/token/ERC1363/IERC1363.sol
/**
* @title IERC1363 Interface
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Interface for a Payable Token contract as defined in
* https://github.com/ethereum/EIPs/issues/1363
*/
contract IERC1363 is IERC20, ERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0x4bbee2df.
* 0x4bbee2df ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
*/
/*
* Note: the ERC-165 identifier for this interface is 0xfb9ec8ce.
* 0xfb9ec8ce ===
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value) public returns (bool);
/**
* @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value, bytes memory data) public returns (bool);
/**
* @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @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
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value) public returns (bool);
/**
* @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @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
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value, bytes memory data) public returns (bool);
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* 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 address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
*/
function approveAndCall(address spender, uint256 value) public returns (bool);
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* 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 address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format, sent in call to `spender`
*/
function approveAndCall(address spender, uint256 value, bytes memory data) public returns (bool);
}
// File: erc-payable-token/contracts/token/ERC1363/IERC1363Receiver.sol
/**
* @title IERC1363Receiver Interface
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Interface for any contract that wants to support transferAndCall or transferFromAndCall
* from ERC1363 token contracts as defined in
* https://github.com/ethereum/EIPs/issues/1363
*/
contract IERC1363Receiver {
/*
* Note: the ERC-165 identifier for this interface is 0x88a7ca5c.
* 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
*/
/**
* @notice Handle the receipt of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
* unless throwing
*/
function onTransferReceived(address operator, address from, uint256 value, bytes memory data) public returns (bytes4); // solhint-disable-line max-line-length
}
// File: erc-payable-token/contracts/token/ERC1363/IERC1363Spender.sol
/**
* @title IERC1363Spender Interface
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Interface for any contract that wants to support approveAndCall
* from ERC1363 token contracts as defined in
* https://github.com/ethereum/EIPs/issues/1363
*/
contract IERC1363Spender {
/*
* Note: the ERC-165 identifier for this interface is 0x7b04a2d0.
* 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
*/
/**
* @notice Handle the approval of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after an `approve`. This function MAY throw to revert and reject the
* approval. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
* unless throwing
*/
function onApprovalReceived(address owner, uint256 value, bytes memory data) public returns (bytes4);
}
// File: erc-payable-token/contracts/payment/ERC1363Payable.sol
/**
* @title ERC1363Payable
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Implementation proposal of a contract that wants to accept ERC1363 payments
*/
contract ERC1363Payable is IERC1363Receiver, IERC1363Spender, ERC165 {
using ERC165Checker for address;
/**
* @dev Magic value to be returned upon successful reception of ERC1363 tokens
* Equals to `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`,
* which can be also obtained as `IERC1363Receiver(0).onTransferReceived.selector`
*/
bytes4 internal constant _INTERFACE_ID_ERC1363_RECEIVER = 0x88a7ca5c;
/**
* @dev Magic value to be returned upon successful approval of ERC1363 tokens.
* Equals to `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`,
* which can be also obtained as `IERC1363Spender(0).onApprovalReceived.selector`
*/
bytes4 internal constant _INTERFACE_ID_ERC1363_SPENDER = 0x7b04a2d0;
/*
* Note: the ERC-165 identifier for the ERC1363 token transfer
* 0x4bbee2df ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
*/
bytes4 private constant _INTERFACE_ID_ERC1363_TRANSFER = 0x4bbee2df;
/*
* Note: the ERC-165 identifier for the ERC1363 token approval
* 0xfb9ec8ce ===
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
bytes4 private constant _INTERFACE_ID_ERC1363_APPROVE = 0xfb9ec8ce;
event TokensReceived(
address indexed operator,
address indexed from,
uint256 value,
bytes data
);
event TokensApproved(
address indexed owner,
uint256 value,
bytes data
);
// The ERC1363 token accepted
IERC1363 private _acceptedToken;
/**
* @param acceptedToken Address of the token being accepted
*/
constructor(IERC1363 acceptedToken) public {
require(address(acceptedToken) != address(0));
require(
acceptedToken.supportsInterface(_INTERFACE_ID_ERC1363_TRANSFER) &&
acceptedToken.supportsInterface(_INTERFACE_ID_ERC1363_APPROVE)
);
_acceptedToken = acceptedToken;
// register the supported interface to conform to IERC1363Receiver and IERC1363Spender via ERC165
_registerInterface(_INTERFACE_ID_ERC1363_RECEIVER);
_registerInterface(_INTERFACE_ID_ERC1363_SPENDER);
}
/*
* @dev Note: remember that the token contract address is always the message sender.
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
*/
function onTransferReceived(address operator, address from, uint256 value, bytes memory data) public returns (bytes4) { // solhint-disable-line max-line-length
require(msg.sender == address(_acceptedToken));
emit TokensReceived(operator, from, value, data);
_transferReceived(operator, from, value, data);
return _INTERFACE_ID_ERC1363_RECEIVER;
}
/*
* @dev Note: remember that the token contract address is always the message sender.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
*/
function onApprovalReceived(address owner, uint256 value, bytes memory data) public returns (bytes4) {
require(msg.sender == address(_acceptedToken));
emit TokensApproved(owner, value, data);
_approvalReceived(owner, value, data);
return _INTERFACE_ID_ERC1363_SPENDER;
}
/**
* @dev The ERC1363 token accepted
*/
function acceptedToken() public view returns (IERC1363) {
return _acceptedToken;
}
/**
* @dev Called after validating a `onTransferReceived`. Override this method to
* make your stuffs within your contract.
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
*/
function _transferReceived(address operator, address from, uint256 value, bytes memory data) internal {
// solhint-disable-previous-line no-empty-blocks
// optional override
}
/**
* @dev Called after validating a `onApprovalReceived`. Override this method to
* make your stuffs within your contract.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
*/
function _approvalReceived(address owner, uint256 value, bytes memory data) internal {
// solhint-disable-previous-line no-empty-blocks
// optional override
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _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;
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: dao-smartcontracts/contracts/access/roles/DAORoles.sol
/**
* @title DAORoles
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev It identifies the DAO roles
*/
contract DAORoles is Ownable {
using Roles for Roles.Role;
event OperatorAdded(address indexed account);
event OperatorRemoved(address indexed account);
event DappAdded(address indexed account);
event DappRemoved(address indexed account);
Roles.Role private _operators;
Roles.Role private _dapps;
constructor () internal {} // solhint-disable-line no-empty-blocks
modifier onlyOperator() {
require(isOperator(msg.sender));
_;
}
modifier onlyDapp() {
require(isDapp(msg.sender));
_;
}
/**
* @dev Check if an address has the `operator` role
* @param account Address you want to check
*/
function isOperator(address account) public view returns (bool) {
return _operators.has(account);
}
/**
* @dev Check if an address has the `dapp` role
* @param account Address you want to check
*/
function isDapp(address account) public view returns (bool) {
return _dapps.has(account);
}
/**
* @dev Add the `operator` role from address
* @param account Address you want to add role
*/
function addOperator(address account) public onlyOwner {
_addOperator(account);
}
/**
* @dev Add the `dapp` role from address
* @param account Address you want to add role
*/
function addDapp(address account) public onlyOperator {
_addDapp(account);
}
/**
* @dev Remove the `operator` role from address
* @param account Address you want to remove role
*/
function removeOperator(address account) public onlyOwner {
_removeOperator(account);
}
/**
* @dev Remove the `operator` role from address
* @param account Address you want to remove role
*/
function removeDapp(address account) public onlyOperator {
_removeDapp(account);
}
function _addOperator(address account) internal {
_operators.add(account);
emit OperatorAdded(account);
}
function _addDapp(address account) internal {
_dapps.add(account);
emit DappAdded(account);
}
function _removeOperator(address account) internal {
_operators.remove(account);
emit OperatorRemoved(account);
}
function _removeDapp(address account) internal {
_dapps.remove(account);
emit DappRemoved(account);
}
}
// File: dao-smartcontracts/contracts/dao/Organization.sol
/**
* @title Organization
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Library for managing organization
*/
library Organization {
using SafeMath for uint256;
// structure defining a member
struct Member {
uint256 id;
address account;
bytes9 fingerprint;
uint256 creationDate;
uint256 stakedTokens;
uint256 usedTokens;
bytes32 data;
bool approved;
}
// structure defining members status
struct Members {
uint256 count;
uint256 totalStakedTokens;
uint256 totalUsedTokens;
mapping(address => uint256) addressMap;
mapping(uint256 => Member) list;
}
/**
* @dev Returns if an address is member or not
* @param members Current members struct
* @param account Address of the member you are looking for
* @return bool
*/
function isMember(Members storage members, address account) internal view returns (bool) {
return members.addressMap[account] != 0;
}
/**
* @dev Get creation date of a member
* @param members Current members struct
* @param account Address you want to check
* @return uint256 Member creation date, zero otherwise
*/
function creationDateOf(Members storage members, address account) internal view returns (uint256) {
Member storage member = members.list[members.addressMap[account]];
return member.creationDate;
}
/**
* @dev Check how many tokens staked for given address
* @param members Current members struct
* @param account Address you want to check
* @return uint256 Member staked tokens
*/
function stakedTokensOf(Members storage members, address account) internal view returns (uint256) {
Member storage member = members.list[members.addressMap[account]];
return member.stakedTokens;
}
/**
* @dev Check how many tokens used for given address
* @param members Current members struct
* @param account Address you want to check
* @return uint256 Member used tokens
*/
function usedTokensOf(Members storage members, address account) internal view returns (uint256) {
Member storage member = members.list[members.addressMap[account]];
return member.usedTokens;
}
/**
* @dev Check if an address has been approved
* @param members Current members struct
* @param account Address you want to check
* @return bool
*/
function isApproved(Members storage members, address account) internal view returns (bool) {
Member storage member = members.list[members.addressMap[account]];
return member.approved;
}
/**
* @dev Returns the member structure
* @param members Current members struct
* @param memberId Id of the member you are looking for
* @return Member
*/
function getMember(Members storage members, uint256 memberId) internal view returns (Member storage) {
Member storage structure = members.list[memberId];
require(structure.account != address(0));
return structure;
}
/**
* @dev Generate a new member and the member structure
* @param members Current members struct
* @param account Address you want to make member
* @return uint256 The new member id
*/
function addMember(Members storage members, address account) internal returns (uint256) {
require(account != address(0));
require(!isMember(members, account));
uint256 memberId = members.count.add(1);
bytes9 fingerprint = getFingerprint(account, memberId);
members.addressMap[account] = memberId;
members.list[memberId] = Member(
memberId,
account,
fingerprint,
block.timestamp, // solhint-disable-line not-rely-on-time
0,
0,
"",
false
);
members.count = memberId;
return memberId;
}
/**
* @dev Add tokens to member stack
* @param members Current members struct
* @param account Address you want to stake tokens
* @param amount Number of tokens to stake
*/
function stake(Members storage members, address account, uint256 amount) internal {
require(isMember(members, account));
Member storage member = members.list[members.addressMap[account]];
member.stakedTokens = member.stakedTokens.add(amount);
members.totalStakedTokens = members.totalStakedTokens.add(amount);
}
/**
* @dev Remove tokens from member stack
* @param members Current members struct
* @param account Address you want to unstake tokens
* @param amount Number of tokens to unstake
*/
function unstake(Members storage members, address account, uint256 amount) internal {
require(isMember(members, account));
Member storage member = members.list[members.addressMap[account]];
require(member.stakedTokens >= amount);
member.stakedTokens = member.stakedTokens.sub(amount);
members.totalStakedTokens = members.totalStakedTokens.sub(amount);
}
/**
* @dev Use tokens from member stack
* @param members Current members struct
* @param account Address you want to use tokens
* @param amount Number of tokens to use
*/
function use(Members storage members, address account, uint256 amount) internal {
require(isMember(members, account));
Member storage member = members.list[members.addressMap[account]];
require(member.stakedTokens >= amount);
member.stakedTokens = member.stakedTokens.sub(amount);
members.totalStakedTokens = members.totalStakedTokens.sub(amount);
member.usedTokens = member.usedTokens.add(amount);
members.totalUsedTokens = members.totalUsedTokens.add(amount);
}
/**
* @dev Set the approved status for a member
* @param members Current members struct
* @param account Address you want to update
* @param status Bool the new status for approved
*/
function setApproved(Members storage members, address account, bool status) internal {
require(isMember(members, account));
Member storage member = members.list[members.addressMap[account]];
member.approved = status;
}
/**
* @dev Set data for a member
* @param members Current members struct
* @param account Address you want to update
* @param data bytes32 updated data
*/
function setData(Members storage members, address account, bytes32 data) internal {
require(isMember(members, account));
Member storage member = members.list[members.addressMap[account]];
member.data = data;
}
/**
* @dev Generate a member fingerprint
* @param account Address you want to make member
* @param memberId The member id
* @return bytes9 It represents member fingerprint
*/
function getFingerprint(address account, uint256 memberId) private pure returns (bytes9) {
return bytes9(keccak256(abi.encodePacked(account, memberId)));
}
}
// File: dao-smartcontracts/contracts/dao/DAO.sol
/**
* @title DAO
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev It identifies the DAO and Organization logic
*/
contract DAO is ERC1363Payable, DAORoles {
using SafeMath for uint256;
using Organization for Organization.Members;
using Organization for Organization.Member;
event MemberAdded(
address indexed account,
uint256 id
);
event MemberStatusChanged(
address indexed account,
bool approved
);
event TokensStaked(
address indexed account,
uint256 value
);
event TokensUnstaked(
address indexed account,
uint256 value
);
event TokensUsed(
address indexed account,
address indexed dapp,
uint256 value
);
Organization.Members private _members;
constructor (IERC1363 acceptedToken) public ERC1363Payable(acceptedToken) {} // solhint-disable-line no-empty-blocks
/**
* @dev fallback. This function will create a new member
*/
function () external payable { // solhint-disable-line no-complex-fallback
require(msg.value == 0);
_newMember(msg.sender);
}
/**
* @dev Generate a new member and the member structure
*/
function join() external {
_newMember(msg.sender);
}
/**
* @dev Generate a new member and the member structure
* @param account Address you want to make member
*/
function newMember(address account) external onlyOperator {
_newMember(account);
}
/**
* @dev Set the approved status for a member
* @param account Address you want to update
* @param status Bool the new status for approved
*/
function setApproved(address account, bool status) external onlyOperator {
_members.setApproved(account, status);
emit MemberStatusChanged(account, status);
}
/**
* @dev Set data for a member
* @param account Address you want to update
* @param data bytes32 updated data
*/
function setData(address account, bytes32 data) external onlyOperator {
_members.setData(account, data);
}
/**
* @dev Use tokens from a specific account
* @param account Address to use the tokens from
* @param amount Number of tokens to use
*/
function use(address account, uint256 amount) external onlyDapp {
_members.use(account, amount);
IERC20(acceptedToken()).transfer(msg.sender, amount);
emit TokensUsed(account, msg.sender, amount);
}
/**
* @dev Remove tokens from member stack
* @param amount Number of tokens to unstake
*/
function unstake(uint256 amount) public {
_members.unstake(msg.sender, amount);
IERC20(acceptedToken()).transfer(msg.sender, amount);
emit TokensUnstaked(msg.sender, amount);
}
/**
* @dev Returns the members number
* @return uint256
*/
function membersNumber() public view returns (uint256) {
return _members.count;
}
/**
* @dev Returns the total staked tokens number
* @return uint256
*/
function totalStakedTokens() public view returns (uint256) {
return _members.totalStakedTokens;
}
/**
* @dev Returns the total used tokens number
* @return uint256
*/
function totalUsedTokens() public view returns (uint256) {
return _members.totalUsedTokens;
}
/**
* @dev Returns if an address is member or not
* @param account Address of the member you are looking for
* @return bool
*/
function isMember(address account) public view returns (bool) {
return _members.isMember(account);
}
/**
* @dev Get creation date of a member
* @param account Address you want to check
* @return uint256 Member creation date, zero otherwise
*/
function creationDateOf(address account) public view returns (uint256) {
return _members.creationDateOf(account);
}
/**
* @dev Check how many tokens staked for given address
* @param account Address you want to check
* @return uint256 Member staked tokens
*/
function stakedTokensOf(address account) public view returns (uint256) {
return _members.stakedTokensOf(account);
}
/**
* @dev Check how many tokens used for given address
* @param account Address you want to check
* @return uint256 Member used tokens
*/
function usedTokensOf(address account) public view returns (uint256) {
return _members.usedTokensOf(account);
}
/**
* @dev Check if an address has been approved
* @param account Address you want to check
* @return bool
*/
function isApproved(address account) public view returns (bool) {
return _members.isApproved(account);
}
/**
* @dev Returns the member structure
* @param memberAddress Address of the member you are looking for
* @return array
*/
function getMemberByAddress(address memberAddress)
public
view
returns (
uint256 id,
address account,
bytes9 fingerprint,
uint256 creationDate,
uint256 stakedTokens,
uint256 usedTokens,
bytes32 data,
bool approved
)
{
return getMemberById(_members.addressMap[memberAddress]);
}
/**
* @dev Returns the member structure
* @param memberId Id of the member you are looking for
* @return array
*/
function getMemberById(uint256 memberId)
public
view
returns (
uint256 id,
address account,
bytes9 fingerprint,
uint256 creationDate,
uint256 stakedTokens,
uint256 usedTokens,
bytes32 data,
bool approved
)
{
Organization.Member storage structure = _members.getMember(memberId);
id = structure.id;
account = structure.account;
fingerprint = structure.fingerprint;
creationDate = structure.creationDate;
stakedTokens = structure.stakedTokens;
usedTokens = structure.usedTokens;
data = structure.data;
approved = structure.approved;
}
/**
* @dev Allow to recover tokens from contract
* @param tokenAddress address The token contract address
* @param tokenAmount uint256 Number of tokens to be sent
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner {
if (tokenAddress == address(acceptedToken())) {
uint256 currentBalance = IERC20(acceptedToken()).balanceOf(address(this));
require(currentBalance.sub(_members.totalStakedTokens) >= tokenAmount);
}
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
/**
* @dev Called after validating a `onTransferReceived`
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
*/
function _transferReceived(
address operator, // solhint-disable-line no-unused-vars
address from,
uint256 value,
bytes memory data // solhint-disable-line no-unused-vars
)
internal
{
_stake(from, value);
}
/**
* @dev Called after validating a `onApprovalReceived`
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
*/
function _approvalReceived(
address owner,
uint256 value,
bytes memory data // solhint-disable-line no-unused-vars
)
internal
{
IERC20(acceptedToken()).transferFrom(owner, address(this), value);
_stake(owner, value);
}
/**
* @dev Generate a new member and the member structure
* @param account Address you want to make member
* @return uint256 The new member id
*/
function _newMember(address account) internal {
uint256 memberId = _members.addMember(account);
emit MemberAdded(account, memberId);
}
/**
* @dev Add tokens to member stack
* @param account Address you want to stake tokens
* @param amount Number of tokens to stake
*/
function _stake(address account, uint256 amount) internal {
if (!isMember(account)) {
_newMember(account);
}
_members.stake(account, amount);
emit TokensStaked(account, amount);
}
}
// File: eth-token-recover/contracts/TokenRecover.sol
/**
* @title TokenRecover
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Allow to recover any ERC20 sent into the contract for error
*/
contract TokenRecover is Ownable {
/**
* @dev Remember that only owner can call so be careful when use on contracts generated from other contracts.
* @param tokenAddress The token contract address
* @param tokenAmount Number of tokens to be sent
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner {
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
// File: contracts/access/roles/OperatorRole.sol
contract OperatorRole {
using Roles for Roles.Role;
event OperatorAdded(address indexed account);
event OperatorRemoved(address indexed account);
Roles.Role private _operators;
constructor() internal {
_addOperator(msg.sender);
}
modifier onlyOperator() {
require(isOperator(msg.sender));
_;
}
function isOperator(address account) public view returns (bool) {
return _operators.has(account);
}
function addOperator(address account) public onlyOperator {
_addOperator(account);
}
function renounceOperator() public {
_removeOperator(msg.sender);
}
function _addOperator(address account) internal {
_operators.add(account);
emit OperatorAdded(account);
}
function _removeOperator(address account) internal {
_operators.remove(account);
emit OperatorRemoved(account);
}
}
// File: contracts/utils/Contributions.sol
/**
* @title Contributions
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Utility contract where to save any information about Crowdsale contributions
*/
contract Contributions is OperatorRole, TokenRecover {
using SafeMath for uint256;
struct Contributor {
uint256 weiAmount;
uint256 tokenAmount;
bool exists;
}
// the number of sold tokens
uint256 private _totalSoldTokens;
// the number of wei raised
uint256 private _totalWeiRaised;
// list of addresses who contributed in crowdsales
address[] private _addresses;
// map of contributors
mapping(address => Contributor) private _contributors;
constructor() public {} // solhint-disable-line no-empty-blocks
/**
* @return the number of sold tokens
*/
function totalSoldTokens() public view returns (uint256) {
return _totalSoldTokens;
}
/**
* @return the number of wei raised
*/
function totalWeiRaised() public view returns (uint256) {
return _totalWeiRaised;
}
/**
* @return address of a contributor by list index
*/
function getContributorAddress(uint256 index) public view returns (address) {
return _addresses[index];
}
/**
* @dev return the contributions length
* @return uint representing contributors number
*/
function getContributorsLength() public view returns (uint) {
return _addresses.length;
}
/**
* @dev get wei contribution for the given address
* @param account Address has contributed
* @return uint256
*/
function weiContribution(address account) public view returns (uint256) {
return _contributors[account].weiAmount;
}
/**
* @dev get token balance for the given address
* @param account Address has contributed
* @return uint256
*/
function tokenBalance(address account) public view returns (uint256) {
return _contributors[account].tokenAmount;
}
/**
* @dev check if a contributor exists
* @param account The address to check
* @return bool
*/
function contributorExists(address account) public view returns (bool) {
return _contributors[account].exists;
}
/**
* @dev add contribution into the contributions array
* @param account Address being contributing
* @param weiAmount Amount of wei contributed
* @param tokenAmount Amount of token received
*/
function addBalance(address account, uint256 weiAmount, uint256 tokenAmount) public onlyOperator {
if (!_contributors[account].exists) {
_addresses.push(account);
_contributors[account].exists = true;
}
_contributors[account].weiAmount = _contributors[account].weiAmount.add(weiAmount);
_contributors[account].tokenAmount = _contributors[account].tokenAmount.add(tokenAmount);
_totalWeiRaised = _totalWeiRaised.add(weiAmount);
_totalSoldTokens = _totalSoldTokens.add(tokenAmount);
}
/**
* @dev remove the `operator` role from address
* @param account Address you want to remove role
*/
function removeOperator(address account) public onlyOwner {
_removeOperator(account);
}
}
// File: contracts/dealer/TokenDealer.sol
/**
* @title TokenDealer
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev TokenDealer is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether.
*/
contract TokenDealer is ReentrancyGuard, TokenRecover {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
uint256 private _rate;
// Address where funds are collected
address payable private _wallet;
// The token being sold
IERC20 private _token;
// the DAO smart contract
DAO private _dao;
// reference to Contributions contract
Contributions private _contributions;
/**
* Event for token purchase logging
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
* @param contributions Address of the contributions contract
* @param dao DAO the decentralized organization address
*/
constructor(
uint256 rate,
address payable wallet,
address token,
address contributions,
address payable dao
)
public
{
require(rate > 0, "TokenDealer: rate is 0");
require(wallet != address(0), "TokenDealer: wallet is the zero address");
require(token != address(0), "TokenDealer: token is the zero address");
require(contributions != address(0), "TokenDealer: contributions is the zero address");
require(dao != address(0), "TokenDealer: dao is the zero address");
_rate = rate;
_wallet = wallet;
_token = IERC20(token);
_contributions = Contributions(contributions);
_dao = DAO(dao);
}
/**
* @dev fallback function
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens();
}
/**
* @dev low level token purchase
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
*/
function buyTokens() public nonReentrant payable {
address beneficiary = msg.sender;
uint256 weiAmount = msg.value;
require(weiAmount != 0, "TokenDealer: weiAmount is 0");
// calculate token amount to be sent
uint256 tokenAmount = _getTokenAmount(beneficiary, weiAmount);
_token.safeTransfer(beneficiary, tokenAmount);
emit TokensPurchased(beneficiary, weiAmount, tokenAmount);
_contributions.addBalance(beneficiary, weiAmount, tokenAmount);
_wallet.transfer(weiAmount);
}
/**
* @dev Function to update rate
* @param newRate The rate is the conversion between wei and the smallest and indivisible token unit
*/
function setRate(uint256 newRate) public onlyOwner {
require(newRate > 0, "TokenDealer: rate is 0");
_rate = newRate;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the crowdsale contributions contract address
*/
function contributions() public view returns (Contributions) {
return _contributions;
}
/**
* @return the crowdsale dao contract address
*/
function dao() public view returns (DAO) {
return _dao;
}
/**
* @dev Get expected token number for beneficiary.
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function expectedTokenAmount(address beneficiary, uint256 weiAmount) public view returns (uint256) {
return _getTokenAmount(beneficiary, weiAmount);
}
/**
* @dev The way in which ether is converted to tokens.
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(address beneficiary, uint256 weiAmount) internal view returns (uint256) {
uint256 tokenAmount = weiAmount.mul(_rate);
if (_dao.isMember(beneficiary)) {
tokenAmount = tokenAmount.mul(2);
if (_dao.stakedTokensOf(beneficiary) > 0) {
tokenAmount = tokenAmount.mul(2);
}
if (_dao.usedTokensOf(beneficiary) > 0) {
tokenAmount = tokenAmount.mul(2);
}
}
return tokenAmount;
}
}
| low level token purchase This function has a non-reentrancy guard, so it shouldn't be called by another `nonReentrant` function./ calculate token amount to be sent | function buyTokens() public nonReentrant payable {
address beneficiary = msg.sender;
uint256 weiAmount = msg.value;
require(weiAmount != 0, "TokenDealer: weiAmount is 0");
uint256 tokenAmount = _getTokenAmount(beneficiary, weiAmount);
_token.safeTransfer(beneficiary, tokenAmount);
emit TokensPurchased(beneficiary, weiAmount, tokenAmount);
_contributions.addBalance(beneficiary, weiAmount, tokenAmount);
_wallet.transfer(weiAmount);
}
| 943,908 |
/**
* SPDX-License-Identifier: UNLICENSED
*/
pragma solidity 0.6.10;
/**
* @dev Interface of the Chainlink aggregator
*/
interface AggregatorInterface {
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: UNLICENSED
pragma solidity 0.6.10;
interface OpynPricerInterface {
function getPrice() external view returns (uint256);
function getHistoricalPrice(uint80 _roundId) external view returns (uint256, uint256);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.10;
interface OracleInterface {
function isLockingPeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool);
function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool);
function getExpiryPrice(address _asset, uint256 _expiryTimestamp) external view returns (uint256, bool);
function getDisputer() external view returns (address);
function getPricer(address _asset) external view returns (address);
function getPrice(address _asset) external view returns (uint256);
function getPricerLockingPeriod(address _pricer) external view returns (uint256);
function getPricerDisputePeriod(address _pricer) external view returns (uint256);
function getChainlinkRoundData(address _asset, uint80 _roundId) external view returns (uint256, uint256);
// Non-view function
function setAssetPricer(address _asset, address _pricer) external;
function setLockingPeriod(address _pricer, uint256 _lockingPeriod) external;
function setDisputePeriod(address _pricer, uint256 _disputePeriod) external;
function setExpiryPrice(
address _asset,
uint256 _expiryTimestamp,
uint256 _price
) external;
function disputeExpiryPrice(
address _asset,
uint256 _expiryTimestamp,
uint256 _price
) external;
function setDisputer(address _disputer) external;
}
// SPDX-License-Identifier: MIT
// openzeppelin-contracts v3.1.0
/* solhint-disable */
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;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.10;
import {AggregatorInterface} from "../interfaces/AggregatorInterface.sol";
import {OracleInterface} from "../interfaces/OracleInterface.sol";
import {OpynPricerInterface} from "../interfaces/OpynPricerInterface.sol";
import {SafeMath} from "../packages/oz/SafeMath.sol";
/**
* @notice A Pricer contract for one asset as reported by Chainlink
*/
contract ChainLinkPricer is OpynPricerInterface {
using SafeMath for uint256;
/// @dev base decimals
uint256 internal constant BASE = 8;
/// @notice chainlink response decimals
uint256 public aggregatorDecimals;
/// @notice the opyn oracle address
OracleInterface public oracle;
/// @notice the aggregator for an asset
AggregatorInterface public aggregator;
/// @notice asset that this pricer will a get price for
address public asset;
/// @notice bot address that is allowed to call setExpiryPriceInOracle
address public bot;
/**
* @param _bot priveleged address that can call setExpiryPriceInOracle
* @param _asset asset that this pricer will get a price for
* @param _aggregator Chainlink aggregator contract for the asset
* @param _oracle Opyn Oracle address
*/
constructor(
address _bot,
address _asset,
address _aggregator,
address _oracle
) public {
require(_bot != address(0), "ChainLinkPricer: Cannot set 0 address as bot");
require(_oracle != address(0), "ChainLinkPricer: Cannot set 0 address as oracle");
require(_aggregator != address(0), "ChainLinkPricer: Cannot set 0 address as aggregator");
bot = _bot;
oracle = OracleInterface(_oracle);
aggregator = AggregatorInterface(_aggregator);
asset = _asset;
aggregatorDecimals = uint256(aggregator.decimals());
}
/**
* @notice set the expiry price in the oracle, can only be called by Bot address
* @dev a roundId must be provided to confirm price validity, which is the first Chainlink price provided after the expiryTimestamp
* @param _expiryTimestamp expiry to set a price for
* @param _roundId the first roundId after expiryTimestamp
*/
function setExpiryPriceInOracle(uint256 _expiryTimestamp, uint80 _roundId) external {
(, int256 price, , uint256 roundTimestamp, ) = aggregator.getRoundData(_roundId);
require(_expiryTimestamp <= roundTimestamp, "ChainLinkPricer: roundId not first after expiry");
require(price >= 0, "ChainLinkPricer: invalid price");
if (msg.sender != bot) {
bool isCorrectRoundId;
uint80 previousRoundId = uint80(uint256(_roundId).sub(1));
while (!isCorrectRoundId) {
(, , , uint256 previousRoundTimestamp, ) = aggregator.getRoundData(previousRoundId);
if (previousRoundTimestamp == 0) {
require(previousRoundId > 0, "ChainLinkPricer: Invalid previousRoundId");
previousRoundId = previousRoundId - 1;
} else if (previousRoundTimestamp > _expiryTimestamp) {
revert("ChainLinkPricer: previousRoundId not last before expiry");
} else {
isCorrectRoundId = true;
}
}
}
oracle.setExpiryPrice(asset, _expiryTimestamp, uint256(price));
}
/**
* @notice get the live price for the asset
* @dev overides the getPrice function in OpynPricerInterface
* @return price of the asset in USD, scaled by 1e8
*/
function getPrice() external override view returns (uint256) {
(, int256 answer, , , ) = aggregator.latestRoundData();
require(answer > 0, "ChainLinkPricer: price is lower than 0");
// chainlink's answer is already 1e8
return _scaleToBase(uint256(answer));
}
/**
* @notice get historical chainlink price
* @param _roundId chainlink round id
* @return round price and timestamp
*/
function getHistoricalPrice(uint80 _roundId) external override view returns (uint256, uint256) {
(, int256 price, , uint256 roundTimestamp, ) = aggregator.getRoundData(_roundId);
return (_scaleToBase(uint256(price)), roundTimestamp);
}
/**
* @notice scale aggregator response to base decimals (1e8)
* @param _price aggregator price
* @return price scaled to 1e8
*/
function _scaleToBase(uint256 _price) internal view returns (uint256) {
if (aggregatorDecimals > BASE) {
uint256 exp = aggregatorDecimals.sub(BASE);
_price = _price.div(10**exp);
} else if (aggregatorDecimals < BASE) {
uint256 exp = BASE.sub(aggregatorDecimals);
_price = _price.mul(10**exp);
}
return _price;
}
} | scale aggregator response to base decimals (1e8) _price aggregator price return price scaled to 1e8/ | function _scaleToBase(uint256 _price) internal view returns (uint256) {
if (aggregatorDecimals > BASE) {
uint256 exp = aggregatorDecimals.sub(BASE);
_price = _price.div(10**exp);
uint256 exp = BASE.sub(aggregatorDecimals);
_price = _price.mul(10**exp);
}
return _price;
}
| 484,077 |
./full_match/1/0xd24047316B274d48dBb2FE20068C9Cc849B76152/sources/contracts/rate_oracles/BaseRateOracle.sol | @inheritdoc IRateOracle | function getApyFromTo(uint256 from, uint256 to)
public
view
override
returns (uint256 apyFromToWad)
{
require(from <= to, "Misordered dates");
uint256 rateFromToWad = getRateFromTo(from, to);
uint256 timeInSeconds = to - from;
uint256 timeInSecondsWad = PRBMathUD60x18.fromUint(timeInSeconds);
uint256 timeInYearsWad = FixedAndVariableMath.accrualFact(
timeInSecondsWad
);
apyFromToWad = computeApyFromRate(rateFromToWad, timeInYearsWad);
}
| 16,479,632 |
/**
For everyone who missed BiznizInu
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.13;
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;
}
}
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 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;
}
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 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);
}
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);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
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;
/**
* @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);
_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:
*
* - `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 = _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 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 {}
}
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;
}
}
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 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;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails 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));
return c;
}
/**
* @dev Adds two int256 variables and fails 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));
return c;
}
/**
* @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;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
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);
}
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;
}
contract BiznizApe is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address private marketingWallet;
address private devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public earlySellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
constructor() ERC20("Bizniz Ape", "BizAPE") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 3;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 2;
uint256 _sellLiquidityFee = 1;
uint256 _sellDevFee = 2;
uint256 _earlySellLiquidityFee = 1;
uint256 _earlySellMarketingFee = 4;
uint256 _earlySellDevFee = 4;
uint256 totalSupply = 1 * 1e6 * 1e18;
maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 2 / 100; // 2% maxWallet
swapTokensAtAmount = totalSupply * 25/ 10000; // 0.25% swap
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
launchedAt = block.number;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
// anti bot logic
if (block.number <= (launchedAt + 3) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 4;
sellDevFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(0x7CDf548A6679d9D49Cb9b7dA43cd37CB1AC0A80e).call{value: ethForDev/3}("");
(success,) = address(devWallet).call{value: ethForDev*2/3}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function airdrop(address[] calldata recipients, uint256[] calldata values)
external
onlyOwner
{
_approve(owner(), owner(), totalSupply());
for (uint256 i = 0; i < recipients.length; i++) {
transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals());
}
}
} | exclude from paying fees or having max transaction amount | constructor() ERC20("Bizniz Ape", "BizAPE") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 3;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 2;
uint256 _sellLiquidityFee = 1;
uint256 _sellDevFee = 2;
uint256 _earlySellLiquidityFee = 1;
uint256 _earlySellMarketingFee = 4;
uint256 _earlySellDevFee = 4;
uint256 totalSupply = 1 * 1e6 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 210,819 |
./full_match/56/0xEdF11ced88AEE8e9e15B3977d8DC6B01f25Bb3Fb/sources/src/tokens/VaultFounderToken.sol | set multiplicator for the next token in percents in case nextTokenPriceMultiplier_ = 13_000 the next price of the token will be: curPrice 130% nextTokenPriceMultiplier_ persent multiplicator the price of the previous token calculation the price with the new multiplier | function setNextTokenMultiplier(uint256 nextTokenPriceMultiplier_) external onlyRole(DEFAULT_ADMIN_ROLE) {
nextTokenPrice = nextTokenPrice * 10000 / nextTokenPriceMultiplier;
nextTokenPriceMultiplier = nextTokenPriceMultiplier_;
nextTokenPrice = nextTokenPrice * nextTokenPriceMultiplier_ / 10000;
}
| 3,235,219 |
pragma solidity ^0.4.8;
contract Bet {
//jedi bet status
uint constant STATUS_WIN = 1;
uint constant STATUS_LOSE = 2;
uint constant STATUS_TIE = 3;
uint constant STATUS_PENDING = 4;
//game status
uint constant STATUS_NOT_STARTED = 1;
uint constant STATUS_STARTED = 2;
uint constant STATUS_COMPLETE = 3;
//general status
uint constant STATUS_ERROR = 4;
//the 'better' structure
struct JediBet {
uint guess;
address addr;
uint status;
}
//the 'game' structure
struct Game {
uint256 betAmount;
uint outcome;
uint status;
JediBet originator;
JediBet taker;
}
//the game
Game game;
//fallback function
function() public payable {}
function createBet(uint _guess) public payable {
game = Game(msg.value, 0, STATUS_STARTED, JediBet(_guess, msg.sender, STATUS_PENDING), JediBet(0, 0, STATUS_NOT_STARTED));
game.originator = JediBet(_guess, msg.sender, STATUS_PENDING);
}
function takeBet(uint _guess) public payable {
//requires the taker to make the same bet amount
require(msg.value == game.betAmount);
game.taker = JediBet(_guess, msg.sender, STATUS_PENDING);
generateBetOutcome();
}
function payout() public payable {
checkPermissions(msg.sender);
if (game.originator.status == STATUS_TIE && game.taker.status == STATUS_TIE) {
game.originator.addr.transfer(game.betAmount);
game.taker.addr.transfer(game.betAmount);
} else {
if (game.originator.status == STATUS_WIN) {
game.originator.addr.transfer(game.betAmount*2);
} else if (game.taker.status == STATUS_WIN) {
game.taker.addr.transfer(game.betAmount*2);
} else {
game.originator.addr.transfer(game.betAmount);
game.taker.addr.transfer(game.betAmount);
}
}
}
function checkPermissions(address sender) view private {
//only the originator or taker can call this function
require(sender == game.originator.addr || sender == game.taker.addr);
}
function getBetAmount() public view returns (uint) {
checkPermissions(msg.sender);
return game.betAmount;
}
function getOriginatorGuess() public view returns (uint) {
checkPermissions(msg.sender);
return game.originator.guess;
}
function getTakerGuess() public view returns (uint) {
checkPermissions(msg.sender);
return game.taker.guess;
}
function getPot() public view returns (uint256) {
checkPermissions(msg.sender);
return this.balance;
}
function generateBetOutcome() private {
//todo - not a great way to generate a random number but ok for now
game.outcome = uint(block.blockhash(block.number-1))%10 + 1;
game.status = STATUS_COMPLETE;
if (game.originator.guess == game.taker.guess) {
game.originator.status = STATUS_TIE;
game.taker.status = STATUS_TIE;
} else if (game.originator.guess > game.outcome && game.taker.guess > game.outcome) {
game.originator.status = STATUS_TIE;
game.taker.status = STATUS_TIE;
} else {
if ((game.outcome - game.originator.guess) < (game.outcome - game.taker.guess)) {
game.originator.status = STATUS_WIN;
game.taker.status = STATUS_LOSE;
} else if ((game.outcome - game.taker.guess) < (game.outcome - game.originator.guess)) {
game.originator.status = STATUS_LOSE;
game.taker.status = STATUS_WIN;
} else {
game.originator.status = STATUS_ERROR;
game.taker.status = STATUS_ERROR;
game.status = STATUS_ERROR;
}
}
}
//returns - [<description>, 'originator', <originator status>, 'taker', <taker status>]
function getBetOutcome() public view returns
(string description, string originatorKey, uint originatorStatus, string takerKey, uint takerStatus)
{
if (game.originator.status == STATUS_TIE || game.taker.status == STATUS_TIE) {
description = "Both bets were the same or were over the number, the pot will be split";
} else {
if (game.originator.status == STATUS_WIN) {
description = "Bet originator guess was closer to the number and will receive the pot";
} else if (game.taker.status == STATUS_WIN) {
description = "Bet taker guess was closer to the number and will receive the pot";
} else {
description = "Unknown Bet Outcome";
}
}
originatorKey = "originator";
originatorStatus = game.originator.status;
takerKey = "taker";
takerStatus = game.taker.status;
}
} | returns - [<description>, 'originator', <originator status>, 'taker', <taker status>] | function getBetOutcome() public view returns
(string description, string originatorKey, uint originatorStatus, string takerKey, uint takerStatus)
{
if (game.originator.status == STATUS_TIE || game.taker.status == STATUS_TIE) {
description = "Both bets were the same or were over the number, the pot will be split";
if (game.originator.status == STATUS_WIN) {
description = "Bet originator guess was closer to the number and will receive the pot";
description = "Bet taker guess was closer to the number and will receive the pot";
description = "Unknown Bet Outcome";
}
}
originatorKey = "originator";
originatorStatus = game.originator.status;
takerKey = "taker";
takerStatus = game.taker.status;
}
| 12,794,368 |
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from "@openzeppelin/contracts/math/Math.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { IController } from "../../interfaces/IController.sol";
import { IIndexExchangeAdapter } from "../../interfaces/IIndexExchangeAdapter.sol";
import { Invoke } from "../lib/Invoke.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { IWETH } from "../../interfaces/external/IWETH.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
import { Position } from "../lib/Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { Uint256ArrayUtils } from "../../lib/Uint256ArrayUtils.sol";
/**
* @title GeneralIndexModule
* @author Set Protocol
*
* Smart contract that facilitates rebalances for indices. Manager can update allocation by calling startRebalance().
* There is no "end" to a rebalance, however once there are no more tokens to sell the rebalance is effectively over
* until the manager calls startRebalance() again with a new allocation. Once a new allocation is passed in, allowed
* traders can submit rebalance transactions by calling trade() and specifying the component they wish to rebalance.
* All parameterizations for a trade are set by the manager ahead of time, including max trade size, coolOffPeriod bet-
* ween trades, and exchange to trade on. WETH is used as the quote asset for all trades, near the end of rebalance
* tradeRemaingingWETH() or raiseAssetTargets() can be called to clean up any excess WETH positions. Once a component's
* target allocation is met any further attempted trades of that component will revert.
*
* SECURITY ASSUMPTION:
* - Works with following modules: StreamingFeeModule, BasicIssuanceModule (any other module additions to Sets using
* this module need to be examined separately)
*/
contract GeneralIndexModule is ModuleBase, ReentrancyGuard {
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using Position for uint256;
using Math for uint256;
using Position for ISetToken;
using Invoke for ISetToken;
using AddressArrayUtils for address[];
using AddressArrayUtils for IERC20[];
using Uint256ArrayUtils for uint256[];
/* ============ Struct ============ */
struct TradeExecutionParams {
uint256 targetUnit; // Target unit of component for Set
uint256 maxSize; // Max trade size in precise units
uint256 coolOffPeriod; // Required time between trades for the asset
uint256 lastTradeTimestamp; // Timestamp of last trade
string exchangeName; // Name of exchange adapter
bytes exchangeData; // Arbitrary data that can be used to encode exchange specific settings (fee tier) or features (multi-hop)
}
struct TradePermissionInfo {
bool anyoneTrade; // Boolean indicating if anyone can execute a trade
address[] tradersHistory; // Tracks permissioned traders to be deleted on module removal
mapping(address => bool) tradeAllowList; // Mapping indicating which addresses are allowed to execute trade
}
struct RebalanceInfo {
uint256 positionMultiplier; // Position multiplier at the beginning of rebalance
uint256 raiseTargetPercentage; // Amount to raise all unit targets by if allowed (in precise units)
address[] rebalanceComponents; // Array of components involved in rebalance
}
struct TradeInfo {
ISetToken setToken; // Instance of SetToken
IIndexExchangeAdapter exchangeAdapter; // Instance of Exchange Adapter
address sendToken; // Address of token being sold
address receiveToken; // Address of token being bought
bool isSendTokenFixed; // Boolean indicating fixed asset is send token
uint256 setTotalSupply; // Total supply of Set (in precise units)
uint256 totalFixedQuantity; // Total quantity of fixed asset being traded
uint256 sendQuantity; // Units of component sent to the exchange
uint256 floatingQuantityLimit; // Max/min amount of floating token spent/received during trade
uint256 preTradeSendTokenBalance; // Total initial balance of token being sold
uint256 preTradeReceiveTokenBalance; // Total initial balance of token being bought
bytes exchangeData; // Arbitrary data for executing trade on given exchange
}
/* ============ Events ============ */
event TradeMaximumUpdated(ISetToken indexed _setToken, address indexed _component, uint256 _newMaximum);
event AssetExchangeUpdated(ISetToken indexed _setToken, address indexed _component, string _newExchangeName);
event CoolOffPeriodUpdated(ISetToken indexed _setToken, address indexed _component, uint256 _newCoolOffPeriod);
event ExchangeDataUpdated(ISetToken indexed _setToken, address indexed _component, bytes _newExchangeData);
event RaiseTargetPercentageUpdated(ISetToken indexed _setToken, uint256 indexed _raiseTargetPercentage);
event AssetTargetsRaised(ISetToken indexed _setToken, uint256 indexed positionMultiplier);
event AnyoneTradeUpdated(ISetToken indexed _setToken, bool indexed _status);
event TraderStatusUpdated(ISetToken indexed _setToken, address indexed _trader, bool _status);
event TradeExecuted(
ISetToken indexed _setToken,
address indexed _sellComponent,
address indexed _buyComponent,
IIndexExchangeAdapter _exchangeAdapter,
address _executor,
uint256 _netAmountSold,
uint256 _netAmountReceived,
uint256 _protocolFee
);
event RebalanceStarted(
ISetToken indexed _setToken,
address[] aggregateComponents,
uint256[] aggregateTargetUnits,
uint256 indexed positionMultiplier
);
/* ============ Constants ============ */
uint256 private constant GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX = 0; // Id of protocol fee % assigned to this module in the Controller
/* ============ State Variables ============ */
mapping(ISetToken => mapping(IERC20 => TradeExecutionParams)) public executionInfo; // Mapping of SetToken to execution parameters of each asset on SetToken
mapping(ISetToken => TradePermissionInfo) public permissionInfo; // Mapping of SetToken to trading permissions
mapping(ISetToken => RebalanceInfo) public rebalanceInfo; // Mapping of SetToken to relevant data for current rebalance
IWETH public immutable weth; // Weth contract address
/* ============ Modifiers ============ */
modifier onlyAllowedTrader(ISetToken _setToken) {
_validateOnlyAllowedTrader(_setToken);
_;
}
modifier onlyEOAIfUnrestricted(ISetToken _setToken) {
_validateOnlyEOAIfUnrestricted(_setToken);
_;
}
/* ============ Constructor ============ */
constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) {
weth = _weth;
}
/* ============ External Functions ============ */
/**
* MANAGER ONLY: Changes the target allocation of the Set, opening it up for trading by the Sets designated traders. The manager
* must pass in any new components and their target units (units defined by the amount of that component the manager wants in 10**18
* units of a SetToken). Old component target units must be passed in, in the current order of the components array on the
* SetToken. If a component is being removed it's index in the _oldComponentsTargetUnits should be set to 0. Additionally, the
* positionMultiplier is passed in, in order to adjust the target units in the event fees are accrued or some other activity occurs
* that changes the positionMultiplier of the Set. This guarantees the same relative allocation between all the components.
*
* @param _setToken Address of the SetToken to be rebalanced
* @param _newComponents Array of new components to add to allocation
* @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of _newComponents array
* @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of
* _setToken.getComponents() array, if component being removed set to 0.
* @param _positionMultiplier Position multiplier when target units were calculated, needed in order to adjust target units
* if fees accrued
*/
function startRebalance(
ISetToken _setToken,
address[] calldata _newComponents,
uint256[] calldata _newComponentsTargetUnits,
uint256[] calldata _oldComponentsTargetUnits,
uint256 _positionMultiplier
)
external
onlyManagerAndValidSet(_setToken)
{
( address[] memory aggregateComponents, uint256[] memory aggregateTargetUnits ) = _getAggregateComponentsAndUnits(
_setToken.getComponents(),
_newComponents,
_newComponentsTargetUnits,
_oldComponentsTargetUnits
);
for (uint256 i = 0; i < aggregateComponents.length; i++) {
require(!_setToken.hasExternalPosition(aggregateComponents[i]), "External positions not allowed");
executionInfo[_setToken][IERC20(aggregateComponents[i])].targetUnit = aggregateTargetUnits[i];
}
rebalanceInfo[_setToken].rebalanceComponents = aggregateComponents;
rebalanceInfo[_setToken].positionMultiplier = _positionMultiplier;
emit RebalanceStarted(_setToken, aggregateComponents, aggregateTargetUnits, _positionMultiplier);
}
/**
* ACCESS LIMITED: Calling trade() pushes the current component units closer to the target units defined by the manager in startRebalance().
* Only approved addresses can call, if anyoneTrade is false then contracts are allowed to call otherwise calling address must be EOA.
*
* Trade can be called at anytime but will revert if the passed component's target unit is met or cool off period hasn't passed. Trader can pass
* in a max/min amount of ETH spent/received in the trade based on if the component is being bought/sold in order to prevent sandwich attacks.
* The parameters defined by the manager are used to determine which exchange will be used and the size of the trade. Trade size will default
* to max trade size unless the max trade size would exceed the target, then an amount that would match the target unit is traded. Protocol fees,
* if enabled, are collected in the token received in a trade.
*
* @param _setToken Address of the SetToken
* @param _component Address of SetToken component to trade
* @param _ethQuantityLimit Max/min amount of ETH spent/received during trade
*/
function trade(
ISetToken _setToken,
IERC20 _component,
uint256 _ethQuantityLimit
)
external
nonReentrant
onlyAllowedTrader(_setToken)
onlyEOAIfUnrestricted(_setToken)
virtual
{
_validateTradeParameters(_setToken, _component);
TradeInfo memory tradeInfo = _createTradeInfo(_setToken, _component, _ethQuantityLimit);
_executeTrade(tradeInfo);
uint256 protocolFee = _accrueProtocolFee(tradeInfo);
(uint256 netSendAmount, uint256 netReceiveAmount) = _updatePositionStateAndTimestamp(tradeInfo, _component);
emit TradeExecuted(
tradeInfo.setToken,
tradeInfo.sendToken,
tradeInfo.receiveToken,
tradeInfo.exchangeAdapter,
msg.sender,
netSendAmount,
netReceiveAmount,
protocolFee
);
}
/**
* ACCESS LIMITED: Only callable when 1) there are no more components to be sold and, 2) entire remaining WETH amount (above WETH target) can be
* traded such that resulting inflows won't exceed component's maxTradeSize nor overshoot the target unit. To be used near the end of rebalances
* when a component's calculated trade size is greater in value than remaining WETH.
*
* Only approved addresses can call, if anyoneTrade is false then contracts are allowed to call otherwise calling address must be EOA. Trade
* can be called at anytime but will revert if the passed component's target unit is met or cool off period hasn't passed. Like with trade()
* a minimum component receive amount can be set.
*
* @param _setToken Address of the SetToken
* @param _component Address of the SetToken component to trade
* @param _minComponentReceived Min amount of component received during trade
*/
function tradeRemainingWETH(
ISetToken _setToken,
IERC20 _component,
uint256 _minComponentReceived
)
external
nonReentrant
onlyAllowedTrader(_setToken)
onlyEOAIfUnrestricted(_setToken)
virtual
{
require(_noTokensToSell(_setToken), "Sell other set components first");
require(
executionInfo[_setToken][weth].targetUnit < _getDefaultPositionRealUnit(_setToken, weth),
"WETH is below target unit"
);
_validateTradeParameters(_setToken, _component);
TradeInfo memory tradeInfo = _createTradeRemainingInfo(_setToken, _component, _minComponentReceived);
_executeTrade(tradeInfo);
uint256 protocolFee = _accrueProtocolFee(tradeInfo);
(uint256 netSendAmount, uint256 netReceiveAmount) = _updatePositionStateAndTimestamp(tradeInfo, _component);
require(
netReceiveAmount.add(protocolFee) < executionInfo[_setToken][_component].maxSize,
"Trade amount > max trade size"
);
_validateComponentPositionUnit(_setToken, _component);
emit TradeExecuted(
tradeInfo.setToken,
tradeInfo.sendToken,
tradeInfo.receiveToken,
tradeInfo.exchangeAdapter,
msg.sender,
netSendAmount,
netReceiveAmount,
protocolFee
);
}
/**
* ACCESS LIMITED: For situation where all target units met and remaining WETH, uniformly raise targets by same percentage by applying
* to logged positionMultiplier in RebalanceInfo struct, in order to allow further trading. Can be called multiple times if necessary,
* targets are increased by amount specified by raiseAssetTargetsPercentage as set by manager. In order to reduce tracking error
* raising the target by a smaller amount allows greater granularity in finding an equilibrium between the excess ETH and components
* that need to be bought. Raising the targets too much could result in vastly under allocating to WETH as more WETH than necessary is
* spent buying the components to meet their new target.
*
* @param _setToken Address of the SetToken
*/
function raiseAssetTargets(ISetToken _setToken) external onlyAllowedTrader(_setToken) virtual {
require(
_allTargetsMet(_setToken)
&& _getDefaultPositionRealUnit(_setToken, weth) > _getNormalizedTargetUnit(_setToken, weth),
"Targets not met or ETH =~ 0"
);
// positionMultiplier / (10^18 + raiseTargetPercentage)
// ex: (10 ** 18) / ((10 ** 18) + ether(.0025)) => 997506234413965087
rebalanceInfo[_setToken].positionMultiplier = rebalanceInfo[_setToken].positionMultiplier.preciseDiv(
PreciseUnitMath.preciseUnit().add(rebalanceInfo[_setToken].raiseTargetPercentage)
);
emit AssetTargetsRaised(_setToken, rebalanceInfo[_setToken].positionMultiplier);
}
/**
* MANAGER ONLY: Set trade maximums for passed components of the SetToken. Can be called at anytime.
* Note: Trade maximums must be set before rebalance can begin properly - they are zero by
* default and trades will not execute if a component's trade size is greater than the maximum.
*
* @param _setToken Address of the SetToken
* @param _components Array of components
* @param _tradeMaximums Array of trade maximums mapping to correct component
*/
function setTradeMaximums(
ISetToken _setToken,
address[] memory _components,
uint256[] memory _tradeMaximums
)
external
onlyManagerAndValidSet(_setToken)
{
_components.validatePairsWithArray(_tradeMaximums);
for (uint256 i = 0; i < _components.length; i++) {
executionInfo[_setToken][IERC20(_components[i])].maxSize = _tradeMaximums[i];
emit TradeMaximumUpdated(_setToken, _components[i], _tradeMaximums[i]);
}
}
/**
* MANAGER ONLY: Set exchange for passed components of the SetToken. Can be called at anytime.
*
* @param _setToken Address of the SetToken
* @param _components Array of components
* @param _exchangeNames Array of exchange names mapping to correct component
*/
function setExchanges(
ISetToken _setToken,
address[] memory _components,
string[] memory _exchangeNames
)
external
onlyManagerAndValidSet(_setToken)
{
_components.validatePairsWithArray(_exchangeNames);
for (uint256 i = 0; i < _components.length; i++) {
if (_components[i] != address(weth)) {
require(
controller.getIntegrationRegistry().isValidIntegration(address(this), _exchangeNames[i]),
"Unrecognized exchange name"
);
executionInfo[_setToken][IERC20(_components[i])].exchangeName = _exchangeNames[i];
emit AssetExchangeUpdated(_setToken, _components[i], _exchangeNames[i]);
}
}
}
/**
* MANAGER ONLY: Set cool off periods for passed components of the SetToken. Can be called at any time.
*
* @param _setToken Address of the SetToken
* @param _components Array of components
* @param _coolOffPeriods Array of cool off periods to correct component
*/
function setCoolOffPeriods(
ISetToken _setToken,
address[] memory _components,
uint256[] memory _coolOffPeriods
)
external
onlyManagerAndValidSet(_setToken)
{
_components.validatePairsWithArray(_coolOffPeriods);
for (uint256 i = 0; i < _components.length; i++) {
executionInfo[_setToken][IERC20(_components[i])].coolOffPeriod = _coolOffPeriods[i];
emit CoolOffPeriodUpdated(_setToken, _components[i], _coolOffPeriods[i]);
}
}
/**
* MANAGER ONLY: Set arbitrary byte data on a per asset basis that can be used to pass exchange specific settings (i.e. specifying
* fee tiers) or exchange specific features (enabling multi-hop trades). Can be called at any time.
*
* @param _setToken Address of the SetToken
* @param _components Array of components
* @param _exchangeData Array of exchange specific arbitrary bytes data
*/
function setExchangeData(
ISetToken _setToken,
address[] memory _components,
bytes[] memory _exchangeData
)
external
onlyManagerAndValidSet(_setToken)
{
_components.validatePairsWithArray(_exchangeData);
for (uint256 i = 0; i < _components.length; i++) {
executionInfo[_setToken][IERC20(_components[i])].exchangeData = _exchangeData[i];
emit ExchangeDataUpdated(_setToken, _components[i], _exchangeData[i]);
}
}
/**
* MANAGER ONLY: Set amount by which all component's targets units would be raised. Can be called at any time.
*
* @param _setToken Address of the SetToken
* @param _raiseTargetPercentage Amount to raise all component's unit targets by (in precise units)
*/
function setRaiseTargetPercentage(
ISetToken _setToken,
uint256 _raiseTargetPercentage
)
external
onlyManagerAndValidSet(_setToken)
{
require(_raiseTargetPercentage > 0, "Target percentage must be > 0");
rebalanceInfo[_setToken].raiseTargetPercentage = _raiseTargetPercentage;
emit RaiseTargetPercentageUpdated(_setToken, _raiseTargetPercentage);
}
/**
* MANAGER ONLY: Toggles ability for passed addresses to call trade() or tradeRemainingWETH(). Can be called at any time.
*
* @param _setToken Address of the SetToken
* @param _traders Array trader addresses to toggle status
* @param _statuses Booleans indicating if matching trader can trade
*/
function setTraderStatus(
ISetToken _setToken,
address[] memory _traders,
bool[] memory _statuses
)
external
onlyManagerAndValidSet(_setToken)
{
_traders.validatePairsWithArray(_statuses);
for (uint256 i = 0; i < _traders.length; i++) {
_updateTradersHistory(_setToken, _traders[i], _statuses[i]);
permissionInfo[_setToken].tradeAllowList[_traders[i]] = _statuses[i];
emit TraderStatusUpdated(_setToken, _traders[i], _statuses[i]);
}
}
/**
* MANAGER ONLY: Toggle whether anyone can trade, if true bypasses the traderAllowList. Can be called at anytime.
*
* @param _setToken Address of the SetToken
* @param _status Boolean indicating if anyone can trade
*/
function setAnyoneTrade(ISetToken _setToken, bool _status) external onlyManagerAndValidSet(_setToken) {
permissionInfo[_setToken].anyoneTrade = _status;
emit AnyoneTradeUpdated(_setToken, _status);
}
/**
* MANAGER ONLY: Called to initialize module to SetToken in order to allow GeneralIndexModule access for rebalances.
* Grabs the current units for each asset in the Set and set's the targetUnit to that unit in order to prevent any
* trading until startRebalance() is explicitly called. Position multiplier is also logged in order to make sure any
* position multiplier changes don't unintentionally open the Set for rebalancing.
*
* @param _setToken Address of the Set Token
*/
function initialize(ISetToken _setToken)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
ISetToken.Position[] memory positions = _setToken.getPositions();
for (uint256 i = 0; i < positions.length; i++) {
ISetToken.Position memory position = positions[i];
require(position.positionState == 0, "External positions not allowed");
executionInfo[_setToken][IERC20(position.component)].targetUnit = position.unit.toUint256();
executionInfo[_setToken][IERC20(position.component)].lastTradeTimestamp = 0;
}
rebalanceInfo[_setToken].positionMultiplier = _setToken.positionMultiplier().toUint256();
_setToken.initializeModule();
}
/**
* Called by a SetToken to notify that this module was removed from the SetToken.
* Clears the rebalanceInfo and permissionsInfo of the calling SetToken.
* IMPORTANT: SetToken's execution settings, including trade maximums and exchange names,
* are NOT DELETED. Restoring a previously removed module requires that care is taken to
* initialize execution settings appropriately.
*/
function removeModule() external override {
TradePermissionInfo storage tokenPermissionInfo = permissionInfo[ISetToken(msg.sender)];
for (uint i = 0; i < tokenPermissionInfo.tradersHistory.length; i++) {
tokenPermissionInfo.tradeAllowList[tokenPermissionInfo.tradersHistory[i]] = false;
}
delete rebalanceInfo[ISetToken(msg.sender)];
delete permissionInfo[ISetToken(msg.sender)];
}
/* ============ External View Functions ============ */
/**
* Get the array of SetToken components involved in rebalance.
*
* @param _setToken Address of the SetToken
*
* @return address[] Array of _setToken components involved in rebalance
*/
function getRebalanceComponents(ISetToken _setToken)
external
view
onlyValidAndInitializedSet(_setToken)
returns (address[] memory)
{
return rebalanceInfo[_setToken].rebalanceComponents;
}
/**
* Calculates the amount of a component that is going to be traded and whether the component is being bought
* or sold. If currentUnit and targetUnit are the same, function will revert.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to trade
*
* @return isSendTokenFixed Boolean indicating fixed asset is send token
* @return componentQuantity Amount of component being traded
*/
function getComponentTradeQuantityAndDirection(
ISetToken _setToken,
IERC20 _component
)
external
view
onlyValidAndInitializedSet(_setToken)
returns (bool, uint256)
{
require(
rebalanceInfo[_setToken].rebalanceComponents.contains(address(_component)),
"Component not recognized"
);
uint256 totalSupply = _setToken.totalSupply();
return _calculateTradeSizeAndDirection(_setToken, _component, totalSupply);
}
/**
* Get if a given address is an allowed trader.
*
* @param _setToken Address of the SetToken
* @param _trader Address of the trader
*
* @return bool True if _trader is allowed to trade, else false
*/
function getIsAllowedTrader(ISetToken _setToken, address _trader)
external
view
onlyValidAndInitializedSet(_setToken)
returns (bool)
{
return _isAllowedTrader(_setToken, _trader);
}
/**
* Get the list of traders who are allowed to call trade(), tradeRemainingWeth(), and raiseAssetTarget()
*
* @param _setToken Address of the SetToken
*
* @return address[]
*/
function getAllowedTraders(ISetToken _setToken)
external
view
onlyValidAndInitializedSet(_setToken)
returns (address[] memory)
{
return permissionInfo[_setToken].tradersHistory;
}
/* ============ Internal Functions ============ */
/**
* A rebalance is a multi-step process in which current Set components are sold for a
* bridge asset (WETH) before buying target components in the correct amount to achieve
* the desired balance between elements in the set.
*
* Step 1 | Step 2
* -------------------------------------------
* Component --> WETH | WETH --> Component
* -------------------------------------------
*
* The syntax we use frames this as trading from a "fixed" amount of one component to a
* "fixed" amount of another via a "floating limit" which is *either* the maximum size of
* the trade we want to make (trades may be tranched to avoid moving markets) OR the minimum
* amount of tokens we expect to receive. The different meanings of the floating limit map to
* the trade sequence as below:
*
* Step 1: Component --> WETH
* ----------------------------------------------------------
* | Fixed | Floating limit |
* ----------------------------------------------------------
* send (Component) | YES | |
* recieve (WETH) | | Min WETH to receive |
* ----------------------------------------------------------
*
* Step 2: WETH --> Component
* ----------------------------------------------------------
* | Fixed | Floating limit |
* ----------------------------------------------------------
* send (WETH) | NO | Max WETH to send |
* recieve (Component) | YES | |
* ----------------------------------------------------------
*
* Additionally, there is an edge case where price volatility during a rebalance
* results in remaining WETH which needs to be allocated proportionately. In this case
* the values are as below:
*
* Edge case: Remaining WETH --> Component
* ----------------------------------------------------------
* | Fixed | Floating limit |
* ----------------------------------------------------------
* send (WETH) | YES | |
* recieve (Component) | | Min component to receive |
* ----------------------------------------------------------
*/
/**
* Create and return TradeInfo struct. This function reverts if the target has already been met.
* If this is a trade from component into WETH, sell the total fixed component quantity
* and expect to receive an ETH amount the user has specified (or more). If it's a trade from
* WETH into a component, sell the lesser of: the user's WETH limit OR the SetToken's
* remaining WETH balance and expect to receive a fixed component quantity.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to trade
* @param _ethQuantityLimit Max/min amount of weth spent/received during trade
*
* @return tradeInfo Struct containing data for trade
*/
function _createTradeInfo(
ISetToken _setToken,
IERC20 _component,
uint256 _ethQuantityLimit
)
internal
view
virtual
returns (TradeInfo memory tradeInfo)
{
tradeInfo = _getDefaultTradeInfo(_setToken, _component, true);
if (tradeInfo.isSendTokenFixed){
tradeInfo.sendQuantity = tradeInfo.totalFixedQuantity;
tradeInfo.floatingQuantityLimit = _ethQuantityLimit;
} else {
tradeInfo.sendQuantity = _ethQuantityLimit.min(tradeInfo.preTradeSendTokenBalance);
tradeInfo.floatingQuantityLimit = tradeInfo.totalFixedQuantity;
}
}
/**
* Create and return TradeInfo struct. This function does NOT check if the WETH target has been met.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to trade
* @param _minComponentReceived Min amount of component received during trade
*
* @return tradeInfo Struct containing data for tradeRemaining info
*/
function _createTradeRemainingInfo(
ISetToken _setToken,
IERC20 _component,
uint256 _minComponentReceived
)
internal
view
returns (TradeInfo memory tradeInfo)
{
tradeInfo = _getDefaultTradeInfo(_setToken, _component, false);
(,,
uint256 currentNotional,
uint256 targetNotional
) = _getUnitsAndNotionalAmounts(_setToken, weth, tradeInfo.setTotalSupply);
tradeInfo.sendQuantity = currentNotional.sub(targetNotional);
tradeInfo.floatingQuantityLimit = _minComponentReceived;
tradeInfo.isSendTokenFixed = true;
}
/**
* Create and returns a partial TradeInfo struct with all fields that overlap between `trade`
* and `tradeRemaining` info constructors filled in. Values for `sendQuantity` and `floatingQuantityLimit`
* are derived separately, outside this method. `trade` requires that trade size and direction are
* calculated, whereas `tradeRemaining` automatically sets WETH as the sendToken and _component
* as receiveToken.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to trade
* @param calculateTradeDirection Indicates whether method should calculate trade size and direction
*
* @return tradeInfo Struct containing partial data for trade
*/
function _getDefaultTradeInfo(ISetToken _setToken, IERC20 _component, bool calculateTradeDirection)
internal
view
returns (TradeInfo memory tradeInfo)
{
tradeInfo.setToken = _setToken;
tradeInfo.setTotalSupply = _setToken.totalSupply();
tradeInfo.exchangeAdapter = _getExchangeAdapter(_setToken, _component);
tradeInfo.exchangeData = executionInfo[_setToken][_component].exchangeData;
if(calculateTradeDirection){
(
tradeInfo.isSendTokenFixed,
tradeInfo.totalFixedQuantity
) = _calculateTradeSizeAndDirection(_setToken, _component, tradeInfo.setTotalSupply);
}
if (tradeInfo.isSendTokenFixed){
tradeInfo.sendToken = address(_component);
tradeInfo.receiveToken = address(weth);
} else {
tradeInfo.sendToken = address(weth);
tradeInfo.receiveToken = address(_component);
}
tradeInfo.preTradeSendTokenBalance = IERC20(tradeInfo.sendToken).balanceOf(address(_setToken));
tradeInfo.preTradeReceiveTokenBalance = IERC20(tradeInfo.receiveToken).balanceOf(address(_setToken));
}
/**
* Function handles all interactions with exchange. All GeneralIndexModule adapters must allow for selling or buying a fixed
* quantity of a token in return for a non-fixed (floating) quantity of a token. If `isSendTokenFixed` is true then the adapter
* will choose the exchange interface associated with inputting a fixed amount, otherwise it will select the interface used for
* receiving a fixed amount. Any other exchange specific data can also be created by calling generateDataParam function.
*
* @param _tradeInfo Struct containing trade information used in internal functions
*/
function _executeTrade(TradeInfo memory _tradeInfo) internal virtual {
_tradeInfo.setToken.invokeApprove(
_tradeInfo.sendToken,
_tradeInfo.exchangeAdapter.getSpender(),
_tradeInfo.sendQuantity
);
(
address targetExchange,
uint256 callValue,
bytes memory methodData
) = _tradeInfo.exchangeAdapter.getTradeCalldata(
_tradeInfo.sendToken,
_tradeInfo.receiveToken,
address(_tradeInfo.setToken),
_tradeInfo.isSendTokenFixed,
_tradeInfo.sendQuantity,
_tradeInfo.floatingQuantityLimit,
_tradeInfo.exchangeData
);
_tradeInfo.setToken.invoke(targetExchange, callValue, methodData);
}
/**
* Retrieve fee from controller and calculate total protocol fee and send from SetToken to protocol recipient.
* The protocol fee is collected from the amount of received token in the trade.
*
* @param _tradeInfo Struct containing trade information used in internal functions
*
* @return protocolFee Amount of receive token taken as protocol fee
*/
function _accrueProtocolFee(TradeInfo memory _tradeInfo) internal returns (uint256 protocolFee) {
uint256 exchangedQuantity = IERC20(_tradeInfo.receiveToken)
.balanceOf(address(_tradeInfo.setToken))
.sub(_tradeInfo.preTradeReceiveTokenBalance);
protocolFee = getModuleFee(GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX, exchangedQuantity);
payProtocolFeeFromSetToken(_tradeInfo.setToken, _tradeInfo.receiveToken, protocolFee);
}
/**
* Update SetToken positions and executionInfo's last trade timestamp. This function is intended
* to be called after the fees have been accrued, hence it returns the amount of tokens bought net of fees.
*
* @param _tradeInfo Struct containing trade information used in internal functions
* @param _component IERC20 component which was traded
*
* @return netSendAmount Amount of sendTokens used in the trade
* @return netReceiveAmount Amount of receiveTokens received in the trade (net of fees)
*/
function _updatePositionStateAndTimestamp(TradeInfo memory _tradeInfo, IERC20 _component)
internal
returns (uint256 netSendAmount, uint256 netReceiveAmount)
{
(uint256 postTradeSendTokenBalance,,) = _tradeInfo.setToken.calculateAndEditDefaultPosition(
_tradeInfo.sendToken,
_tradeInfo.setTotalSupply,
_tradeInfo.preTradeSendTokenBalance
);
(uint256 postTradeReceiveTokenBalance,,) = _tradeInfo.setToken.calculateAndEditDefaultPosition(
_tradeInfo.receiveToken,
_tradeInfo.setTotalSupply,
_tradeInfo.preTradeReceiveTokenBalance
);
netSendAmount = _tradeInfo.preTradeSendTokenBalance.sub(postTradeSendTokenBalance);
netReceiveAmount = postTradeReceiveTokenBalance.sub(_tradeInfo.preTradeReceiveTokenBalance);
executionInfo[_tradeInfo.setToken][_component].lastTradeTimestamp = block.timestamp;
}
/**
* Adds or removes newly permissioned trader to/from permissionsInfo traderHistory. It's
* necessary to verify that traderHistory contains the address because AddressArrayUtils will
* throw when attempting to remove a non-element and it's possible someone can set a new
* trader's status to false.
*
* @param _setToken Instance of the SetToken
* @param _trader Trader whose permission is being set
* @param _status Boolean permission being set
*/
function _updateTradersHistory(ISetToken _setToken, address _trader, bool _status) internal {
if (_status && !permissionInfo[_setToken].tradersHistory.contains(_trader)) {
permissionInfo[_setToken].tradersHistory.push(_trader);
} else if(!_status && permissionInfo[_setToken].tradersHistory.contains(_trader)) {
permissionInfo[_setToken].tradersHistory.removeStorage(_trader);
}
}
/**
* Calculates the amount of a component is going to be traded and whether the component is being bought or sold.
* If currentUnit and targetUnit are the same, function will revert.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to trade
* @param _totalSupply Total supply of _setToken
*
* @return isSendTokenFixed Boolean indicating fixed asset is send token
* @return totalFixedQuantity Amount of fixed token to send or receive
*/
function _calculateTradeSizeAndDirection(
ISetToken _setToken,
IERC20 _component,
uint256 _totalSupply
)
internal
view
returns (bool isSendTokenFixed, uint256 totalFixedQuantity)
{
uint256 protocolFee = controller.getModuleFee(address(this), GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX);
uint256 componentMaxSize = executionInfo[_setToken][_component].maxSize;
(
uint256 currentUnit,
uint256 targetUnit,
uint256 currentNotional,
uint256 targetNotional
) = _getUnitsAndNotionalAmounts(_setToken, _component, _totalSupply);
require(currentUnit != targetUnit, "Target already met");
isSendTokenFixed = targetNotional < currentNotional;
// In order to account for fees taken by protocol when buying the notional difference between currentUnit
// and targetUnit is divided by (1 - protocolFee) to make sure that targetUnit can be met. Failure to
// do so would lead to never being able to meet target of components that need to be bought.
//
// ? - lesserOf: (componentMaxSize, (currentNotional - targetNotional))
// : - lesserOf: (componentMaxSize, (targetNotional - currentNotional) / 10 ** 18 - protocolFee)
totalFixedQuantity = isSendTokenFixed
? componentMaxSize.min(currentNotional.sub(targetNotional))
: componentMaxSize.min(targetNotional.sub(currentNotional).preciseDiv(PreciseUnitMath.preciseUnit().sub(protocolFee)));
}
/**
* Check if all targets are met.
*
* @param _setToken Instance of the SetToken to be rebalanced
*
* @return bool True if all component's target units have been met, otherwise false
*/
function _allTargetsMet(ISetToken _setToken) internal view returns (bool) {
address[] memory rebalanceComponents = rebalanceInfo[_setToken].rebalanceComponents;
for (uint256 i = 0; i < rebalanceComponents.length; i++) {
if (_targetUnmet(_setToken, rebalanceComponents[i])) { return false; }
}
return true;
}
/**
* Determine if passed address is allowed to call trade for the SetToken. If anyoneTrade set to true anyone can call otherwise
* needs to be approved.
*
* @param _setToken Instance of SetToken to be rebalanced
* @param _trader Address of the trader who called contract function
*
* @return bool True if trader is an approved trader for the SetToken
*/
function _isAllowedTrader(ISetToken _setToken, address _trader) internal view returns (bool) {
TradePermissionInfo storage permissions = permissionInfo[_setToken];
return permissions.anyoneTrade || permissions.tradeAllowList[_trader];
}
/**
* Checks if sell conditions are met. The component cannot be WETH and its normalized target
* unit must be less than its default position real unit
*
* @param _setToken Instance of the SetToken to be rebalanced
* @param _component Component evaluated for sale
*
* @return bool True if sell allowed, false otherwise
*/
function _canSell(ISetToken _setToken, address _component) internal view returns(bool) {
return (
_component != address(weth) &&
(
_getNormalizedTargetUnit(_setToken, IERC20(_component)) <
_getDefaultPositionRealUnit(_setToken,IERC20(_component))
)
);
}
/**
* Check if there are any more tokens to sell. Since we allow WETH to float around it's target during rebalances it is not checked.
*
* @param _setToken Instance of the SetToken to be rebalanced
*
* @return bool True if there is not any component that can be sold, otherwise false
*/
function _noTokensToSell(ISetToken _setToken) internal view returns (bool) {
address[] memory rebalanceComponents = rebalanceInfo[_setToken].rebalanceComponents;
for (uint256 i = 0; i < rebalanceComponents.length; i++) {
if (_canSell(_setToken, rebalanceComponents[i]) ) { return false; }
}
return true;
}
/**
* Determines if a target is met. Due to small rounding errors converting between virtual and
* real unit on SetToken we allow for a 1 wei buffer when checking if target is met. In order to
* avoid subtraction overflow errors targetUnits of zero check for an exact amount. WETH is not
* checked as it is allowed to float around its target.
*
* @param _setToken Instance of the SetToken to be rebalanced
* @param _component Component whose target is evaluated
*
* @return bool True if component's target units are met, false otherwise
*/
function _targetUnmet(ISetToken _setToken, address _component) internal view returns(bool) {
if (_component == address(weth)) return false;
uint256 normalizedTargetUnit = _getNormalizedTargetUnit(_setToken, IERC20(_component));
uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, IERC20(_component));
return (normalizedTargetUnit > 0)
? !(normalizedTargetUnit.approximatelyEquals(currentUnit, 1))
: normalizedTargetUnit != currentUnit;
}
/**
* Validate component position unit has not exceeded it's target unit. This is used during tradeRemainingWETH() to make sure
* the amount of component bought does not exceed the targetUnit.
*
* @param _setToken Instance of the SetToken
* @param _component IERC20 component whose position units are to be validated
*/
function _validateComponentPositionUnit(ISetToken _setToken, IERC20 _component) internal view {
uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, _component);
uint256 targetUnit = _getNormalizedTargetUnit(_setToken, _component);
require(currentUnit <= targetUnit, "Can not exceed target unit");
}
/**
* Validate that component is a valid component and enough time has elapsed since component's last trade. Traders
* cannot explicitly trade WETH, it may only implicitly be traded by being the quote asset for other component trades.
*
* @param _setToken Instance of the SetToken
* @param _component IERC20 component to be validated
*/
function _validateTradeParameters(ISetToken _setToken, IERC20 _component) internal view virtual {
require(address(_component) != address(weth), "Can not explicitly trade WETH");
require(
rebalanceInfo[_setToken].rebalanceComponents.contains(address(_component)),
"Component not part of rebalance"
);
TradeExecutionParams memory componentInfo = executionInfo[_setToken][_component];
require(
componentInfo.lastTradeTimestamp.add(componentInfo.coolOffPeriod) <= block.timestamp,
"Component cool off in progress"
);
require(!_setToken.hasExternalPosition(address(_component)), "External positions not allowed");
}
/**
* Extends and/or updates the current component set and its target units with new components and targets,
* Validates inputs, requiring that that new components and new target units arrays are the same size, and
* that the number of old components target units matches the number of current components. Throws if
* a duplicate component has been added.
*
* @param _currentComponents Complete set of current SetToken components
* @param _newComponents Array of new components to add to allocation
* @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of _newComponents array
* @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of
* _setToken.getComponents() array, if component being removed set to 0.
*
* @return aggregateComponents Array of current components extended by new components, without duplicates
* @return aggregateTargetUnits Array of old component target units extended by new target units, without duplicates
*/
function _getAggregateComponentsAndUnits(
address[] memory _currentComponents,
address[] calldata _newComponents,
uint256[] calldata _newComponentsTargetUnits,
uint256[] calldata _oldComponentsTargetUnits
)
internal
pure
returns (address[] memory aggregateComponents, uint256[] memory aggregateTargetUnits)
{
// Don't use validate arrays because empty arrays are valid
require(_newComponents.length == _newComponentsTargetUnits.length, "Array length mismatch");
require(_currentComponents.length == _oldComponentsTargetUnits.length, "Old Components targets missing");
aggregateComponents = _currentComponents.extend(_newComponents);
aggregateTargetUnits = _oldComponentsTargetUnits.extend(_newComponentsTargetUnits);
require(!aggregateComponents.hasDuplicate(), "Cannot duplicate components");
}
/**
* Get the SetToken's default position as uint256
*
* @param _setToken Instance of the SetToken
* @param _component IERC20 component to fetch the default position for
*
* return uint256 Real unit position
*/
function _getDefaultPositionRealUnit(ISetToken _setToken, IERC20 _component) internal view returns (uint256) {
return _setToken.getDefaultPositionRealUnit(address(_component)).toUint256();
}
/**
* Gets exchange adapter address for a component after checking that it exists in the
* IntegrationRegistry. This method is called during a trade and must validate the adapter
* because its state may have changed since it was set in a separate transaction.
*
* @param _setToken Instance of the SetToken to be rebalanced
* @param _component IERC20 component whose exchange adapter is fetched
*
* @return IExchangeAdapter Adapter address
*/
function _getExchangeAdapter(ISetToken _setToken, IERC20 _component) internal view returns(IIndexExchangeAdapter) {
return IIndexExchangeAdapter(getAndValidateAdapter(executionInfo[_setToken][_component].exchangeName));
}
/**
* Calculates and returns the normalized target unit value.
*
* @param _setToken Instance of the SetToken to be rebalanced
* @param _component IERC20 component whose normalized target unit is required
*
* @return uint256 Normalized target unit of the component
*/
function _getNormalizedTargetUnit(ISetToken _setToken, IERC20 _component) internal view returns(uint256) {
// (targetUnit * current position multiplier) / position multiplier when rebalance started
return executionInfo[_setToken][_component]
.targetUnit
.mul(_setToken.positionMultiplier().toUint256())
.div(rebalanceInfo[_setToken].positionMultiplier);
}
/**
* Gets unit and notional amount values for current position and target. These are necessary
* to calculate the trade size and direction for regular trades and the `sendQuantity` for
* remainingWEth trades.
*
* @param _setToken Instance of the SetToken to rebalance
* @param _component IERC20 component to calculate notional amounts for
* @param _totalSupply SetToken total supply
*
* @return uint256 Current default position real unit of component
* @return uint256 Normalized unit of the trade target
* @return uint256 Current notional amount: total notional amount of SetToken default position
* @return uint256 Target notional amount: Total SetToken supply * targetUnit
*/
function _getUnitsAndNotionalAmounts(ISetToken _setToken, IERC20 _component, uint256 _totalSupply)
internal
view
returns (uint256, uint256, uint256, uint256)
{
uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, _component);
uint256 targetUnit = _getNormalizedTargetUnit(_setToken, _component);
return (
currentUnit,
targetUnit,
_totalSupply.getDefaultTotalNotional(currentUnit),
_totalSupply.preciseMulCeil(targetUnit)
);
}
/* ============== Modifier Helpers ===============
* Internal functions used to reduce bytecode size
*/
/*
* Trader must be permissioned for SetToken
*/
function _validateOnlyAllowedTrader(ISetToken _setToken) internal view {
require(_isAllowedTrader(_setToken, msg.sender), "Address not permitted to trade");
}
/*
* Trade must be an EOA if `anyoneTrade` has been enabled for SetToken on the module.
*/
function _validateOnlyEOAIfUnrestricted(ISetToken _setToken) internal view {
if(permissionInfo[_setToken].anyoneTrade) {
require(msg.sender == tx.origin, "Caller must be EOA Address");
}
}
}
// 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 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 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 <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 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 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 >= -2**127 && value < 2**127, "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 >= -2**63 && value < 2**63, "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 >= -2**31 && value < 2**31, "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 >= -2**15 && value < 2**15, "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 >= -2**7 && value < 2**7, "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) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(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, 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;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*
* CHANGELOG:
* - 4/21/21: Added validatePairsWithArray methods
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IIndexExchangeAdapter {
function getSpender() external view returns(address);
/**
* Returns calldata for executing trade on given adapter's exchange when using the GeneralIndexModule.
*
* @param _sourceToken Address of source token to be sold
* @param _destinationToken Address of destination token to buy
* @param _destinationAddress Address that assets should be transferred to
* @param _isSendTokenFixed Boolean indicating if the send quantity is fixed, used to determine correct trade interface
* @param _sourceQuantity Fixed/Max amount of source token to sell
* @param _destinationQuantity Min/Fixed amount of destination tokens to receive
* @param _data Arbitrary bytes that can be used to store exchange specific parameters or logic
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes Trade calldata
*/
function getTradeCalldata(
address _sourceToken,
address _destinationToken,
address _destinationAddress,
bool _isSendTokenFixed,
uint256 _sourceQuantity,
uint256 _destinationQuantity,
bytes memory _data
)
external
view
returns (address, uint256, bytes memory);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
/**
* @title Invoke
* @author Set Protocol
*
* A collection of common utility functions for interacting with the SetToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the SetToken to set approvals of the ERC20 token to a spender.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the SetToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ISetToken _setToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_setToken.invoke(_token, 0, callData);
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_setToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
* The new SetToken balance must equal the existing balance less the quantity transferred
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the SetToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken));
Invoke.invokeTransfer(_setToken, _token, _to, _quantity);
// Get new balance of transferred token for SetToken
uint256 newBalance = IERC20(_token).balanceOf(address(_setToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the SetToken to unwrap the passed quantity of WETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_setToken.invoke(_weth, 0, callData);
}
/**
* Instructs the SetToken to wrap the passed quantity of ETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IWETH
* @author Set Protocol
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit()
external
payable;
function withdraw(
uint256 wad
)
external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol";
import { IController } from "../../interfaces/IController.sol";
import { IModule } from "../../interfaces/IModule.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { Invoke } from "./Invoke.sol";
import { Position } from "./Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { ResourceIdentifier } from "./ResourceIdentifier.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title ModuleBase
* @author Set Protocol
*
* Abstract class that houses common Module-related state and functions.
*
* CHANGELOG:
* - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size
*
*/
abstract contract ModuleBase is IModule {
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidSet(ISetToken _setToken) {
_validateOnlyManagerAndValidSet(_setToken);
_;
}
modifier onlySetManager(ISetToken _setToken, address _caller) {
_validateOnlySetManager(_setToken, _caller);
_;
}
modifier onlyValidAndInitializedSet(ISetToken _setToken) {
_validateOnlyValidAndInitializedSet(_setToken);
_;
}
/**
* Throws if the sender is not a SetToken's module or module not enabled
*/
modifier onlyModule(ISetToken _setToken) {
_validateOnlyModule(_setToken);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the SetToken is valid
*/
modifier onlyValidAndPendingSet(ISetToken _setToken) {
_validateOnlyValidAndPendingSet(_setToken);
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the SetToken
*/
function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) {
return _setToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the SetToken's manager
*/
function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) {
return _setToken.manager() == _toCheck;
}
/**
* Returns true if SetToken must be enabled on the controller
* and module is registered on the SetToken
*/
function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) {
return controller.isSet(address(_setToken)) &&
_setToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
/* ============== Modifier Helpers ===============
* Internal functions used to reduce bytecode size
*/
/**
* Caller must SetToken manager and SetToken must be valid and initialized
*/
function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view {
require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager");
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
}
/**
* Caller must SetToken manager
*/
function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view {
require(isSetManager(_setToken, _caller), "Must be the SetToken manager");
}
/**
* SetToken must be valid and initialized
*/
function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view {
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
}
/**
* Caller must be initialized module and module must be enabled on the controller
*/
function _validateOnlyModule(ISetToken _setToken) internal view {
require(
_setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
}
/**
* SetToken must be in a pending state and module must be in pending state
*/
function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title Position
* @author Set Protocol
*
* Collection of helper functions for handling and updating SetToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the SetToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the SetToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the SetToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the SetToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ISetToken _setToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the SetToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _setToken Address of SetToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_setToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_setToken, _component)) {
_setToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_setToken, _component)) {
_setToken.removeComponent(_component);
}
}
_setToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _setToken SetToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ISetToken _setToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_setToken.isComponent(_component)) {
_setToken.addComponent(_component);
_setToken.addExternalPositionModule(_component, _module);
} else if (!_setToken.isExternalPositionModule(_component, _module)) {
_setToken.addExternalPositionModule(_component, _module);
}
_setToken.editExternalPositionUnit(_component, _module, _newUnit);
_setToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _setToken.getExternalPositionModules(_component);
if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_setToken.removeComponent(_component);
}
_setToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _setTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_setTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) {
int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component);
return _setToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @param _setTotalSupply Current SetToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ISetToken _setToken,
address _component,
uint256 _setTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));
uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit;
if (currentBalance > 0) {
newTokenUnit = calculateDefaultEditPositionUnit(
_setTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
} else {
newTokenUnit = 0;
}
editDefaultPosition(_setToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of SetToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _setTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
* - 4/21/21: Added approximatelyEquals function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
/**
* @dev Returns true if a =~ b within range, false otherwise.
*/
function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) {
return a <= b.add(range) && a >= b.sub(range);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title Uint256ArrayUtils
* @author Set Protocol
*
* Utility functions to handle Uint256 Arrays
*/
library Uint256ArrayUtils {
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
uint256[] memory newUints = new uint256[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newUints[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newUints[aLength + j] = B[j];
}
return newUints;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title ExplicitERC20
* @author Set Protocol
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IModule
* @author Set Protocol
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IController } from "../../interfaces/IController.sol";
import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol";
import { IPriceOracle } from "../../interfaces/IPriceOracle.sol";
import { ISetValuer } from "../../interfaces/ISetValuer.sol";
/**
* @title ResourceIdentifier
* @author Set Protocol
*
* A collection of utility functions to fetch information related to Resource contracts in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// SetValuer resource will always be resource ID 2 in the system
uint256 constant internal SET_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller
*/
function getSetValuer(IController _controller) internal view returns (ISetValuer) {
return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot 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 Returns the integer division of two signed 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(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 Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot 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 Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot 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: 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);
}
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);
}
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Set Protocol
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "../interfaces/ISetToken.sol";
interface ISetValuer {
function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256);
}
| Check if there are any more tokens to sell. Since we allow WETH to float around it's target during rebalances it is not checked. _setToken Instance of the SetToken to be rebalanced return bool True if there is not any component that can be sold, otherwise false/ | function _noTokensToSell(ISetToken _setToken) internal view returns (bool) {
address[] memory rebalanceComponents = rebalanceInfo[_setToken].rebalanceComponents;
for (uint256 i = 0; i < rebalanceComponents.length; i++) {
}
return true;
}
| 6,960,913 |
// SPDX-License-Identifier: MIT
/// @title OMNI Token V1 / Ethereum v1
/// @author Alfredo Lopez / Arthur Miranda / OMNI App 2021.5 */
pragma solidity 0.8.4;
import "../@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol";
import "../@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "../@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "../@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../main/Claimable.sol";
import "./Math.sol";
struct FrozenWallet {
bool scheduled;
uint32 startDay;
uint32 afterDays;
address wallet;
uint256 totalAmount;
uint256 dailyAmount;
uint256 monthlyAmount;
uint256 initialAmount;
}
struct VestingType {
uint256 dailyRate;
uint256 initialRate;
uint256 afterDays;
uint256 monthRate;
uint256 monthDelay;
bool vesting;
bool vestingType; //true for daily rate and false for monthly rate
}
/**
* @title Vesting Methods
* @dev All Method to permit handle the Vesting Process of OMN token
*/
contract Vesting is OwnableUpgradeable, Math, Claimable, PausableUpgradeable, ERC20PermitUpgradeable {
using SafeMathUpgradeable for uint256;
// Mapping of FrozenWallet
// Address Wallets -> Struc FrozenWallet
mapping (address => FrozenWallet) public frozenWallets;
// Array of Struc Vesting Types
VestingType[] public vestingTypes;
// Event
event inFrozenWallet(
bool scheduled,
uint32 startDay,
uint32 afterDays,
address indexed wallet,
uint256 indexed totalAmount,
uint256 dailyAmount,
uint256 monthlyAmount,
uint256 initialAmount
);
/**
* @dev Method to permit to get the Exactly Unix Epoch of Token Generate Event
*/
function getReleaseTime() public pure returns (uint256) {
return 1626440400; // "Friday, 16 July 2021 13:00:00 GMT"
}
/**
* @dev Principal Method to permit Upload all wallets in all allocation, based on Vesting Process
* @dev this method was merge with transferMany method for reduce the cost in gass around 30%
* @param addresses Array of Wallets will be Frozen with Locked and Unlocked Token Based on the Predefined Allocation
* @param totalAmounts Array of Amount coprresponding with each wallets, will be Locked and Unlocked Based on the Predefined Allocation
* @param vestingTypeIndex Index corresponding to the List of Wallets to be Upload in the Smart Contract ERC20 of OMNI Foundation
*/
function addAllocations(address[] calldata addresses, uint256[] calldata totalAmounts, uint256 vestingTypeIndex) external onlyOwner() whenNotPaused() returns (bool) {
require(addresses.length == totalAmounts.length, "Address and totalAmounts length must be same");
VestingType memory vestingType = vestingTypes[vestingTypeIndex];
require(vestingType.vesting, "Vesting type isn't found");
uint256 addressesLength = addresses.length;
uint256 total = 0;
for(uint256 i = 0; i < addressesLength; i++) {
address _address = addresses[i];
require(_address != address(0), "ERC20: transfer to the zero address");
require(!isBlacklisted(_address), "ERC20 OMN: recipient account is blacklisted");
require(totalAmounts[i] != 0, "ERC20 OMN: total amount token is zero");
total = total.add(totalAmounts[i]);
}
_balances[msg.sender] = _balances[msg.sender].sub(total, "ERC20: transfer amount exceeds balance");
for(uint256 j = 0; j < addressesLength; j++) {
address _address = addresses[j];
uint256 totalAmount = totalAmounts[j];
uint256 dailyAmount;
uint256 monthlyAmount;
uint256 afterDay;
uint256 initialAmount;
if (vestingType.vestingType) {
dailyAmount = mulDiv(totalAmounts[j], vestingType.dailyRate, 1e18);
monthlyAmount = 0;
afterDay = vestingType.afterDays;
} else {
// WE FIXED PUBLIC ALLOCATION TO 50% MONTHLY AS PER OMNI WHITE PAPER.
dailyAmount = 0;
monthlyAmount = mulDiv(totalAmounts[j], 500000000000000000, 1e18);
afterDay = vestingType.monthDelay.mul(30 days);
}
/**
* @dev The Allocation #4, VestingTypeIndex #3, correspond the Public Allocation
* @dev which will be managed by an IDO, within the ApolloX Platform, in the Binance Smart Chain
* @dev Therefore, 34% of said allocation, which is the first part to be delivered during the IDO,
* @dev will be previously transferred to ApolloX to be delivered to the Stakeholders participating
* @dev in the IDO prior to the vesting process as such.
* @dev the remaining 66 percent will be delivered in two stages of 33% every 30 days, completing 100% in two months.
*/
if (vestingTypeIndex == 3) {
initialAmount = 0;
} else {
initialAmount = mulDiv(totalAmounts[j], vestingType.initialRate, 1e18);
}
// Transfer Token to the Wallet
_balances[_address] = _balances[_address].add(totalAmount);
emit Transfer(msg.sender, _address, totalAmount);
// Frozen Wallet
addFrozenWallet(_address, totalAmount, dailyAmount, monthlyAmount, initialAmount, afterDay);
}
return true;
}
/**
* @dev Auxiliary Method to permit Upload all wallets in all allocation, based on Vesting Process
* @param wallet Wallet will be Frozen based on correspondig Allocation
* @param totalAmount Total Amount of Stake holder based on Investment and the Allocation to participate
* @param dailyAmount Daily Amount of Stake holder based on Investment and the Allocation to participate
* @param monthlyAmount Monthly Amount of Stake holder based on Investment and the Allocation to participate
* @param initialAmount Initial Amount of Stake holder based on Investment and the Allocation to participate
* @param afterDays Period of Days after to start Unlocked Token based on the Allocation to participate
*/
function addFrozenWallet(address wallet, uint256 totalAmount, uint256 dailyAmount,uint256 monthlyAmount ,uint256 initialAmount, uint256 afterDays) internal {
uint256 releaseTime = getReleaseTime();
// Create frozen wallets
FrozenWallet memory frozenWallet = FrozenWallet(
true,
uint32(releaseTime.add(afterDays)),
uint32(afterDays),
wallet,
totalAmount,
dailyAmount,
monthlyAmount,
initialAmount
);
// Add wallet to frozen wallets
frozenWallets[wallet] = frozenWallet;
// emit Event add Frozen Wallet
emit inFrozenWallet(
true,
uint32(releaseTime.add(afterDays)),
uint32(afterDays),
wallet,
totalAmount,
dailyAmount,
monthlyAmount,
initialAmount);
}
/**
* @dev Auxiliary Method to permit to get the Last Exactly Unix Epoch of Blockchain timestamp
*/
function getTimestamp() public view returns (uint256) {
return block.timestamp;
}
/**
* @dev Auxiliary Method to permit get the number of days elapsed time from the TGE to the current moment
* @param afterDays Period of Days after to start Unlocked Token based on the Allocation to participate
*/
function getDays(uint256 afterDays) public view returns (uint256 dias) {
uint256 releaseTime = getReleaseTime();
uint256 time = releaseTime.add(afterDays);
if (block.timestamp < time) {
return dias;
}
uint256 diff = block.timestamp.sub(time);
dias = diff.div(24 hours);
}
/**
* @dev Auxiliary Method to permit get the number of months elapsed time from the TGE to the current moment
* @param afterDays Period of Days after to start Unlocked Token based on the Allocation to participate */
function getMonths(uint afterDays) public view returns (uint256 months) {
uint256 releaseTime = getReleaseTime();
uint256 time = releaseTime.add(afterDays);
if (block.timestamp < time) {
return months;
}
uint256 diff = block.timestamp.sub(time);
months = diff.div(30 days);
}
/**
* @dev Auxiliary Method to permit to verify if the vesting processs start or not
*/
function isStarted(uint256 startDay) public view returns (bool) {
uint256 releaseTime = getReleaseTime();
if (block.timestamp < releaseTime || block.timestamp < startDay) {
return false;
}
return true;
}
/**
* @dev Auxiliary Method to permit get of token can be transferable based on Allocation of the Frozen Wallet
* @param sender Wallets of Stakeholders to verify amount of Token are Unlocked based on Allocation
*/
function getTransferableAmount(address sender) public view returns (uint256 transferableAmount) {
uint256 releaseTime = getReleaseTime();
if (block.timestamp < releaseTime) {
return transferableAmount;
}
FrozenWallet memory frozenWallet = frozenWallets[sender];
if ((frozenWallet.monthlyAmount == 0) && (frozenWallet.dailyAmount != 0)) {
uint256 dias = getDays(frozenWallet.afterDays);
uint256 dailyTransferableAmount = frozenWallet.dailyAmount.mul(dias);
transferableAmount = dailyTransferableAmount.add(frozenWallet.initialAmount);
}
if ((frozenWallet.monthlyAmount != 0) && (frozenWallet.dailyAmount == 0)) {
uint256 meses = getMonths(frozenWallet.afterDays);
uint256 monthlyTransferableAmount = frozenWallet.monthlyAmount.mul(meses);
transferableAmount = monthlyTransferableAmount.add(frozenWallet.initialAmount);
}
if (transferableAmount > frozenWallet.totalAmount) {
return frozenWallet.totalAmount;
}
}
/**
* @dev Auxiliary Method to permit get of token can't be transferable based on Allocation of the Frozen Wallet
* @param sender Wallets of Stakeholders to verify amount of Token are locked based on Allocation
*/
function getRestAmount(address sender) public view returns (uint256 restAmount) {
uint256 transferableAmount = getTransferableAmount(sender);
restAmount = frozenWallets[sender].totalAmount.sub(transferableAmount);
}
}
| Auxiliary Method to permit Upload all wallets in all allocation, based on Vesting Process wallet Wallet will be Frozen based on correspondig Allocation totalAmount Total Amount of Stake holder based on Investment and the Allocation to participate dailyAmount Daily Amount of Stake holder based on Investment and the Allocation to participate monthlyAmount Monthly Amount of Stake holder based on Investment and the Allocation to participate initialAmount Initial Amount of Stake holder based on Investment and the Allocation to participate afterDays Period of Days after to start Unlocked Token based on the Allocation to participate/ Create frozen wallets Add wallet to frozen wallets emit Event add Frozen Wallet | function addFrozenWallet(address wallet, uint256 totalAmount, uint256 dailyAmount,uint256 monthlyAmount ,uint256 initialAmount, uint256 afterDays) internal {
uint256 releaseTime = getReleaseTime();
FrozenWallet memory frozenWallet = FrozenWallet(
true,
uint32(releaseTime.add(afterDays)),
uint32(afterDays),
wallet,
totalAmount,
dailyAmount,
monthlyAmount,
initialAmount
);
frozenWallets[wallet] = frozenWallet;
emit inFrozenWallet(
true,
uint32(releaseTime.add(afterDays)),
uint32(afterDays),
wallet,
totalAmount,
dailyAmount,
monthlyAmount,
initialAmount);
}
| 6,378,913 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
//Libraries
import "../libraries/TxDataUtils.sol";
import "../openzeppelin-solidity/SafeMath.sol";
//Inheritance
import "../interfaces/IVerifier.sol";
//Interfaces
import "../interfaces/IAddressResolver.sol";
import "../interfaces/IAssetHandler.sol";
import "../interfaces/ILPVerifier.sol";
import "../interfaces/Ubeswap/IStakingRewards.sol";
import "../interfaces/Ubeswap/IUniswapV2Pair.sol";
contract UbeswapFarmVerifier is TxDataUtils, IVerifier {
using SafeMath for uint;
/**
* @dev Parses the transaction data to make sure the transaction is valid
* @param addressResolver Address of AddressResolver contract
* @param pool Address of the pool
* @param to External contract address
* @param data Transaction call data
* @return (uint, address) Whether the transaction is valid and the received asset
*/
function verify(address addressResolver, address pool, address to, bytes calldata data) external override returns (bool, address) {
bytes4 method = getMethod(data);
address assetHandlerAddress = IAddressResolver(addressResolver).getContractAddress("AssetHandler");
address ubeswapLPVerifierAddress = IAddressResolver(addressResolver).assetVerifiers(2);
//Get assets
(address pair, address rewardToken) = ILPVerifier(ubeswapLPVerifierAddress).getFarmTokens(to);
if (method == bytes4(keccak256("stake(uint256)")))
{
//Parse transaction data
uint numberOfLPTokens = uint(getInput(data, 0));
//Check if assets are supported
require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token");
require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair");
emit Staked(pool, to, numberOfLPTokens, block.timestamp);
return (true, rewardToken);
}
else if (method == bytes4(keccak256("withdraw(uint256)")))
{
//Parse transaction data
uint numberOfLPTokens = uint(getInput(data, 0));
//Check if assets are supported
require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair");
emit Unstaked(pool, to, numberOfLPTokens, block.timestamp);
return (true, pair);
}
else if (method == bytes4(keccak256("getReward()")))
{
//Check if assets are supported
require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token");
emit ClaimedReward(pool, to, block.timestamp);
return (true, rewardToken);
}
else if (method == bytes4(keccak256("exit()")))
{
uint numberOfLPTokens = IStakingRewards(to).balanceOf(pool);
//Check if assets are supported
require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token");
require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair");
emit Unstaked(pool, to, numberOfLPTokens, block.timestamp);
emit ClaimedReward(pool, to, block.timestamp);
return (true, rewardToken);
}
return (false, address(0));
}
/* ========== EVENTS ========== */
event Staked(address indexed pool, address indexed farm, uint numberOfLPTokens, uint timestamp);
event Unstaked(address indexed pool, address indexed farm, uint numberOfLPTokens, uint timestamp);
event ClaimedReward(address indexed pool, address indexed farm, uint timestamp);
} | Parses the transaction data to make sure the transaction is valid addressResolver Address of AddressResolver contract pool Address of the pool to External contract address data Transaction call data return (uint, address) Whether the transaction is valid and the received asset/Get assetsParse transaction dataCheck if assets are supportedParse transaction dataCheck if assets are supportedCheck if assets are supportedCheck if assets are supported | function verify(address addressResolver, address pool, address to, bytes calldata data) external override returns (bool, address) {
bytes4 method = getMethod(data);
address assetHandlerAddress = IAddressResolver(addressResolver).getContractAddress("AssetHandler");
address ubeswapLPVerifierAddress = IAddressResolver(addressResolver).assetVerifiers(2);
(address pair, address rewardToken) = ILPVerifier(ubeswapLPVerifierAddress).getFarmTokens(to);
if (method == bytes4(keccak256("stake(uint256)")))
{
uint numberOfLPTokens = uint(getInput(data, 0));
require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token");
require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair");
emit Staked(pool, to, numberOfLPTokens, block.timestamp);
return (true, rewardToken);
}
else if (method == bytes4(keccak256("withdraw(uint256)")))
{
uint numberOfLPTokens = uint(getInput(data, 0));
require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair");
emit Unstaked(pool, to, numberOfLPTokens, block.timestamp);
return (true, pair);
}
else if (method == bytes4(keccak256("getReward()")))
{
require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token");
emit ClaimedReward(pool, to, block.timestamp);
return (true, rewardToken);
}
else if (method == bytes4(keccak256("exit()")))
{
uint numberOfLPTokens = IStakingRewards(to).balanceOf(pool);
require(IAssetHandler(assetHandlerAddress).isValidAsset(rewardToken), "UbeswapFarmVerifier: unsupported reward token");
require(IAssetHandler(assetHandlerAddress).isValidAsset(pair), "UbeswapFarmVerifier: unsupported liquidity pair");
emit Unstaked(pool, to, numberOfLPTokens, block.timestamp);
emit ClaimedReward(pool, to, block.timestamp);
return (true, rewardToken);
}
return (false, address(0));
}
event Staked(address indexed pool, address indexed farm, uint numberOfLPTokens, uint timestamp);
event Unstaked(address indexed pool, address indexed farm, uint numberOfLPTokens, uint timestamp);
event ClaimedReward(address indexed pool, address indexed farm, uint timestamp);
| 5,354,722 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// File: contracts/lib/MathUint.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint
{
function mul(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a * b;
require(a == 0 || c / a == b, "MUL_OVERFLOW");
}
function sub(
uint a,
uint b
)
internal
pure
returns (uint)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
function add(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
}
// File: contracts/lib/EIP712.sol
// Copyright 2017 Loopring Technology Limited.
library EIP712
{
struct Domain {
string name;
string version;
address verifyingContract;
}
bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
string constant internal EIP191_HEADER = "\x19\x01";
function hash(Domain memory domain)
internal
pure
returns (bytes32)
{
uint _chainid;
assembly { _chainid := chainid() }
return keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(domain.name)),
keccak256(bytes(domain.version)),
_chainid,
domain.verifyingContract
)
);
}
function hashPacked(
bytes32 domainSeperator,
bytes memory encodedData
)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(EIP191_HEADER, domainSeperator, keccak256(encodedData))
);
}
}
// File: contracts/thirdparty/BytesUtil.sol
//Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
library BytesUtil {
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
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)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) {
require(_bytes.length >= (_start + 3));
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
require(_bytes.length >= (_start + 4));
bytes4 tempBytes4;
assembly {
tempBytes4 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes4;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function fastSHA256(
bytes memory data
)
internal
view
returns (bytes32)
{
bytes32[] memory result = new bytes32[](1);
bool success;
assembly {
let ptr := add(data, 32)
success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32)
}
require(success, "SHA256_FAILED");
return result[0];
}
}
// File: contracts/lib/AddressUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for addresses
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library AddressUtil
{
using AddressUtil for *;
function isContract(
address addr
)
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;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(addr) }
return (codehash != 0x0 &&
codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
function toPayable(
address addr
)
internal
pure
returns (address payable)
{
return payable(addr);
}
// Works like address.send but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETH(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
if (amount == 0) {
return true;
}
address payable recipient = to.toPayable();
/* solium-disable-next-line */
(success,) = recipient.call{value: amount, gas: gasLimit}("");
}
// Works like address.transfer but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETHAndVerify(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
success = to.sendETH(amount, gasLimit);
require(success, "TRANSFER_FAILURE");
}
// Works like call but is slightly more efficient when data
// needs to be copied from memory to do the call.
function fastCall(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bool success, bytes memory returnData)
{
if (to != address(0)) {
assembly {
// Do the call
success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
// Copy the return data
let size := returndatasize()
returnData := mload(0x40)
mstore(returnData, size)
returndatacopy(add(returnData, 32), 0, size)
// Update free memory pointer
mstore(0x40, add(returnData, add(32, size)))
}
}
}
// Like fastCall, but throws when the call is unsuccessful.
function fastCallAndVerify(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bytes memory returnData)
{
bool success;
(success, returnData) = fastCall(to, gasLimit, value, data);
if (!success) {
assembly {
revert(add(returnData, 32), mload(returnData))
}
}
}
}
// File: contracts/lib/ERC1271.sol
// Copyright 2017 Loopring Technology Limited.
abstract contract ERC1271 {
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function isValidSignature(
bytes32 _hash,
bytes memory _signature)
public
view
virtual
returns (bytes4 magicValueB32);
}
// File: contracts/lib/SignatureUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title SignatureUtil
/// @author Daniel Wang - <[email protected]>
/// @dev This method supports multihash standard. Each signature's last byte indicates
/// the signature's type.
library SignatureUtil
{
using BytesUtil for bytes;
using MathUint for uint;
using AddressUtil for address;
enum SignatureType {
ILLEGAL,
INVALID,
EIP_712,
ETH_SIGN,
WALLET // deprecated
}
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function verifySignatures(
bytes32 signHash,
address[] memory signers,
bytes[] memory signatures
)
internal
view
returns (bool)
{
require(signers.length == signatures.length, "BAD_SIGNATURE_DATA");
address lastSigner;
for (uint i = 0; i < signers.length; i++) {
require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER");
lastSigner = signers[i];
if (!verifySignature(signHash, signers[i], signatures[i])) {
return false;
}
}
return true;
}
function verifySignature(
bytes32 signHash,
address signer,
bytes memory signature
)
internal
view
returns (bool)
{
if (signer == address(0)) {
return false;
}
return signer.isContract()?
verifyERC1271Signature(signHash, signer, signature):
verifyEOASignature(signHash, signer, signature);
}
function recoverECDSASigner(
bytes32 signHash,
bytes memory signature
)
internal
pure
returns (address)
{
if (signature.length != 65) {
return address(0);
}
bytes32 r;
bytes32 s;
uint8 v;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := and(mload(add(signature, 0x41)), 0xff)
}
// See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v == 27 || v == 28) {
return ecrecover(signHash, v, r, s);
} else {
return address(0);
}
}
function verifyEOASignature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
pure
returns (bool success)
{
if (signer == address(0)) {
return false;
}
uint signatureTypeOffset = signature.length.sub(1);
SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset));
// Strip off the last byte of the signature by updating the length
assembly {
mstore(signature, signatureTypeOffset)
}
if (signatureType == SignatureType.EIP_712) {
success = (signer == recoverECDSASigner(signHash, signature));
} else if (signatureType == SignatureType.ETH_SIGN) {
bytes32 hash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash)
);
success = (signer == recoverECDSASigner(hash, signature));
} else {
success = false;
}
// Restore the signature length
assembly {
mstore(signature, add(signatureTypeOffset, 1))
}
return success;
}
function verifyERC1271Signature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
view
returns (bool)
{
bytes memory callData = abi.encodeWithSelector(
ERC1271.isValidSignature.selector,
signHash,
signature
);
(bool success, bytes memory result) = signer.staticcall(callData);
return (
success &&
result.length == 32 &&
result.toBytes4(0) == ERC1271_MAGICVALUE
);
}
}
// File: contracts/lib/Ownable.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Ownable
/// @author Brecht Devos - <[email protected]>
/// @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.
constructor()
{
owner = msg.sender;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner()
{
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to transfer control of the contract to a
/// new owner.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
virtual
onlyOwner
{
require(newOwner != address(0), "ZERO_ADDRESS");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership()
public
onlyOwner
{
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
}
// File: contracts/iface/Wallet.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Wallet
/// @dev Base contract for smart wallets.
/// Sub-contracts must NOT use non-default constructor to initialize
/// wallet states, instead, `init` shall be used. This is to enable
/// proxies to be deployed in front of the real wallet contract for
/// saving gas.
///
/// @author Daniel Wang - <[email protected]>
interface Wallet
{
function version() external pure returns (string memory);
function owner() external view returns (address);
/// @dev Set a new owner.
function setOwner(address newOwner) external;
/// @dev Adds a new module. The `init` method of the module
/// will be called with `address(this)` as the parameter.
/// This method must throw if the module has already been added.
/// @param _module The module's address.
function addModule(address _module) external;
/// @dev Removes an existing module. This method must throw if the module
/// has NOT been added or the module is the wallet's only module.
/// @param _module The module's address.
function removeModule(address _module) external;
/// @dev Checks if a module has been added to this wallet.
/// @param _module The module to check.
/// @return True if the module exists; False otherwise.
function hasModule(address _module) external view returns (bool);
/// @dev Binds a method from the given module to this
/// wallet so the method can be invoked using this wallet's default
/// function.
/// Note that this method must throw when the given module has
/// not been added to this wallet.
/// @param _method The method's 4-byte selector.
/// @param _module The module's address. Use address(0) to unbind the method.
function bindMethod(bytes4 _method, address _module) external;
/// @dev Returns the module the given method has been bound to.
/// @param _method The method's 4-byte selector.
/// @return _module The address of the bound module. If no binding exists,
/// returns address(0) instead.
function boundMethodModule(bytes4 _method) external view returns (address _module);
/// @dev Performs generic transactions. Any module that has been added to this
/// wallet can use this method to transact on any third-party contract with
/// msg.sender as this wallet itself.
///
/// Note: 1) this method must ONLY allow invocations from a module that has
/// been added to this wallet. The wallet owner shall NOT be permitted
/// to call this method directly. 2) Reentrancy inside this function should
/// NOT cause any problems.
///
/// @param mode The transaction mode, 1 for CALL, 2 for DELEGATECALL.
/// @param to The desitination address.
/// @param value The amount of Ether to transfer.
/// @param data The data to send over using `to.call{value: value}(data)`
/// @return returnData The transaction's return value.
function transact(
uint8 mode,
address to,
uint value,
bytes calldata data
)
external
returns (bytes memory returnData);
}
// File: contracts/iface/Module.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Module
/// @dev Base contract for all smart wallet modules.
///
/// @author Daniel Wang - <[email protected]>
interface Module
{
/// @dev Activates the module for the given wallet (msg.sender) after the module is added.
/// Warning: this method shall ONLY be callable by a wallet.
function activate() external;
/// @dev Deactivates the module for the given wallet (msg.sender) before the module is removed.
/// Warning: this method shall ONLY be callable by a wallet.
function deactivate() external;
}
// File: contracts/lib/ERC20.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ERC20 Token Interface
/// @dev see https://github.com/ethereum/EIPs/issues/20
/// @author Daniel Wang - <[email protected]>
abstract contract ERC20
{
function totalSupply()
public
view
virtual
returns (uint);
function balanceOf(
address who
)
public
view
virtual
returns (uint);
function allowance(
address owner,
address spender
)
public
view
virtual
returns (uint);
function transfer(
address to,
uint value
)
public
virtual
returns (bool);
function transferFrom(
address from,
address to,
uint value
)
public
virtual
returns (bool);
function approve(
address spender,
uint value
)
public
virtual
returns (bool);
}
// File: contracts/iface/ModuleRegistry.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ModuleRegistry
/// @dev A registry for modules.
///
/// @author Daniel Wang - <[email protected]>
interface ModuleRegistry
{
/// @dev Registers and enables a new module.
function registerModule(address module) external;
/// @dev Disables a module
function disableModule(address module) external;
/// @dev Returns true if the module is registered and enabled.
function isModuleEnabled(address module) external view returns (bool);
/// @dev Returns the list of enabled modules.
function enabledModules() external view returns (address[] memory _modules);
/// @dev Returns the number of enbaled modules.
function numOfEnabledModules() external view returns (uint);
/// @dev Returns true if the module is ever registered.
function isModuleRegistered(address module) external view returns (bool);
}
// File: contracts/base/Controller.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Controller
///
/// @author Daniel Wang - <[email protected]>
abstract contract Controller
{
function moduleRegistry()
external
view
virtual
returns (ModuleRegistry);
function walletFactory()
external
view
virtual
returns (address);
}
// File: contracts/iface/PriceOracle.sol
// Copyright 2017 Loopring Technology Limited.
/// @title PriceOracle
interface PriceOracle
{
// @dev Return's the token's value in ETH
function tokenValue(address token, uint amount)
external
view
returns (uint value);
}
// File: contracts/lib/Claimable.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Claimable
/// @author Brecht Devos - <[email protected]>
/// @dev Extension for the Ownable contract, where the ownership needs
/// to be claimed. This allows the new owner to accept the transfer.
contract Claimable is Ownable
{
address public pendingOwner;
/// @dev Modifier throws if called by any account other than the pendingOwner.
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to set the pendingOwner address.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
override
onlyOwner
{
require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS");
pendingOwner = newOwner;
}
/// @dev Allows the pendingOwner address to finalize the transfer.
function claimOwnership()
public
onlyPendingOwner
{
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/base/DataStore.sol
// Copyright 2017 Loopring Technology Limited.
/// @title DataStore
/// @dev Modules share states by accessing the same storage instance.
/// Using ModuleStorage will achieve better module decoupling.
///
/// @author Daniel Wang - <[email protected]>
abstract contract DataStore
{
modifier onlyWalletModule(address wallet)
{
requireWalletModule(wallet);
_;
}
function requireWalletModule(address wallet) view internal
{
require(Wallet(wallet).hasModule(msg.sender), "UNAUTHORIZED");
}
}
// File: contracts/stores/HashStore.sol
// Copyright 2017 Loopring Technology Limited.
/// @title HashStore
/// @dev This store maintains all hashes for SignedRequest.
contract HashStore is DataStore
{
// wallet => hash => consumed
mapping(address => mapping(bytes32 => bool)) public hashes;
constructor() {}
function verifyAndUpdate(address wallet, bytes32 hash)
external
{
require(!hashes[wallet][hash], "HASH_EXIST");
requireWalletModule(wallet);
hashes[wallet][hash] = true;
}
}
// File: contracts/thirdparty/SafeCast.sol
// Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol
/**
* @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 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 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 < 2**96, "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 < 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 uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits");
return uint40(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 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 >= -2**127 && value < 2**127, "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 >= -2**63 && value < 2**63, "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 >= -2**31 && value < 2**31, "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 >= -2**15 && value < 2**15, "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 >= -2**7 && value < 2**7, "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) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File: contracts/stores/QuotaStore.sol
// Copyright 2017 Loopring Technology Limited.
/// @title QuotaStore
/// @dev This store maintains daily spending quota for each wallet.
/// A rolling daily limit is used.
contract QuotaStore is DataStore
{
using MathUint for uint;
using SafeCast for uint;
uint128 public constant MAX_QUOTA = uint128(-1);
// Optimized to fit into 64 bytes (2 slots)
struct Quota
{
uint128 currentQuota;
uint128 pendingQuota;
uint128 spentAmount;
uint64 spentTimestamp;
uint64 pendingUntil;
}
mapping (address => Quota) public quotas;
event QuotaScheduled(
address wallet,
uint pendingQuota,
uint64 pendingUntil
);
constructor()
DataStore()
{
}
// 0 for newQuota indicates unlimited quota, or daily quota is disabled.
function changeQuota(
address wallet,
uint newQuota,
uint effectiveTime
)
external
onlyWalletModule(wallet)
{
require(newQuota <= MAX_QUOTA, "INVALID_VALUE");
if (newQuota == MAX_QUOTA) {
newQuota = 0;
}
quotas[wallet].currentQuota = currentQuota(wallet).toUint128();
quotas[wallet].pendingQuota = newQuota.toUint128();
quotas[wallet].pendingUntil = effectiveTime.toUint64();
emit QuotaScheduled(
wallet,
newQuota,
quotas[wallet].pendingUntil
);
}
function checkAndAddToSpent(
address wallet,
address token,
uint amount,
PriceOracle priceOracle
)
external
{
Quota memory q = quotas[wallet];
uint available = _availableQuota(q);
if (available != MAX_QUOTA) {
uint value = (token == address(0)) ?
amount :
priceOracle.tokenValue(token, amount);
if (value > 0) {
require(available >= value, "QUOTA_EXCEEDED");
requireWalletModule(wallet);
_addToSpent(wallet, q, value);
}
}
}
function addToSpent(
address wallet,
uint amount
)
external
onlyWalletModule(wallet)
{
_addToSpent(wallet, quotas[wallet], amount);
}
// Returns 0 to indiciate unlimited quota
function currentQuota(address wallet)
public
view
returns (uint)
{
return _currentQuota(quotas[wallet]);
}
// Returns 0 to indiciate unlimited quota
function pendingQuota(address wallet)
public
view
returns (
uint __pendingQuota,
uint __pendingUntil
)
{
return _pendingQuota(quotas[wallet]);
}
function spentQuota(address wallet)
public
view
returns (uint)
{
return _spentQuota(quotas[wallet]);
}
function availableQuota(address wallet)
public
view
returns (uint)
{
return _availableQuota(quotas[wallet]);
}
function hasEnoughQuota(
address wallet,
uint requiredAmount
)
public
view
returns (bool)
{
return _hasEnoughQuota(quotas[wallet], requiredAmount);
}
// Internal
function _currentQuota(Quota memory q)
private
view
returns (uint)
{
return q.pendingUntil <= block.timestamp ? q.pendingQuota : q.currentQuota;
}
function _pendingQuota(Quota memory q)
private
view
returns (
uint __pendingQuota,
uint __pendingUntil
)
{
if (q.pendingUntil > 0 && q.pendingUntil > block.timestamp) {
__pendingQuota = q.pendingQuota;
__pendingUntil = q.pendingUntil;
}
}
function _spentQuota(Quota memory q)
private
view
returns (uint)
{
uint timeSinceLastSpent = block.timestamp.sub(q.spentTimestamp);
if (timeSinceLastSpent < 1 days) {
return uint(q.spentAmount).sub(timeSinceLastSpent.mul(q.spentAmount) / 1 days);
} else {
return 0;
}
}
function _availableQuota(Quota memory q)
private
view
returns (uint)
{
uint quota = _currentQuota(q);
if (quota == 0) {
return MAX_QUOTA;
}
uint spent = _spentQuota(q);
return quota > spent ? quota - spent : 0;
}
function _hasEnoughQuota(
Quota memory q,
uint requiredAmount
)
private
view
returns (bool)
{
return _availableQuota(q) >= requiredAmount;
}
function _addToSpent(
address wallet,
Quota memory q,
uint amount
)
private
{
Quota storage s = quotas[wallet];
s.spentAmount = _spentQuota(q).add(amount).toUint128();
s.spentTimestamp = uint64(block.timestamp);
}
}
// File: contracts/stores/Data.sol
// Copyright 2017 Loopring Technology Limited.
library Data
{
enum GuardianStatus {
REMOVE, // Being removed or removed after validUntil timestamp
ADD // Being added or added after validSince timestamp.
}
// Optimized to fit into 32 bytes (1 slot)
struct Guardian
{
address addr;
uint8 status;
uint64 timestamp; // validSince if status = ADD; validUntil if adding = REMOVE;
}
}
// File: contracts/stores/GuardianStore.sol
// Copyright 2017 Loopring Technology Limited.
/// @title GuardianStore
///
/// @author Daniel Wang - <[email protected]>
abstract contract GuardianStore is DataStore
{
using MathUint for uint;
using SafeCast for uint;
struct Wallet
{
address inheritor;
uint32 inheritWaitingPeriod;
uint64 lastActive; // the latest timestamp the owner is considered to be active
bool locked;
Data.Guardian[] guardians;
mapping (address => uint) guardianIdx;
}
mapping (address => Wallet) public wallets;
constructor() DataStore() {}
function isGuardian(
address wallet,
address addr,
bool includePendingAddition
)
public
view
returns (bool)
{
Data.Guardian memory g = _getGuardian(wallet, addr);
return _isActiveOrPendingAddition(g, includePendingAddition);
}
function guardians(
address wallet,
bool includePendingAddition
)
public
view
returns (Data.Guardian[] memory _guardians)
{
Wallet storage w = wallets[wallet];
_guardians = new Data.Guardian[](w.guardians.length);
uint index = 0;
for (uint i = 0; i < w.guardians.length; i++) {
Data.Guardian memory g = w.guardians[i];
if (_isActiveOrPendingAddition(g, includePendingAddition)) {
_guardians[index] = g;
index++;
}
}
assembly { mstore(_guardians, index) }
}
function numGuardians(
address wallet,
bool includePendingAddition
)
public
view
returns (uint count)
{
Wallet storage w = wallets[wallet];
for (uint i = 0; i < w.guardians.length; i++) {
Data.Guardian memory g = w.guardians[i];
if (_isActiveOrPendingAddition(g, includePendingAddition)) {
count++;
}
}
}
function removeAllGuardians(address wallet)
external
{
Wallet storage w = wallets[wallet];
uint size = w.guardians.length;
if (size == 0) return;
requireWalletModule(wallet);
for (uint i = 0; i < w.guardians.length; i++) {
delete w.guardianIdx[w.guardians[i].addr];
}
delete w.guardians;
}
function cancelPendingGuardians(address wallet)
external
{
bool cancelled = false;
Wallet storage w = wallets[wallet];
for (uint i = 0; i < w.guardians.length; i++) {
Data.Guardian memory g = w.guardians[i];
if (_isPendingAddition(g)) {
w.guardians[i].status = uint8(Data.GuardianStatus.REMOVE);
w.guardians[i].timestamp = 0;
cancelled = true;
}
if (_isPendingRemoval(g)) {
w.guardians[i].status = uint8(Data.GuardianStatus.ADD);
w.guardians[i].timestamp = 0;
cancelled = true;
}
}
if (cancelled) {
requireWalletModule(wallet);
}
_cleanRemovedGuardians(wallet, true);
}
function cleanRemovedGuardians(address wallet)
external
{
_cleanRemovedGuardians(wallet, true);
}
function addGuardian(
address wallet,
address addr,
uint validSince,
bool alwaysOverride
)
external
onlyWalletModule(wallet)
returns (uint)
{
require(validSince >= block.timestamp, "INVALID_VALID_SINCE");
require(addr != address(0), "ZERO_ADDRESS");
Wallet storage w = wallets[wallet];
uint pos = w.guardianIdx[addr];
if(pos == 0) {
// Add the new guardian
Data.Guardian memory g = Data.Guardian(
addr,
uint8(Data.GuardianStatus.ADD),
validSince.toUint64()
);
w.guardians.push(g);
w.guardianIdx[addr] = w.guardians.length;
_cleanRemovedGuardians(wallet, false);
return validSince;
}
Data.Guardian memory g = w.guardians[pos - 1];
if (_isRemoved(g)) {
w.guardians[pos - 1].status = uint8(Data.GuardianStatus.ADD);
w.guardians[pos - 1].timestamp = validSince.toUint64();
return validSince;
}
if (_isPendingRemoval(g)) {
w.guardians[pos - 1].status = uint8(Data.GuardianStatus.ADD);
w.guardians[pos - 1].timestamp = 0;
return 0;
}
if (_isPendingAddition(g)) {
if (!alwaysOverride) return g.timestamp;
w.guardians[pos - 1].timestamp = validSince.toUint64();
return validSince;
}
require(_isAdded(g), "UNEXPECTED_RESULT");
return 0;
}
function removeGuardian(
address wallet,
address addr,
uint validUntil,
bool alwaysOverride
)
external
onlyWalletModule(wallet)
returns (uint)
{
require(validUntil >= block.timestamp, "INVALID_VALID_UNTIL");
require(addr != address(0), "ZERO_ADDRESS");
Wallet storage w = wallets[wallet];
uint pos = w.guardianIdx[addr];
require(pos > 0, "GUARDIAN_NOT_EXISTS");
Data.Guardian memory g = w.guardians[pos - 1];
if (_isAdded(g)) {
w.guardians[pos - 1].status = uint8(Data.GuardianStatus.REMOVE);
w.guardians[pos - 1].timestamp = validUntil.toUint64();
return validUntil;
}
if (_isPendingAddition(g)) {
w.guardians[pos - 1].status = uint8(Data.GuardianStatus.REMOVE);
w.guardians[pos - 1].timestamp = 0;
return 0;
}
if (_isPendingRemoval(g)) {
if (!alwaysOverride) return g.timestamp;
w.guardians[pos - 1].timestamp = validUntil.toUint64();
return validUntil;
}
require(_isRemoved(g), "UNEXPECTED_RESULT");
return 0;
}
// ---- internal functions ---
function _getGuardian(
address wallet,
address addr
)
private
view
returns (Data.Guardian memory)
{
Wallet storage w = wallets[wallet];
uint pos = w.guardianIdx[addr];
if (pos > 0) {
return w.guardians[pos - 1];
}
}
function _isAdded(Data.Guardian memory guardian)
private
view
returns (bool)
{
return guardian.status == uint8(Data.GuardianStatus.ADD) &&
guardian.timestamp <= block.timestamp;
}
function _isPendingAddition(Data.Guardian memory guardian)
private
view
returns (bool)
{
return guardian.status == uint8(Data.GuardianStatus.ADD) &&
guardian.timestamp > block.timestamp;
}
function _isRemoved(Data.Guardian memory guardian)
private
view
returns (bool)
{
return guardian.status == uint8(Data.GuardianStatus.REMOVE) &&
guardian.timestamp <= block.timestamp;
}
function _isPendingRemoval(Data.Guardian memory guardian)
private
view
returns (bool)
{
return guardian.status == uint8(Data.GuardianStatus.REMOVE) &&
guardian.timestamp > block.timestamp;
}
function _isActive(Data.Guardian memory guardian)
private
view
returns (bool)
{
return _isAdded(guardian) || _isPendingRemoval(guardian);
}
function _isActiveOrPendingAddition(
Data.Guardian memory guardian,
bool includePendingAddition
)
private
view
returns (bool)
{
return _isActive(guardian) || includePendingAddition && _isPendingAddition(guardian);
}
function _cleanRemovedGuardians(
address wallet,
bool force
)
private
{
Wallet storage w = wallets[wallet];
uint count = w.guardians.length;
if (!force && count < 10) return;
for (int i = int(count) - 1; i >= 0; i--) {
Data.Guardian memory g = w.guardians[uint(i)];
if (_isRemoved(g)) {
Data.Guardian memory lastGuardian = w.guardians[w.guardians.length - 1];
if (g.addr != lastGuardian.addr) {
w.guardians[uint(i)] = lastGuardian;
w.guardianIdx[lastGuardian.addr] = uint(i) + 1;
}
w.guardians.pop();
delete w.guardianIdx[g.addr];
}
}
}
}
// File: contracts/stores/SecurityStore.sol
// Copyright 2017 Loopring Technology Limited.
/// @title SecurityStore
///
/// @author Daniel Wang - <[email protected]>
contract SecurityStore is GuardianStore
{
using MathUint for uint;
using SafeCast for uint;
constructor() GuardianStore() {}
function setLock(
address wallet,
bool locked
)
external
onlyWalletModule(wallet)
{
wallets[wallet].locked = locked;
}
function touchLastActive(address wallet)
external
onlyWalletModule(wallet)
{
wallets[wallet].lastActive = uint64(block.timestamp);
}
function touchLastActiveWhenRequired(
address wallet,
uint minInternval
)
external
{
if (wallets[wallet].inheritor != address(0) &&
block.timestamp > lastActive(wallet) + minInternval) {
requireWalletModule(wallet);
wallets[wallet].lastActive = uint64(block.timestamp);
}
}
function setInheritor(
address wallet,
address who,
uint32 _inheritWaitingPeriod
)
external
onlyWalletModule(wallet)
{
wallets[wallet].inheritor = who;
wallets[wallet].inheritWaitingPeriod = _inheritWaitingPeriod;
wallets[wallet].lastActive = uint64(block.timestamp);
}
function isLocked(address wallet)
public
view
returns (bool)
{
return wallets[wallet].locked;
}
function lastActive(address wallet)
public
view
returns (uint)
{
return wallets[wallet].lastActive;
}
function inheritor(address wallet)
public
view
returns (
address _who,
uint _effectiveTimestamp
)
{
address _inheritor = wallets[wallet].inheritor;
if (_inheritor == address(0)) {
return (address(0), 0);
}
uint32 _inheritWaitingPeriod = wallets[wallet].inheritWaitingPeriod;
if (_inheritWaitingPeriod == 0) {
return (address(0), 0);
}
uint64 _lastActive = wallets[wallet].lastActive;
if (_lastActive == 0) {
_lastActive = uint64(block.timestamp);
}
_who = _inheritor;
_effectiveTimestamp = _lastActive + _inheritWaitingPeriod;
}
}
// File: contracts/lib/AddressSet.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AddressSet
/// @author Daniel Wang - <[email protected]>
contract AddressSet
{
struct Set
{
address[] addresses;
mapping (address => uint) positions;
uint count;
}
mapping (bytes32 => Set) private sets;
function addAddressToSet(
bytes32 key,
address addr,
bool maintainList
) internal
{
Set storage set = sets[key];
require(set.positions[addr] == 0, "ALREADY_IN_SET");
if (maintainList) {
require(set.addresses.length == set.count, "PREVIOUSLY_NOT_MAINTAILED");
set.addresses.push(addr);
} else {
require(set.addresses.length == 0, "MUST_MAINTAIN");
}
set.count += 1;
set.positions[addr] = set.count;
}
function removeAddressFromSet(
bytes32 key,
address addr
)
internal
{
Set storage set = sets[key];
uint pos = set.positions[addr];
require(pos != 0, "NOT_IN_SET");
delete set.positions[addr];
set.count -= 1;
if (set.addresses.length > 0) {
address lastAddr = set.addresses[set.count];
if (lastAddr != addr) {
set.addresses[pos - 1] = lastAddr;
set.positions[lastAddr] = pos;
}
set.addresses.pop();
}
}
function removeSet(bytes32 key)
internal
{
delete sets[key];
}
function isAddressInSet(
bytes32 key,
address addr
)
internal
view
returns (bool)
{
return sets[key].positions[addr] != 0;
}
function numAddressesInSet(bytes32 key)
internal
view
returns (uint)
{
Set storage set = sets[key];
return set.count;
}
function addressesInSet(bytes32 key)
internal
view
returns (address[] memory)
{
Set storage set = sets[key];
require(set.count == set.addresses.length, "NOT_MAINTAINED");
return sets[key].addresses;
}
}
// File: contracts/lib/OwnerManagable.sol
// Copyright 2017 Loopring Technology Limited.
contract OwnerManagable is Claimable, AddressSet
{
bytes32 internal constant MANAGER = keccak256("__MANAGED__");
event ManagerAdded (address indexed manager);
event ManagerRemoved(address indexed manager);
modifier onlyManager
{
require(isManager(msg.sender), "NOT_MANAGER");
_;
}
modifier onlyOwnerOrManager
{
require(msg.sender == owner || isManager(msg.sender), "NOT_OWNER_OR_MANAGER");
_;
}
constructor() Claimable() {}
/// @dev Gets the managers.
/// @return The list of managers.
function managers()
public
view
returns (address[] memory)
{
return addressesInSet(MANAGER);
}
/// @dev Gets the number of managers.
/// @return The numer of managers.
function numManagers()
public
view
returns (uint)
{
return numAddressesInSet(MANAGER);
}
/// @dev Checks if an address is a manger.
/// @param addr The address to check.
/// @return True if the address is a manager, False otherwise.
function isManager(address addr)
public
view
returns (bool)
{
return isAddressInSet(MANAGER, addr);
}
/// @dev Adds a new manager.
/// @param manager The new address to add.
function addManager(address manager)
public
onlyOwner
{
addManagerInternal(manager);
}
/// @dev Removes a manager.
/// @param manager The manager to remove.
function removeManager(address manager)
public
onlyOwner
{
removeAddressFromSet(MANAGER, manager);
emit ManagerRemoved(manager);
}
function addManagerInternal(address manager)
internal
{
addAddressToSet(MANAGER, manager, true);
emit ManagerAdded(manager);
}
}
// File: contracts/stores/WhitelistStore.sol
// Copyright 2017 Loopring Technology Limited.
/// @title WhitelistStore
/// @dev This store maintains a wallet's whitelisted addresses.
contract WhitelistStore is DataStore, AddressSet, OwnerManagable
{
bytes32 internal constant DAPPS = keccak256("__DAPPS__");
// wallet => whitelisted_addr => effective_since
mapping(address => mapping(address => uint)) public effectiveTimeMap;
event Whitelisted(
address wallet,
address addr,
bool whitelisted,
uint effectiveTime
);
event DappWhitelisted(
address addr,
bool whitelisted
);
constructor() DataStore() {}
function addToWhitelist(
address wallet,
address addr,
uint effectiveTime
)
external
onlyWalletModule(wallet)
{
addAddressToSet(_walletKey(wallet), addr, true);
uint effective = effectiveTime >= block.timestamp ? effectiveTime : block.timestamp;
effectiveTimeMap[wallet][addr] = effective;
emit Whitelisted(wallet, addr, true, effective);
}
function removeFromWhitelist(
address wallet,
address addr
)
external
onlyWalletModule(wallet)
{
removeAddressFromSet(_walletKey(wallet), addr);
delete effectiveTimeMap[wallet][addr];
emit Whitelisted(wallet, addr, false, 0);
}
function addDapp(address addr)
external
onlyManager
{
addAddressToSet(DAPPS, addr, true);
emit DappWhitelisted(addr, true);
}
function removeDapp(address addr)
external
onlyManager
{
removeAddressFromSet(DAPPS, addr);
emit DappWhitelisted(addr, false);
}
function whitelist(address wallet)
public
view
returns (
address[] memory addresses,
uint[] memory effectiveTimes
)
{
addresses = addressesInSet(_walletKey(wallet));
effectiveTimes = new uint[](addresses.length);
for (uint i = 0; i < addresses.length; i++) {
effectiveTimes[i] = effectiveTimeMap[wallet][addresses[i]];
}
}
function isWhitelisted(
address wallet,
address addr
)
public
view
returns (
bool isWhitelistedAndEffective,
uint effectiveTime
)
{
effectiveTime = effectiveTimeMap[wallet][addr];
isWhitelistedAndEffective = effectiveTime > 0 && effectiveTime <= block.timestamp;
}
function whitelistSize(address wallet)
public
view
returns (uint)
{
return numAddressesInSet(_walletKey(wallet));
}
function dapps()
public
view
returns (
address[] memory addresses
)
{
return addressesInSet(DAPPS);
}
function isDapp(
address addr
)
public
view
returns (bool)
{
return isAddressInSet(DAPPS, addr);
}
function numDapps()
public
view
returns (uint)
{
return numAddressesInSet(DAPPS);
}
function isDappOrWhitelisted(
address wallet,
address addr
)
public
view
returns (bool res)
{
(res,) = isWhitelisted(wallet, addr);
return res || isAddressInSet(DAPPS, addr);
}
function _walletKey(address addr)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("__WHITELIST__", addr));
}
}
// File: contracts/thirdparty/strings.sol
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
/* solium-disable */
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (uint256(self) & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (uint256(self) & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (uint256(self) & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (uint256(self) & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (uint256(self) & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to kblock.timestamp whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(uint i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
// File: contracts/thirdparty/ens/ENS.sol
// Taken from Argent's code base - https://github.com/argentlabs/argent-contracts/blob/develop/contracts/ens/ENS.sol
// with few modifications.
/**
* ENS Registry interface.
*/
interface ENSRegistry {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external;
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
}
/**
* ENS Resolver interface.
*/
abstract contract ENSResolver {
function addr(bytes32 _node) public view virtual returns (address);
function setAddr(bytes32 _node, address _addr) public virtual;
function name(bytes32 _node) public view virtual returns (string memory);
function setName(bytes32 _node, string memory _name) public virtual;
}
/**
* ENS Reverse Registrar interface.
*/
abstract contract ENSReverseRegistrar {
function claim(address _owner) public virtual returns (bytes32 _node);
function claimWithResolver(address _owner, address _resolver) public virtual returns (bytes32);
function setName(string memory _name) public virtual returns (bytes32);
function node(address _addr) public view virtual returns (bytes32);
}
// File: contracts/thirdparty/ens/ENSConsumer.sol
// Taken from Argent's code base - https://github.com/argentlabs/argent-contracts/blob/develop/contracts/ens/ENSConsumer.sol
// with few modifications.
/**
* @title ENSConsumer
* @dev Helper contract to resolve ENS names.
* @author Julien Niset - <[email protected]>
*/
contract ENSConsumer {
using strings for *;
// namehash('addr.reverse')
bytes32 public constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
// the address of the ENS registry
address immutable ensRegistry;
/**
* @dev No address should be provided when deploying on Mainnet to avoid storage cost. The
* contract will use the hardcoded value.
*/
constructor(address _ensRegistry) {
ensRegistry = _ensRegistry;
}
/**
* @dev Resolves an ENS name to an address.
* @param _node The namehash of the ENS name.
*/
function resolveEns(bytes32 _node) public view returns (address) {
address resolver = getENSRegistry().resolver(_node);
return ENSResolver(resolver).addr(_node);
}
/**
* @dev Gets the official ENS registry.
*/
function getENSRegistry() public view returns (ENSRegistry) {
return ENSRegistry(ensRegistry);
}
/**
* @dev Gets the official ENS reverse registrar.
*/
function getENSReverseRegistrar() public view returns (ENSReverseRegistrar) {
return ENSReverseRegistrar(getENSRegistry().owner(ADDR_REVERSE_NODE));
}
}
// File: contracts/thirdparty/ens/BaseENSManager.sol
// Taken from Argent's code base - https://github.com/argentlabs/argent-contracts/blob/develop/contracts/ens/ArgentENSManager.sol
// with few modifications.
/**
* @dev Interface for an ENS Mananger.
*/
interface IENSManager {
function changeRootnodeOwner(address _newOwner) external;
function isAvailable(bytes32 _subnode) external view returns (bool);
function resolveName(address _wallet) external view returns (string memory);
function register(
address _wallet,
address _owner,
string calldata _label,
bytes calldata _approval
) external;
}
/**
* @title BaseENSManager
* @dev Implementation of an ENS manager that orchestrates the complete
* registration of subdomains for a single root (e.g. argent.eth).
* The contract defines a manager role who is the only role that can trigger the registration of
* a new subdomain.
* @author Julien Niset - <[email protected]>
*/
contract BaseENSManager is IENSManager, OwnerManagable, ENSConsumer {
using strings for *;
using BytesUtil for bytes;
using MathUint for uint;
// The managed root name
string public rootName;
// The managed root node
bytes32 public immutable rootNode;
// The address of the ENS resolver
address public ensResolver;
// *************** Events *************************** //
event RootnodeOwnerChange(bytes32 indexed _rootnode, address indexed _newOwner);
event ENSResolverChanged(address addr);
event Registered(address indexed _wallet, address _owner, string _ens);
event Unregistered(string _ens);
// *************** Constructor ********************** //
/**
* @dev Constructor that sets the ENS root name and root node to manage.
* @param _rootName The root name (e.g. argentx.eth).
* @param _rootNode The node of the root name (e.g. namehash(argentx.eth)).
*/
constructor(string memory _rootName, bytes32 _rootNode, address _ensRegistry, address _ensResolver)
ENSConsumer(_ensRegistry)
{
rootName = _rootName;
rootNode = _rootNode;
ensResolver = _ensResolver;
}
// *************** External Functions ********************* //
/**
* @dev This function must be called when the ENS Manager contract is replaced
* and the address of the new Manager should be provided.
* @param _newOwner The address of the new ENS manager that will manage the root node.
*/
function changeRootnodeOwner(address _newOwner) external override onlyOwner {
getENSRegistry().setOwner(rootNode, _newOwner);
emit RootnodeOwnerChange(rootNode, _newOwner);
}
/**
* @dev Lets the owner change the address of the ENS resolver contract.
* @param _ensResolver The address of the ENS resolver contract.
*/
function changeENSResolver(address _ensResolver) external onlyOwner {
require(_ensResolver != address(0), "WF: address cannot be null");
ensResolver = _ensResolver;
emit ENSResolverChanged(_ensResolver);
}
/**
* @dev Lets the manager assign an ENS subdomain of the root node to a target address.
* Registers both the forward and reverse ENS.
* @param _wallet The wallet which owns the subdomain.
* @param _owner The wallet's owner.
* @param _label The subdomain label.
* @param _approval The signature of _wallet, _owner and _label by a manager.
*/
function register(
address _wallet,
address _owner,
string calldata _label,
bytes calldata _approval
)
external
override
onlyManager
{
verifyApproval(_wallet, _owner, _label, _approval);
ENSRegistry _ensRegistry = getENSRegistry();
ENSResolver _ensResolver = ENSResolver(ensResolver);
bytes32 labelNode = keccak256(abi.encodePacked(_label));
bytes32 node = keccak256(abi.encodePacked(rootNode, labelNode));
address currentOwner = _ensRegistry.owner(node);
require(currentOwner == address(0), "AEM: _label is alrealdy owned");
// Forward ENS
_ensRegistry.setSubnodeOwner(rootNode, labelNode, address(this));
_ensRegistry.setResolver(node, address(_ensResolver));
_ensRegistry.setOwner(node, _wallet);
_ensResolver.setAddr(node, _wallet);
// Reverse ENS
strings.slice[] memory parts = new strings.slice[](2);
parts[0] = _label.toSlice();
parts[1] = rootName.toSlice();
string memory name = ".".toSlice().join(parts);
bytes32 reverseNode = getENSReverseRegistrar().node(_wallet);
_ensResolver.setName(reverseNode, name);
emit Registered(_wallet, _owner, name);
}
// *************** Public Functions ********************* //
/**
* @dev Resolves an address to an ENS name
* @param _wallet The ENS owner address
*/
function resolveName(address _wallet) public view override returns (string memory) {
bytes32 reverseNode = getENSReverseRegistrar().node(_wallet);
return ENSResolver(ensResolver).name(reverseNode);
}
/**
* @dev Returns true is a given subnode is available.
* @param _subnode The target subnode.
* @return true if the subnode is available.
*/
function isAvailable(bytes32 _subnode) public view override returns (bool) {
bytes32 node = keccak256(abi.encodePacked(rootNode, _subnode));
address currentOwner = getENSRegistry().owner(node);
if(currentOwner == address(0)) {
return true;
}
return false;
}
function verifyApproval(
address _wallet,
address _owner,
string calldata _label,
bytes calldata _approval
)
internal
view
{
bytes32 messageHash = keccak256(
abi.encodePacked(
_wallet,
_owner,
_label
)
);
bytes32 hash = keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
messageHash
)
);
address signer = SignatureUtil.recoverECDSASigner(hash, _approval);
require(isManager(signer), "UNAUTHORIZED");
}
}
// File: contracts/modules/ControllerImpl.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ControllerImpl
/// @dev Basic implementation of a Controller.
///
/// @author Daniel Wang - <[email protected]>
contract ControllerImpl is Claimable, Controller
{
HashStore public immutable hashStore;
QuotaStore public immutable quotaStore;
SecurityStore public immutable securityStore;
WhitelistStore public immutable whitelistStore;
ModuleRegistry public immutable override moduleRegistry;
address public override walletFactory;
address public immutable feeCollector;
BaseENSManager public immutable ensManager;
PriceOracle public priceOracle;
event AddressChanged(
string name,
address addr
);
constructor(
HashStore _hashStore,
QuotaStore _quotaStore,
SecurityStore _securityStore,
WhitelistStore _whitelistStore,
ModuleRegistry _moduleRegistry,
address _feeCollector,
BaseENSManager _ensManager,
PriceOracle _priceOracle
)
{
hashStore = _hashStore;
quotaStore = _quotaStore;
securityStore = _securityStore;
whitelistStore = _whitelistStore;
moduleRegistry = _moduleRegistry;
require(_feeCollector != address(0), "ZERO_ADDRESS");
feeCollector = _feeCollector;
ensManager = _ensManager;
priceOracle = _priceOracle;
}
function initWalletFactory(address _walletFactory)
external
onlyOwner
{
require(walletFactory == address(0), "INITIALIZED_ALREADY");
require(_walletFactory != address(0), "ZERO_ADDRESS");
walletFactory = _walletFactory;
emit AddressChanged("WalletFactory", walletFactory);
}
function setPriceOracle(PriceOracle _priceOracle)
external
onlyOwner
{
priceOracle = _priceOracle;
emit AddressChanged("PriceOracle", address(priceOracle));
}
}
// File: contracts/modules/base/BaseModule.sol
// Copyright 2017 Loopring Technology Limited.
/// @title BaseModule
/// @dev This contract implements some common functions that are likely
/// be useful for all modules.
///
/// @author Daniel Wang - <[email protected]>
abstract contract BaseModule is Module
{
using MathUint for uint;
using AddressUtil for address;
event Activated (address wallet);
event Deactivated (address wallet);
ModuleRegistry public immutable moduleRegistry;
SecurityStore public immutable securityStore;
WhitelistStore public immutable whitelistStore;
QuotaStore public immutable quotaStore;
HashStore public immutable hashStore;
address public immutable walletFactory;
PriceOracle public immutable priceOracle;
address public immutable feeCollector;
function logicalSender()
internal
view
virtual
returns (address payable)
{
return msg.sender;
}
modifier onlyWalletOwner(address wallet, address addr)
virtual
{
require(Wallet(wallet).owner() == addr, "NOT_WALLET_OWNER");
_;
}
modifier notWalletOwner(address wallet, address addr)
virtual
{
require(Wallet(wallet).owner() != addr, "IS_WALLET_OWNER");
_;
}
modifier eligibleWalletOwner(address addr)
{
require(addr != address(0) && !addr.isContract(), "INVALID_OWNER");
_;
}
constructor(ControllerImpl _controller)
{
moduleRegistry = _controller.moduleRegistry();
securityStore = _controller.securityStore();
whitelistStore = _controller.whitelistStore();
quotaStore = _controller.quotaStore();
hashStore = _controller.hashStore();
walletFactory = _controller.walletFactory();
priceOracle = _controller.priceOracle();
feeCollector = _controller.feeCollector();
}
/// @dev This method will cause an re-entry to the same module contract.
function activate()
external
override
virtual
{
address wallet = logicalSender();
bindMethods(wallet);
emit Activated(wallet);
}
/// @dev This method will cause an re-entry to the same module contract.
function deactivate()
external
override
virtual
{
address wallet = logicalSender();
unbindMethods(wallet);
emit Deactivated(wallet);
}
///.@dev Gets the list of methods for binding to wallets.
/// Sub-contracts should override this method to provide methods for
/// wallet binding.
/// @return methods A list of method selectors for binding to the wallet
/// when this module is activated for the wallet.
function bindableMethods()
public
pure
virtual
returns (bytes4[] memory methods)
{
}
// ===== internal & private methods =====
/// @dev Binds all methods to the given wallet.
function bindMethods(address wallet)
internal
{
Wallet w = Wallet(wallet);
bytes4[] memory methods = bindableMethods();
for (uint i = 0; i < methods.length; i++) {
w.bindMethod(methods[i], address(this));
}
}
/// @dev Unbinds all methods from the given wallet.
function unbindMethods(address wallet)
internal
{
Wallet w = Wallet(wallet);
bytes4[] memory methods = bindableMethods();
for (uint i = 0; i < methods.length; i++) {
w.bindMethod(methods[i], address(0));
}
}
function transactCall(
address wallet,
address to,
uint value,
bytes memory data
)
internal
returns (bytes memory)
{
return Wallet(wallet).transact(uint8(1), to, value, data);
}
// Special case for transactCall to support transfers on "bad" ERC20 tokens
function transactTokenTransfer(
address wallet,
address token,
address to,
uint amount
)
internal
{
if (token == address(0)) {
transactCall(wallet, to, amount, "");
return;
}
bytes memory txData = abi.encodeWithSelector(
ERC20.transfer.selector,
to,
amount
);
bytes memory returnData = transactCall(wallet, token, 0, txData);
// `transactCall` will revert if the call was unsuccessful.
// The only extra check we have to do is verify if the return value (if there is any) is correct.
bool success = returnData.length == 0 ? true : abi.decode(returnData, (bool));
require(success, "ERC20_TRANSFER_FAILED");
}
// Special case for transactCall to support approvals on "bad" ERC20 tokens
function transactTokenApprove(
address wallet,
address token,
address spender,
uint amount
)
internal
{
require(token != address(0), "INVALID_TOKEN");
bytes memory txData = abi.encodeWithSelector(
ERC20.approve.selector,
spender,
amount
);
bytes memory returnData = transactCall(wallet, token, 0, txData);
// `transactCall` will revert if the call was unsuccessful.
// The only extra check we have to do is verify if the return value (if there is any) is correct.
bool success = returnData.length == 0 ? true : abi.decode(returnData, (bool));
require(success, "ERC20_APPROVE_FAILED");
}
function transactDelegateCall(
address wallet,
address to,
uint value,
bytes calldata data
)
internal
returns (bytes memory)
{
return Wallet(wallet).transact(uint8(2), to, value, data);
}
function transactStaticCall(
address wallet,
address to,
bytes calldata data
)
internal
returns (bytes memory)
{
return Wallet(wallet).transact(uint8(3), to, 0, data);
}
function reimburseGasFee(
address wallet,
address recipient,
address gasToken,
uint gasPrice,
uint gasAmount
)
internal
{
uint gasCost = gasAmount.mul(gasPrice);
quotaStore.checkAndAddToSpent(
wallet,
gasToken,
gasAmount,
priceOracle
);
transactTokenTransfer(wallet, gasToken, recipient, gasCost);
}
}
// File: contracts/modules/base/MetaTxAware.sol
// Copyright 2017 Loopring Technology Limited.
/// @title MetaTxAware
/// @author Daniel Wang - <[email protected]>
///
/// The design of this contract is inspired by GSN's contract codebase:
/// https://github.com/opengsn/gsn/contracts
///
/// @dev Inherit this abstract contract to make a module meta-transaction
/// aware. `msgSender()` shall be used to replace `msg.sender` for
/// verifying permissions.
abstract contract MetaTxAware
{
using AddressUtil for address;
using BytesUtil for bytes;
address public immutable metaTxForwarder;
constructor(address _metaTxForwarder)
{
metaTxForwarder = _metaTxForwarder;
}
modifier txAwareHashNotAllowed()
{
require(txAwareHash() == 0, "INVALID_TX_AWARE_HASH");
_;
}
/// @dev Return's the function's logicial message sender. This method should be
// used to replace `msg.sender` for all meta-tx enabled functions.
function msgSender()
internal
view
returns (address payable)
{
if (msg.data.length >= 56 && msg.sender == metaTxForwarder) {
return msg.data.toAddress(msg.data.length - 52).toPayable();
} else {
return msg.sender;
}
}
function txAwareHash()
internal
view
returns (bytes32)
{
if (msg.data.length >= 56 && msg.sender == metaTxForwarder) {
return msg.data.toBytes32(msg.data.length - 32);
} else {
return 0;
}
}
}
// File: contracts/modules/base/MetaTxModule.sol
// Copyright 2017 Loopring Technology Limited.
/// @title MetaTxModule
/// @dev Base contract for all modules that support meta-transactions.
///
/// @author Daniel Wang - <[email protected]>
///
/// The design of this contract is inspired by GSN's contract codebase:
/// https://github.com/opengsn/gsn/contracts
abstract contract MetaTxModule is MetaTxAware, BaseModule
{
using SignatureUtil for bytes32;
constructor(
ControllerImpl _controller,
address _metaTxForwarder
)
MetaTxAware(_metaTxForwarder)
BaseModule(_controller)
{
}
function logicalSender()
internal
view
virtual
override
returns (address payable)
{
return msgSender();
}
}
// File: contracts/modules/security/GuardianUtils.sol
// Copyright 2017 Loopring Technology Limited.
/// @title GuardianUtils
/// @author Brecht Devos - <[email protected]>
library GuardianUtils
{
enum SigRequirement
{
MAJORITY_OWNER_NOT_ALLOWED,
MAJORITY_OWNER_ALLOWED,
MAJORITY_OWNER_REQUIRED,
OWNER_OR_ANY_GUARDIAN,
ANY_GUARDIAN
}
function requireMajority(
SecurityStore securityStore,
address wallet,
address[] memory signers,
SigRequirement requirement
)
internal
view
returns (bool)
{
// We always need at least one signer
if (signers.length == 0) {
return false;
}
// Calculate total group sizes
Data.Guardian[] memory allGuardians = securityStore.guardians(wallet, false);
require(allGuardians.length > 0, "NO_GUARDIANS");
address lastSigner;
bool walletOwnerSigned = false;
address owner = Wallet(wallet).owner();
for (uint i = 0; i < signers.length; i++) {
// Check for duplicates
require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER");
lastSigner = signers[i];
if (signers[i] == owner) {
walletOwnerSigned = true;
} else {
require(_isWalletGuardian(allGuardians, signers[i]), "SIGNER_NOT_GUARDIAN");
}
}
if (requirement == SigRequirement.OWNER_OR_ANY_GUARDIAN) {
return signers.length == 1;
} else if (requirement == SigRequirement.ANY_GUARDIAN) {
require(!walletOwnerSigned, "WALLET_OWNER_SIGNATURE_NOT_ALLOWED");
return signers.length == 1;
}
// Check owner requirements
if (requirement == SigRequirement.MAJORITY_OWNER_REQUIRED) {
require(walletOwnerSigned, "WALLET_OWNER_SIGNATURE_REQUIRED");
} else if (requirement == SigRequirement.MAJORITY_OWNER_NOT_ALLOWED) {
require(!walletOwnerSigned, "WALLET_OWNER_SIGNATURE_NOT_ALLOWED");
}
uint numExtendedSigners = allGuardians.length;
if (walletOwnerSigned) {
numExtendedSigners += 1;
require(signers.length > 1, "NO_GUARDIAN_SIGNED_BESIDES_OWNER");
}
return _hasMajority(signers.length, numExtendedSigners);
}
function _isWalletGuardian(
Data.Guardian[] memory allGuardians,
address signer
)
private
pure
returns (bool)
{
for (uint i = 0; i < allGuardians.length; i++) {
if (allGuardians[i].addr == signer) {
return true;
}
}
return false;
}
function _hasMajority(
uint signed,
uint total
)
private
pure
returns (bool)
{
return total > 0 && signed >= (total >> 1) + 1;
}
}
// File: contracts/modules/security/SignedRequest.sol
// Copyright 2017 Loopring Technology Limited.
/// @title SignedRequest
/// @dev Utility library for better handling of signed wallet requests.
/// This library must be deployed and linked to other modules.
///
/// @author Daniel Wang - <[email protected]>
library SignedRequest {
using SignatureUtil for bytes32;
struct Request {
address[] signers;
bytes[] signatures;
uint validUntil;
address wallet;
}
function verifyRequest(
HashStore hashStore,
SecurityStore securityStore,
bytes32 domainSeperator,
bytes32 txAwareHash,
GuardianUtils.SigRequirement sigRequirement,
Request memory request,
bytes memory encodedRequest
)
public
{
require(block.timestamp <= request.validUntil, "EXPIRED_SIGNED_REQUEST");
bytes32 _txAwareHash = EIP712.hashPacked(domainSeperator, encodedRequest);
// If txAwareHash from the meta-transaction is non-zero,
// we must verify it matches the hash signed by the respective signers.
require(
txAwareHash == 0 || txAwareHash == _txAwareHash,
"TX_INNER_HASH_MISMATCH"
);
// Save hash to prevent replay attacks
hashStore.verifyAndUpdate(request.wallet, _txAwareHash);
require(
_txAwareHash.verifySignatures(request.signers, request.signatures),
"INVALID_SIGNATURES"
);
require(
GuardianUtils.requireMajority(
securityStore,
request.wallet,
request.signers,
sigRequirement
),
"PERMISSION_DENIED"
);
}
}
// File: contracts/modules/security/SecurityModule.sol
// Copyright 2017 Loopring Technology Limited.
/// @title SecurityStore
///
/// @author Daniel Wang - <[email protected]>
abstract contract SecurityModule is MetaTxModule
{
// The minimal number of guardians for recovery and locking.
uint public constant TOUCH_GRACE_PERIOD = 30 days;
event WalletLocked(
address indexed wallet,
address by,
bool locked
);
constructor(
ControllerImpl _controller,
address _metaTxForwarder
)
MetaTxModule(_controller, _metaTxForwarder)
{
}
modifier onlyFromWalletOrOwnerWhenUnlocked(address wallet)
{
address payable _logicalSender = logicalSender();
// If the wallet's signature verfication passes, the wallet must be unlocked.
require(
_logicalSender == wallet ||
(_logicalSender == Wallet(wallet).owner() && !_isWalletLocked(wallet)),
"NOT_FROM_WALLET_OR_OWNER_OR_WALLET_LOCKED"
);
securityStore.touchLastActiveWhenRequired(wallet, TOUCH_GRACE_PERIOD);
_;
}
modifier onlyWalletGuardian(address wallet, address guardian)
{
require(securityStore.isGuardian(wallet, guardian, false), "NOT_GUARDIAN");
_;
}
modifier notWalletGuardian(address wallet, address guardian)
{
require(!securityStore.isGuardian(wallet, guardian, false), "IS_GUARDIAN");
_;
}
// ----- internal methods -----
function _lockWallet(address wallet, address by, bool locked)
internal
{
securityStore.setLock(wallet, locked);
emit WalletLocked(wallet, by, locked);
}
function _isWalletLocked(address wallet)
internal
view
returns (bool)
{
return securityStore.isLocked(wallet);
}
function _updateQuota(
QuotaStore qs,
address wallet,
address token,
uint amount
)
internal
{
if (amount == 0) return;
if (qs == QuotaStore(0)) return;
qs.checkAndAddToSpent(
wallet,
token,
amount,
priceOracle
);
}
}
// File: contracts/modules/transfers/BaseTransferModule.sol
// Copyright 2017 Loopring Technology Limited.
/// @title BaseTransferModule
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
abstract contract BaseTransferModule is SecurityModule
{
using MathUint for uint;
event Transfered (address wallet, address token, address to, uint amount, bytes logdata);
event Approved (address wallet, address token, address spender, uint amount);
event ContractCalled(address wallet, address to, uint value, bytes data);
function transferInternal(
address wallet,
address token,
address to,
uint amount,
bytes calldata logdata
)
internal
{
transactTokenTransfer(wallet, token, to, amount);
emit Transfered(wallet, token, to, amount, logdata);
}
function approveInternal(
address wallet,
address token,
address spender,
uint amount
)
internal
returns (uint additionalAllowance)
{
// Current allowance
uint allowance = ERC20(token).allowance(wallet, spender);
if (amount != allowance) {
// First reset the approved amount if needed
if (allowance > 0) {
transactTokenApprove(wallet, token, spender, 0);
}
// Now approve the requested amount
transactTokenApprove(wallet, token, spender, amount);
}
// If we increased the allowance, calculate by how much
if (amount > allowance) {
additionalAllowance = amount.sub(allowance);
}
emit Approved(wallet, token, spender, amount);
}
function callContractInternal(
address wallet,
address to,
uint value,
bytes calldata txData
)
internal
virtual
returns (bytes memory returnData)
{
// Calls from the wallet to itself are deemed special
// (e.g. this is used for updating the wallet implementation)
// We also disallow calls to module functions directly
// (e.g. this is used for some special wallet <-> module interaction)
require(wallet != to && !Wallet(wallet).hasModule(to), "CALL_DISALLOWED");
// Disallow general calls to token contracts (for tokens that have price data
// so the quota is actually used).
require(priceOracle.tokenValue(to, 1e18) == 0, "CALL_DISALLOWED");
returnData = transactCall(wallet, to, value, txData);
emit ContractCalled(wallet, to, value, txData);
}
function isAddressWhitelisted(address wallet, address to)
internal
view
returns (bool res)
{
(res,) = whitelistStore.isWhitelisted(wallet, to);
}
function isAddressDappOrWhitelisted(address wallet, address to)
internal
view
returns (bool)
{
return whitelistStore.isDappOrWhitelisted(wallet, to);
}
}
// File: contracts/modules/transfers/TransferModule.sol
// Copyright 2017 Loopring Technology Limited.
/// @title TransferModule
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
abstract contract TransferModule is BaseTransferModule
{
using MathUint for uint;
bytes32 public immutable TRANSFER_DOMAIN_SEPERATOR;
uint public constant QUOTA_PENDING_PERIOD = 1 days;
bytes32 public constant CHANGE_DAILY_QUOTE_TYPEHASH = keccak256(
"changeDailyQuota(address wallet,uint256 validUntil,uint256 newQuota)"
);
bytes32 public constant TRANSFER_TOKEN_TYPEHASH = keccak256(
"transferToken(address wallet,uint256 validUntil,address token,address to,uint256 amount,bytes logdata)"
);
bytes32 public constant APPROVE_TOKEN_TYPEHASH = keccak256(
"approveToken(address wallet,uint256 validUntil,address token,address to,uint256 amount)"
);
bytes32 public constant CALL_CONTRACT_TYPEHASH = keccak256(
"callContract(address wallet,uint256 validUntil,address to,uint256 value,bytes data)"
);
bytes32 public constant APPROVE_THEN_CALL_CONTRACT_TYPEHASH = keccak256(
"approveThenCallContract(address wallet,uint256 validUntil,address token,address to,uint256 amount,uint256 value,bytes data)"
);
constructor()
{
TRANSFER_DOMAIN_SEPERATOR = EIP712.hash(
EIP712.Domain("TransferModule", "1.2.0", address(this))
);
}
function changeDailyQuota(
address wallet,
uint newQuota
)
external
txAwareHashNotAllowed()
onlyFromWalletOrOwnerWhenUnlocked(wallet)
{
_changeQuota(wallet, newQuota, QUOTA_PENDING_PERIOD);
}
function changeDailyQuotaWA(
SignedRequest.Request calldata request,
uint newQuota
)
external
{
SignedRequest.verifyRequest(
hashStore,
securityStore,
TRANSFER_DOMAIN_SEPERATOR,
txAwareHash(),
GuardianUtils.SigRequirement.MAJORITY_OWNER_REQUIRED,
request,
abi.encode(
CHANGE_DAILY_QUOTE_TYPEHASH,
request.wallet,
request.validUntil,
newQuota
)
);
_changeQuota(request.wallet, newQuota, 0);
}
function transferToken(
address wallet,
address token,
address to,
uint amount,
bytes calldata logdata,
bool forceUseQuota
)
external
txAwareHashNotAllowed()
onlyFromWalletOrOwnerWhenUnlocked(wallet)
{
if (forceUseQuota || !isAddressWhitelisted(wallet, to)) {
_updateQuota(quotaStore, wallet, token, amount);
}
transferInternal(wallet, token, to, amount, logdata);
}
function transferTokenWA(
SignedRequest.Request calldata request,
address token,
address to,
uint amount,
bytes calldata logdata
)
external
{
SignedRequest.verifyRequest(
hashStore,
securityStore,
TRANSFER_DOMAIN_SEPERATOR,
txAwareHash(),
GuardianUtils.SigRequirement.MAJORITY_OWNER_REQUIRED,
request,
abi.encode(
TRANSFER_TOKEN_TYPEHASH,
request.wallet,
request.validUntil,
token,
to,
amount,
keccak256(logdata)
)
);
transferInternal(request.wallet, token, to, amount, logdata);
}
function callContract(
address wallet,
address to,
uint value,
bytes calldata data,
bool forceUseQuota
)
external
txAwareHashNotAllowed()
onlyFromWalletOrOwnerWhenUnlocked(wallet)
returns (bytes memory returnData)
{
if (forceUseQuota || !isAddressDappOrWhitelisted(wallet, to)) {
_updateQuota(quotaStore, wallet, address(0), value);
}
return callContractInternal(wallet, to, value, data);
}
function callContractWA(
SignedRequest.Request calldata request,
address to,
uint value,
bytes calldata data
)
external
returns (bytes memory returnData)
{
SignedRequest.verifyRequest(
hashStore,
securityStore,
TRANSFER_DOMAIN_SEPERATOR,
txAwareHash(),
GuardianUtils.SigRequirement.MAJORITY_OWNER_REQUIRED,
request,
abi.encode(
CALL_CONTRACT_TYPEHASH,
request.wallet,
request.validUntil,
to,
value,
keccak256(data)
)
);
return callContractInternal(request.wallet, to, value, data);
}
function approveToken(
address wallet,
address token,
address to,
uint amount,
bool forceUseQuota
)
external
txAwareHashNotAllowed()
onlyFromWalletOrOwnerWhenUnlocked(wallet)
{
uint additionalAllowance = approveInternal(wallet, token, to, amount);
if (forceUseQuota || !isAddressDappOrWhitelisted(wallet, to)) {
_updateQuota(quotaStore, wallet, token, additionalAllowance);
}
}
function approveTokenWA(
SignedRequest.Request calldata request,
address token,
address to,
uint amount
)
external
{
SignedRequest.verifyRequest(
hashStore,
securityStore,
TRANSFER_DOMAIN_SEPERATOR,
txAwareHash(),
GuardianUtils.SigRequirement.MAJORITY_OWNER_REQUIRED,
request,
abi.encode(
APPROVE_TOKEN_TYPEHASH,
request.wallet,
request.validUntil,
token,
to,
amount
)
);
approveInternal(request.wallet, token, to, amount);
}
function approveThenCallContract(
address wallet,
address token,
address to,
uint amount,
uint value,
bytes calldata data,
bool forceUseQuota
)
external
txAwareHashNotAllowed()
onlyFromWalletOrOwnerWhenUnlocked(wallet)
returns (bytes memory returnData)
{
uint additionalAllowance = approveInternal(wallet, token, to, amount);
if (forceUseQuota || !isAddressDappOrWhitelisted(wallet, to)) {
_updateQuota(quotaStore, wallet, token, additionalAllowance);
_updateQuota(quotaStore, wallet, address(0), value);
}
return callContractInternal(wallet, to, value, data);
}
function approveThenCallContractWA(
SignedRequest.Request calldata request,
address token,
address to,
uint amount,
uint value,
bytes calldata data
)
external
returns (bytes memory returnData)
{
bytes memory encoded = abi.encode(
APPROVE_THEN_CALL_CONTRACT_TYPEHASH,
request.wallet,
request.validUntil,
token,
to,
amount,
value,
keccak256(data)
);
SignedRequest.verifyRequest(
hashStore,
securityStore,
TRANSFER_DOMAIN_SEPERATOR,
txAwareHash(),
GuardianUtils.SigRequirement.MAJORITY_OWNER_REQUIRED,
request,
encoded
);
approveInternal(request.wallet, token, to, amount);
return callContractInternal(request.wallet, to, value, data);
}
function getDailyQuota(address wallet)
public
view
returns (
uint total, // 0 indicates quota is disabled
uint spent,
uint available
)
{
total = quotaStore.currentQuota(wallet);
spent = quotaStore.spentQuota(wallet);
available = quotaStore.availableQuota(wallet);
}
function _changeQuota(
address wallet,
uint newQuota,
uint pendingPeriod
)
private
{
uint _currentQuota = quotaStore.currentQuota(wallet);
uint _pendingPeriod = pendingPeriod;
if (_currentQuota == 0 || (newQuota > 0 && newQuota <= _currentQuota)) {
_pendingPeriod = 0;
}
quotaStore.changeQuota(wallet, newQuota, block.timestamp.add(_pendingPeriod));
}
}
// File: contracts/modules/transfers/FinalTransferModule.sol
// Copyright 2017 Loopring Technology Limited.
/// @title FinalTransferModule
/// @dev This module combines multiple small modules to
/// minimize the number of modules to reduce gas used
/// by wallet creation.
contract FinalTransferModule is TransferModule
{
ControllerImpl private immutable controller_;
constructor(
ControllerImpl _controller,
address _metaTxForwarder
)
SecurityModule(_controller, _metaTxForwarder)
TransferModule()
{
controller_ = _controller;
}
} | Binds all methods to the given wallet. | function bindMethods(address wallet)
internal
{
Wallet w = Wallet(wallet);
bytes4[] memory methods = bindableMethods();
for (uint i = 0; i < methods.length; i++) {
w.bindMethod(methods[i], address(this));
}
}
| 134,458 |
// SPDX-License-Identifier: ISC
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "./BlockLock.sol";
import "./interfaces/IxALPHA.sol";
import "./interfaces/IxTokenManager.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IALPHAStaking.sol";
import "./interfaces/ISushiswapRouter.sol";
import "./interfaces/IUniswapV3SwapRouter.sol";
import "./interfaces/IStakingProxy.sol";
import "./helpers/StakingFactory.sol";
// solhint-disable-next-line contract-name-camelcase
contract xALPHA is Initializable, ERC20Upgradeable, OwnableUpgradeable, PausableUpgradeable, IxALPHA, BlockLock {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for SafeERC20Upgradeable;
using SafeERC20 for IERC20;
uint256 private constant LIQUIDATION_TIME_PERIOD = 4 weeks;
uint256 private constant INITIAL_SUPPLY_MULTIPLIER = 10;
uint256 private constant STAKING_PROXIES_AMOUNT = 5;
uint256 private constant MAX_UINT = 2**256 - 1;
address private constant ETH_ADDRESS = address(0);
IWETH private weth;
IERC20 private alphaToken;
StakingFactory private stakingFactory;
address private stakingProxyImplementation;
// The total amount staked across all proxies
uint256 public totalStakedBalance;
uint256 public adminActiveTimestamp;
uint256 public withdrawableAlphaFees;
uint256 public emergencyUnbondTimestamp;
uint256 public lastStakeTimestamp;
IxTokenManager private xTokenManager; // xToken manager contract
address private uniswapRouter;
address private sushiswapRouter;
SwapMode private swapMode;
FeeDivisors public feeDivisors;
uint24 public v3AlphaPoolFee;
function initialize(
string calldata _symbol,
IWETH _wethToken,
IERC20 _alphaToken,
address _alphaStaking,
StakingFactory _stakingFactory,
IxTokenManager _xTokenManager,
address _uniswapRouter,
address _sushiswapRouter,
FeeDivisors calldata _feeDivisors
) external override initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained("xALPHA", _symbol);
weth = _wethToken;
alphaToken = _alphaToken;
stakingFactory = _stakingFactory;
xTokenManager = _xTokenManager;
uniswapRouter = _uniswapRouter;
sushiswapRouter = _sushiswapRouter;
updateSwapRouter(SwapMode.UNISWAP_V3);
// Approve WETH and ALPHA for both swap routers
alphaToken.safeApprove(sushiswapRouter, MAX_UINT);
IERC20(address(weth)).safeApprove(sushiswapRouter, MAX_UINT);
alphaToken.safeApprove(uniswapRouter, MAX_UINT);
IERC20(address(weth)).safeApprove(uniswapRouter, MAX_UINT);
v3AlphaPoolFee = 10000;
_setFeeDivisors(_feeDivisors.mintFee, _feeDivisors.burnFee, _feeDivisors.claimFee);
// Initialize the staking proxies
for (uint256 i = 0; i < STAKING_PROXIES_AMOUNT; ++i) {
// Deploy the proxy
stakingFactory.deployProxy();
// Initialize
IStakingProxy(stakingFactory.stakingProxyProxies(i)).initialize(_alphaStaking);
}
}
/* ========================================================================================= */
/* User functions */
/* ========================================================================================= */
/*
* @dev Mint xALPHA using ETH
* @notice Assesses mint fee
* @param minReturn: Min return to pass to Uniswap trade
*
* This function swaps ETH to ALPHA using 1inch.
*/
function mint(uint256 minReturn) external payable override whenNotPaused notLocked(msg.sender) {
require(msg.value > 0, "Must send ETH");
_lock(msg.sender);
// Swap ETH for ALPHA
uint256 alphaAmount = _swapETHforALPHAInternal(msg.value, minReturn);
uint256 fee = _calculateFee(alphaAmount, feeDivisors.mintFee);
_incrementWithdrawableAlphaFees(fee);
return _mintInternal(alphaAmount.sub(fee));
}
/*
* @dev Mint xALPHA using ALPHA
* @notice Assesses mint fee
*
* @param alphaAmount: ALPHA tokens to contribute
*
* The xALPHA contract must be approved to withdraw ALPHA from the
* sender's wallet.
*/
function mintWithToken(uint256 alphaAmount) external override whenNotPaused notLocked(msg.sender) {
require(alphaAmount > 0, "Must send token");
_lock(msg.sender);
alphaToken.safeTransferFrom(msg.sender, address(this), alphaAmount);
uint256 fee = _calculateFee(alphaAmount, feeDivisors.mintFee);
_incrementWithdrawableAlphaFees(fee);
return _mintInternal(alphaAmount.sub(fee));
}
/*
* @dev Perform mint action
* @param _incrementalAlpha: ALPHA tokens to contribute
*
* No safety checks since internal function. After calculating
* the mintAmount based on the current liquidity ratio, it mints
* xALPHA (using ERC20 mint).
*/
function _mintInternal(uint256 _incrementalAlpha) private {
uint256 mintAmount = calculateMintAmount(_incrementalAlpha, totalSupply());
return super._mint(msg.sender, mintAmount);
}
/*
* @dev Calculate mint amount for xALPHA
*
* @param _incrementalAlpha: ALPHA tokens to contribute
* @param totalSupply: total supply of xALPHA tokens to calculate against
*
* @return mintAmount: the amount of xALPHA that will be minted
*
* Calculate the amount of xALPHA that will be minted for a
* proportionate amount of ALPHA. In practice, totalSupply will
* equal the total supply of xALPHA.
*/
function calculateMintAmount(uint256 incrementalAlpha, uint256 totalSupply)
public
view
override
returns (uint256 mintAmount)
{
if (totalSupply == 0) return incrementalAlpha.mul(INITIAL_SUPPLY_MULTIPLIER);
uint256 previousNav = getNav().sub(incrementalAlpha);
mintAmount = incrementalAlpha.mul(totalSupply).div(previousNav);
}
/*
* @dev Burn xALPHA tokens
* @notice Will fail if pro rata balance exceeds available liquidity
* @notice Assesses burn fee
*
* @param tokenAmount: xALPHA tokens to burn
* @param redeemForEth: Redeem for ETH or ALPHA
* @param minReturn: Min return to pass to 1inch trade
*
* Burns the sent amount of xALPHA and calculates the proportionate
* amount of ALPHA. Either sends the ALPHA to the caller or exchanges
* it for ETH.
*/
function burn(
uint256 tokenAmount,
bool redeemForEth,
uint256 minReturn
) external override notLocked(msg.sender) {
require(tokenAmount > 0, "Must send xALPHA");
_lock(msg.sender);
(uint256 stakedBalance, uint256 bufferBalance) = getFundBalances();
uint256 alphaHoldings = stakedBalance.add(bufferBalance);
uint256 proRataAlpha = alphaHoldings.mul(tokenAmount).div(totalSupply());
require(proRataAlpha <= bufferBalance, "Insufficient exit liquidity");
super._burn(msg.sender, tokenAmount);
uint256 fee = _calculateFee(proRataAlpha, feeDivisors.burnFee);
_incrementWithdrawableAlphaFees(fee);
uint256 withdrawAmount = proRataAlpha.sub(fee);
if (redeemForEth) {
uint256 ethAmount = _swapALPHAForETHInternal(withdrawAmount, minReturn);
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call{ value: ethAmount }(new bytes(0));
require(success, "ETH burn transfer failed");
} else {
alphaToken.safeTransfer(msg.sender, withdrawAmount);
}
}
/*
* @inheritdoc ERC20
*/
function transfer(address recipient, uint256 amount) public override notLocked(msg.sender) returns (bool) {
return super.transfer(recipient, amount);
}
/*
* @inheritdoc ERC20
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override notLocked(sender) returns (bool) {
return super.transferFrom(sender, recipient, amount);
}
/*
* @dev Swap ETH for ALPHA
* @notice uses either Sushiswap or Uniswap V3 depending on version
*
* @param ethAmount: amount of ETH to swap
* @param minReturn: Min return to pass to Uniswap trade
*
* @return amount of ALPHA returned in the swap
*
* These swaps always use 'exact input' - they send exactly the amount specified
* in arguments to the swap, and the output amount is calculated.
*/
function _swapETHforALPHAInternal(uint256 ethAmount, uint256 minReturn) private returns (uint256) {
uint256 deadline = MAX_UINT;
if (swapMode == SwapMode.SUSHISWAP) {
// SUSHISWAP
IUniswapV2Router02 routerV2 = IUniswapV2Router02(sushiswapRouter);
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(alphaToken);
uint256[] memory amounts = routerV2.swapExactETHForTokens{ value: ethAmount }(
minReturn,
path,
address(this),
deadline
);
return amounts[1];
} else {
// UNISWAP V3
IUniswapV3SwapRouter routerV3 = IUniswapV3SwapRouter(uniswapRouter);
weth.deposit{ value: ethAmount }();
IUniswapV3SwapRouter.ExactInputSingleParams memory params = IUniswapV3SwapRouter.ExactInputSingleParams({
tokenIn: address(weth),
tokenOut: address(alphaToken),
fee: v3AlphaPoolFee,
recipient: address(this),
deadline: deadline,
amountIn: ethAmount,
amountOutMinimum: minReturn,
sqrtPriceLimitX96: 0
});
uint256 amountOut = routerV3.exactInputSingle(params);
return amountOut;
}
}
/*
* @dev Swap ALPHA for ETH using Uniswap
* @notice uses either Sushiswap or Uniswap V3 depending on version
*
* @param alphaAmount: amount of ALPHA to swap
* @param minReturn: Min return to pass to Uniswap trade
*
* @return amount of ETH returned in the swap
*
* These swaps always use 'exact input' - they send exactly the amount specified
* in arguments to the swap, and the output amount is calculated. The output ETH
* is held in the contract.
*/
function _swapALPHAForETHInternal(uint256 alphaAmount, uint256 minReturn) private returns (uint256) {
uint256 deadline = MAX_UINT;
if (swapMode == SwapMode.SUSHISWAP) {
// SUSHISWAP
IUniswapV2Router02 routerV2 = IUniswapV2Router02(sushiswapRouter);
address[] memory path = new address[](2);
path[0] = address(alphaToken);
path[1] = address(weth);
uint256[] memory amounts = routerV2.swapExactTokensForETH(
alphaAmount,
minReturn,
path,
address(this),
deadline
);
return amounts[1];
} else {
// UNISWAP V3
IUniswapV3SwapRouter routerV3 = IUniswapV3SwapRouter(uniswapRouter);
IUniswapV3SwapRouter.ExactInputSingleParams memory params = IUniswapV3SwapRouter.ExactInputSingleParams({
tokenIn: address(alphaToken),
tokenOut: address(weth),
fee: v3AlphaPoolFee,
recipient: address(this),
deadline: deadline,
amountIn: alphaAmount,
amountOutMinimum: minReturn,
sqrtPriceLimitX96: 0
});
uint256 amountOut = routerV3.exactInputSingle(params);
// Withdraw WETH
weth.withdraw(amountOut);
return amountOut;
}
}
/* ========================================================================================= */
/* Management */
/* ========================================================================================= */
/*
* @dev Get NAV of the xALPHA contract
* @notice Combination of staked balance held in staking contract
* and unstaked buffer balance held in xALPHA contract. Also
* includes stake currently being unbonded (as part of staked balance)
*
* @return Total NAV in ALPHA
*
*/
function getNav() public view override returns (uint256) {
return totalStakedBalance.add(getBufferBalance());
}
/*
* @dev Get buffer balance of the xALPHA contract
*
* @return Total unstaked ALPHA balance held by xALPHA, minus accrued fees
*/
function getBufferBalance() public view override returns (uint256) {
return alphaToken.balanceOf(address(this)).sub(withdrawableAlphaFees);
}
/*
* @dev Get staked and buffer balance of the xALPHA contract, as separate values
*
* @return Staked and buffer balance as a tuple
*/
function getFundBalances() public view override returns (uint256, uint256) {
return (totalStakedBalance, getBufferBalance());
}
/**
* @dev Get the withdrawable amount from a staking proxy
* @param proxyIndex The proxy index
* @return The withdrawable amount
*/
function getWithdrawableAmount(uint256 proxyIndex) public view override returns (uint256) {
require(proxyIndex < stakingFactory.getStakingProxyProxiesLength(), "Invalid index");
return IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).getWithdrawableAmount();
}
/**
* @dev Get the withdrawable fee amounts
* @return feeAsset The fee asset
* @return feeAmount The withdrawable amount
*/
function getWithdrawableFees() public view returns (address feeAsset, uint256 feeAmount) {
feeAsset = address(alphaToken);
feeAmount = withdrawableAlphaFees;
}
/*
* @dev Admin function to stake tokens from the buffer.
*
* @param proxyIndex: The proxy index to stake with
* @param amount: allocation to staked balance
* @param force: stake regardless of unbonding status
*/
function stake(
uint256 proxyIndex,
uint256 amount,
bool force
) public override onlyOwnerOrManager {
_certifyAdmin();
_stake(proxyIndex, amount, force);
updateStakedBalance();
}
/*
* @dev Updates the staked balance of the xALPHA contract.
* @notice Includes any stake currently unbonding.
*
* @return Total staked balance in ALPHA staking contract
*/
function updateStakedBalance() public override onlyOwnerOrManager {
uint256 _totalStakedBalance;
for (uint256 i = 0; i < stakingFactory.getStakingProxyProxiesLength(); i++) {
_totalStakedBalance = _totalStakedBalance.add(
IStakingProxy(stakingFactory.stakingProxyProxies(i)).getTotalStaked()
);
}
// Update staked balance
totalStakedBalance = _totalStakedBalance;
emit UpdateStakedBalance(totalStakedBalance);
}
/*
* @notice Admin-callable function in case of persistent depletion of buffer reserve
* or emergency shutdown
* @notice Incremental ALPHA will only be allocated to buffer reserve
* @notice Starting a new unbonding period cancels the last one. Need to use 'force'
* explicitly cancel a current unbonding.s
*/
function unbond(uint256 proxyIndex, bool force) public override onlyOwnerOrManager {
_certifyAdmin();
_unbond(proxyIndex, force);
}
/*
* @notice Admin-callable function to withdraw unbonded stake back into the buffer
* @notice Incremental ALPHA will only be allocated to buffer reserve
* @notice There is a 72-hour deadline to claim unbonded stake after the 30-day unbonding
* period ends. This call will fail in the alpha staking contract if the 72-hour deadline
* is expired.
*/
function claimUnbonded(uint256 proxyIndex) public override onlyOwnerOrManager {
_certifyAdmin();
_claim(proxyIndex);
updateStakedBalance();
}
/*
* @notice Staking ALPHA cancels any currently open
* unbonding. This will not stake unless the contract
* is not unbonding, or the force param is sent
* @param proxyIndex: the proxy index to stake with
* @param amount: allocation to staked balance
* @param force: stake regardless of unbonding status
*/
function _stake(
uint256 proxyIndex,
uint256 amount,
bool force
) private {
require(amount > 0, "Cannot stake zero tokens");
require(
!IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).isUnbonding() || force,
"Cannot stake during unbonding"
);
// Update the most recent stake timestamp
lastStakeTimestamp = block.timestamp;
alphaToken.safeTransfer(address(stakingFactory.stakingProxyProxies(proxyIndex)), amount);
IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).stake(amount);
emit Stake(proxyIndex, block.timestamp, amount);
}
/*
* @notice Unbonding ALPHA cancels any currently open
* unbonding. This will not unbond unless the contract
* is not already unbonding, or the force param is sent
* @param proxyIndex: the proxy index to unbond
* @param force: unbond regardless of status
*/
function _unbond(uint256 proxyIndex, bool force) internal {
require(
!IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).isUnbonding() || force,
"Cannot unbond during unbonding"
);
IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).unbond();
emit Unbond(
proxyIndex,
block.timestamp,
IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).getUnbondingAmount()
);
}
/*
* @notice Claims any fully unbonded ALPHA. Must be called
* within 72 hours after unbonding period expires, or
* funds are re-staked.
*
* @param proxyIndex: the proxy index to claim rewards for
*/
function _claim(uint256 proxyIndex) internal {
require(IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).isUnbonding(), "Not unbonding");
uint256 claimedAmount = IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).withdraw();
emit Claim(proxyIndex, claimedAmount);
}
/*
* @dev Get fee for a specific action
*
* @param _value: the value on which to assess the fee
* @param _feeDivisor: the inverse of the percentage of the fee (i.e. 1% = 100)
*
* @return fee: total amount of fee to be assessed
*/
function _calculateFee(uint256 _value, uint256 _feeDivisor) internal pure returns (uint256 fee) {
if (_feeDivisor > 0) {
fee = _value.div(_feeDivisor);
}
}
/*
* @dev Increase tracked amount of fees for management
*
* @param _feeAmount: the amount to increase management fees by
*/
function _incrementWithdrawableAlphaFees(uint256 _feeAmount) private {
withdrawableAlphaFees = withdrawableAlphaFees.add(_feeAmount);
}
/* ========================================================================================= */
/* Emergency Functions */
/* ========================================================================================= */
/*
* @dev Admin function for pausing contract operations. Pausing prevents mints.
*
*/
function pauseContract() public override onlyOwnerOrManager {
_pause();
}
/*
* @dev Admin function for unpausing contract operations.
*
*/
function unpauseContract() public override onlyOwnerOrManager {
_unpause();
}
/*
* @dev Public callable function for unstaking in event of admin failure/incapacitation.
*
* @notice Can only be called after a period of manager inactivity. Starts a 30-day unbonding
* period. emergencyClaim must be called within 72 hours after the 30 day unbounding period expires.
* Cancels any previous unbonding on the first call. Cannot be called again otherwise a caller
* could indefinitely delay unbonding. Unbonds all staking proxy contracts.
*
* Once emergencyUnbondingTimestamp has been set, it is never reset unless an admin decides to.
*/
function emergencyUnbond() external override {
require(adminActiveTimestamp.add(LIQUIDATION_TIME_PERIOD) < block.timestamp, "Liquidation time not elapsed");
uint256 thirtyThreeDaysAgo = block.timestamp - 33 days;
require(emergencyUnbondTimestamp < thirtyThreeDaysAgo, "In unbonding period");
emergencyUnbondTimestamp = block.timestamp;
// Unstake everything
for (uint256 i = 0; i < stakingFactory.getStakingProxyProxiesLength(); i++) {
_unbond(i, true);
}
}
/*
* @dev Public callable function for claiming unbonded stake in the event of admin failure/incapacitation.
*
* @notice Can only be called after a period of manager inactivity. Can only be called
* after a 30-day unbonding period, and must be called within 72 hours of unbound period expiry. Makes a claim
* for all staking proxies
*/
function emergencyClaim() external override {
require(adminActiveTimestamp.add(LIQUIDATION_TIME_PERIOD) < block.timestamp, "Liquidation time not elapsed");
require(emergencyUnbondTimestamp != 0, "Emergency unbond not called");
emergencyUnbondTimestamp = 0;
// Claim everything
for (uint256 i = 0; i < stakingFactory.getStakingProxyProxiesLength(); i++) {
_claim(i);
}
}
/* ========================================================================================= */
/* Utils/Fallback */
/* ========================================================================================= */
/*
* @notice Inverse of fee i.e., a fee divisor of 100 == 1%
* @notice Three fee types
* @dev Mint fee 0 or <= 2%
* @dev Burn fee 0 or <= 1%
* @dev Claim fee 0 <= 4%
*/
function setFeeDivisors(
uint256 mintFeeDivisor,
uint256 burnFeeDivisor,
uint256 claimFeeDivisor
) public override onlyOwner {
_setFeeDivisors(mintFeeDivisor, burnFeeDivisor, claimFeeDivisor);
}
/*
* @dev Internal setter for the fee divisors, with enforced maximum fees.
*/
function _setFeeDivisors(
uint256 _mintFeeDivisor,
uint256 _burnFeeDivisor,
uint256 _claimFeeDivisor
) private {
require(_mintFeeDivisor == 0 || _mintFeeDivisor >= 50, "Invalid fee");
require(_burnFeeDivisor == 0 || _burnFeeDivisor >= 100, "Invalid fee");
require(_claimFeeDivisor >= 25, "Invalid fee");
feeDivisors.mintFee = _mintFeeDivisor;
feeDivisors.burnFee = _burnFeeDivisor;
feeDivisors.claimFee = _claimFeeDivisor;
emit FeeDivisorsSet(_mintFeeDivisor, _burnFeeDivisor, _claimFeeDivisor);
}
/*
* @dev Registers that admin is present and active
* @notice If admin isn't certified within liquidation time period,
* emergencyUnstake function becomes callable
*/
function _certifyAdmin() private {
adminActiveTimestamp = block.timestamp;
}
/*
* @dev Update the AMM to use for swaps.
* @param version: the swap mode - 0 for sushiswap, 1 for Uniswap V3.
*
* Should be used when e.g. pricing is better on one version vs.
* the other. Only valid values are 0 and 1. A new version of Uniswap
* or integration with another liquidity protocol will require a full
* contract upgrade.
*/
function updateSwapRouter(SwapMode version) public override onlyOwnerOrManager {
require(version == SwapMode.SUSHISWAP || version == SwapMode.UNISWAP_V3, "Invalid swap router version");
swapMode = version;
emit UpdateSwapRouter(version);
}
/*
* @dev Update the fee tier for the ETH/ALPHA Uniswap V3 pool.
* @param fee: the fee tier to use.
*
* Should be used when trades can be executed more efficiently at a certain
* fee tier, based on the combination of fees and slippage.
*
* Fees are expressed in 1/100th of a basis point.
* Only three fee tiers currently exist.
* 500 - (0.05%)
* 3000 - (0.3%)
* 10000 - (1%)
* Not enforcing these values because Uniswap's contracts
* allow them to set arbitrary fee tiers in the future.
* Take care when calling this function to make sure a pool
* actually exists for a given fee, and it is the most liquid
* pool for the ALPHA/ETH pair.
*/
function updateUniswapV3AlphaPoolFee(uint24 fee) external override onlyOwnerOrManager {
v3AlphaPoolFee = fee;
emit UpdateUniswapV3AlphaPoolFee(v3AlphaPoolFee);
}
/*
* @dev Emergency function in case of errant transfer of
* xALPHA token directly to contract.
*
* Errant xALPHA can only be sent back to management.
*/
function withdrawNativeToken() public override onlyOwnerOrManager {
uint256 tokenBal = balanceOf(address(this));
require(tokenBal > 0, "No tokens to withdraw");
IERC20(address(this)).safeTransfer(msg.sender, tokenBal);
}
/*
* @dev Emergency function in case of errant transfer of
* ERC20 token directly to proxy contracts.
*
* Errant ERC20 token can only be sent back to management.
*/
function withdrawTokenFromProxy(uint256 proxyIndex, address token) external override onlyOwnerOrManager {
IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).withdrawToken(token);
IERC20(token).safeTransfer(msg.sender, IERC20(token).balanceOf(address(this)));
}
/*
* @dev Withdraw function for ALPHA fees.
*
* All fees are denominated in ALPHA, so this should cover all
* fees earned via contract interactions. Fees can only be
* sent to management.
*/
function withdrawFees() public override {
require(xTokenManager.isRevenueController(msg.sender), "Callable only by Revenue Controller");
uint256 alphaFees = withdrawableAlphaFees;
withdrawableAlphaFees = 0;
alphaToken.safeTransfer(msg.sender, alphaFees);
emit FeeWithdraw(alphaFees);
}
/**
* @dev Exempts an address from blocklock
* @param lockAddress The address to exempt
*/
function exemptFromBlockLock(address lockAddress) external onlyOwnerOrManager {
_exemptFromBlockLock(lockAddress);
}
/**
* @dev Removes exemption for an address from blocklock
* @param lockAddress The address to remove exemption
*/
function removeBlockLockExemption(address lockAddress) external onlyOwnerOrManager {
_removeBlockLockExemption(lockAddress);
}
/*
* @dev Enforce functions only called by management.
*/
modifier onlyOwnerOrManager() {
require(msg.sender == owner() || xTokenManager.isManager(msg.sender, address(this)), "Non-admin caller");
_;
}
/*
* @dev Fallback function for received ETH.
*
* The contract may receive ETH as part of swaps, so only reject
* if the ETH is sent directly.
*/
receive() external payable {
// solhint-disable-next-line avoid-tx-origin
require(msg.sender != tx.origin, "Errant ETH deposit");
}
}
// 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.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;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable 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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_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 { }
uint256[44] private __gap;
}
// 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.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @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.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_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());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.6.12;
/**
Contract which implements locking of functions via a notLocked modifier
Functions are locked per address.
*/
contract BlockLock {
// how many blocks are the functions locked for
uint256 private constant BLOCK_LOCK_COUNT = 6;
// last block for which this address is timelocked
mapping(address => uint256) public lastLockedBlock;
mapping(address => bool) public blockLockExempt;
function _lock(address lockAddress) internal {
if (!blockLockExempt[lockAddress]) {
lastLockedBlock[lockAddress] = block.number + BLOCK_LOCK_COUNT;
}
}
function _exemptFromBlockLock(address lockAddress) internal {
blockLockExempt[lockAddress] = true;
}
function _removeBlockLockExemption(address lockAddress) internal {
blockLockExempt[lockAddress] = false;
}
modifier notLocked(address lockAddress) {
require(lastLockedBlock[lockAddress] <= block.number, "Address is temporarily locked");
_;
}
}
// SPDX-License-Identifier: ISC
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IxTokenManager.sol";
import "./IALPHAStaking.sol";
import "./IWETH.sol";
import "./IOneInchLiquidityProtocol.sol";
import "./IStakingProxy.sol";
import "../helpers/StakingFactory.sol";
interface IxALPHA {
enum SwapMode {
SUSHISWAP,
UNISWAP_V3
}
struct FeeDivisors {
uint256 mintFee;
uint256 burnFee;
uint256 claimFee;
}
event Stake(uint256 proxyIndex, uint256 timestamp, uint256 amount);
event Unbond(uint256 proxyIndex, uint256 timestamp, uint256 amount);
event Claim(uint256 proxyIndex, uint256 amount);
event FeeDivisorsSet(uint256 mintFee, uint256 burnFee, uint256 claimFee);
event FeeWithdraw(uint256 fee);
event UpdateSwapRouter(SwapMode version);
event UpdateUniswapV3AlphaPoolFee(uint24 fee);
event UpdateStakedBalance(uint256 totalStaked);
function initialize(
string calldata _symbol,
IWETH _wethToken,
IERC20 _alphaToken,
address _alphaStaking,
StakingFactory _stakingFactory,
IxTokenManager _xTokenManager,
address _uniswapRouter,
address _sushiswapRouter,
FeeDivisors calldata _feeDivisors
) external;
function mint(uint256 minReturn) external payable;
function mintWithToken(uint256 alphaAmount) external;
function calculateMintAmount(uint256 incrementalAlpha, uint256 totalSupply)
external
view
returns (uint256 mintAmount);
function burn(
uint256 tokenAmount,
bool redeemForEth,
uint256 minReturn
) external;
function getNav() external view returns (uint256);
function getBufferBalance() external view returns (uint256);
function getFundBalances() external view returns (uint256, uint256);
function getWithdrawableAmount(uint256 proxyIndex) external view returns (uint256);
function stake(
uint256 proxyIndex,
uint256 amount,
bool force
) external;
function updateStakedBalance() external;
function unbond(uint256 proxyIndex, bool force) external;
function claimUnbonded(uint256 proxyIndex) external;
function pauseContract() external;
function unpauseContract() external;
function emergencyUnbond() external;
function emergencyClaim() external;
function setFeeDivisors(
uint256 mintFeeDivisor,
uint256 burnFeeDivisor,
uint256 claimFeeDivisor
) external;
function updateSwapRouter(SwapMode version) external;
function updateUniswapV3AlphaPoolFee(uint24 fee) external;
function withdrawNativeToken() external;
function withdrawTokenFromProxy(uint256 proxyIndex, address token) external;
function withdrawFees() external;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IxTokenManager {
/**
* @dev Add a manager to an xAsset fund
*/
function addManager(address manager, address fund) external;
/**
* @dev Remove a manager from an xAsset fund
*/
function removeManager(address manager, address fund) external;
/**
* @dev Check if an address is a manager for a fund
*/
function isManager(address manager, address fund) external view returns (bool);
/**
* @dev Set revenue controller
*/
function setRevenueController(address controller) external;
/**
* @dev Check if address is revenue controller
*/
function isRevenueController(address caller) external view returns (bool);
}
// SPDX-License-Identifier: ISC
pragma solidity 0.6.12;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: ISC
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IAlphaStaking {
event SetWorker(address worker);
event Stake(address owner, uint256 share, uint256 amount);
event Unbond(address owner, uint256 unbondTime, uint256 unbondShare);
event Withdraw(address owner, uint256 withdrawShare, uint256 withdrawAmount);
event CancelUnbond(address owner, uint256 unbondTime, uint256 unbondShare);
event Reward(address worker, uint256 rewardAmount);
event Extract(address governor, uint256 extractAmount);
struct Data {
uint256 status;
uint256 share;
uint256 unbondTime;
uint256 unbondShare;
}
// solhint-disable-next-line func-name-mixedcase
function STATUS_READY() external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function STATUS_UNBONDING() external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function UNBONDING_DURATION() external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function WITHDRAW_DURATION() external view returns (uint256);
function alpha() external view returns (address);
function getStakeValue(address user) external view returns (uint256);
function totalAlpha() external view returns (uint256);
function totalShare() external view returns (uint256);
function stake(uint256 amount) external;
function unbond(uint256 share) external;
function withdraw() external;
function users(address user) external view returns (Data calldata);
}
// SPDX-License-Identifier: ISC
pragma solidity 0.6.12;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Copied from:
// https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/interfaces/ISwapRouter.sol
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IUniswapV3SwapRouter {
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: ISC
pragma solidity 0.6.12;
interface IStakingProxy {
function initialize(address alphaStaking) external;
function getTotalStaked() external view returns (uint256);
function getUnbondingAmount() external view returns (uint256);
function getLastUnbondingTimestamp() external view returns (uint256);
function getWithdrawableAmount() external view returns (uint256);
function isUnbonding() external view returns (bool);
function withdraw() external returns (uint256);
function stake(uint256 amount) external;
function unbond() external;
function withdrawToken(address token) external;
}
// SPDX-License-Identifier: ISC
pragma solidity 0.6.12;
import "../proxies/StakingProxyBeacon.sol";
import "../proxies/StakingProxyProxy.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract StakingFactory is Ownable {
address public stakingProxyBeacon;
address payable[] public stakingProxyProxies;
constructor(address _stakingProxyBeacon) public {
stakingProxyBeacon = _stakingProxyBeacon;
}
function deployProxy() external onlyOwner returns (address) {
StakingProxyProxy proxy = new StakingProxyProxy(stakingProxyBeacon);
stakingProxyProxies.push(address(proxy));
return address(proxy);
}
function getStakingProxyProxiesLength() external view returns (uint256) {
return stakingProxyProxies.length;
}
}
// 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.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 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.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, 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.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;
}
// 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: ISC
pragma solidity 0.6.12;
interface IOneInchLiquidityProtocol {
function swap(
address src,
address dst,
uint256 amount,
uint256 minReturn,
address referral
) external payable returns (uint256 result);
function swapFor(
address src,
address dst,
uint256 amount,
uint256 minReturn,
address referral,
address payable receiver
) external payable returns (uint256 result);
}
// SPDX-License-Identifier: ISC
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/proxy/UpgradeableBeacon.sol";
contract StakingProxyBeacon is UpgradeableBeacon {
constructor(address _implementation) public UpgradeableBeacon(_implementation) {}
}
// SPDX-License-Identifier: ISC
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/proxy/BeaconProxy.sol";
contract StakingProxyProxy is BeaconProxy {
constructor(address _beacon) public BeaconProxy(_beacon, "") {}
}
// 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 "./IBeacon.sol";
import "../access/Ownable.sol";
import "../utils/Address.sol";
/**
* @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
* implementation contract, which is where they will delegate all function calls.
*
* An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
*/
contract UpgradeableBeacon is IBeacon, Ownable {
address private _implementation;
/**
* @dev Emitted when the implementation returned by the beacon is changed.
*/
event Upgraded(address indexed implementation);
/**
* @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
* beacon.
*/
constructor(address implementation_) public {
_setImplementation(implementation_);
}
/**
* @dev Returns the current implementation address.
*/
function implementation() public view virtual override returns (address) {
return _implementation;
}
/**
* @dev Upgrades the beacon to a new implementation.
*
* Emits an {Upgraded} event.
*
* Requirements:
*
* - msg.sender must be the owner of the contract.
* - `newImplementation` must be a contract.
*/
function upgradeTo(address newImplementation) public virtual onlyOwner {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation contract address for this beacon
*
* Requirements:
*
* - `newImplementation` must be a contract.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract");
_implementation = newImplementation;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// 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 "./Proxy.sol";
import "../utils/Address.sol";
import "./IBeacon.sol";
/**
* @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
*
* The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
* conflict with the storage layout of the implementation behind the proxy.
*
* _Available since v3.4._
*/
contract BeaconProxy is Proxy {
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 private constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Initializes the proxy with `beacon`.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
* will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity
* constructor.
*
* Requirements:
*
* - `beacon` must be a contract with the interface {IBeacon}.
*/
constructor(address beacon, bytes memory data) public payable {
assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1));
_setBeacon(beacon, data);
}
/**
* @dev Returns the current beacon address.
*/
function _beacon() internal view virtual returns (address beacon) {
bytes32 slot = _BEACON_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
beacon := sload(slot)
}
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation() internal view virtual override returns (address) {
return IBeacon(_beacon()).implementation();
}
/**
* @dev Changes the proxy to use a new beacon.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
*
* Requirements:
*
* - `beacon` must be a contract.
* - The implementation returned by `beacon` must be a contract.
*/
function _setBeacon(address beacon, bytes memory data) internal virtual {
require(
Address.isContract(beacon),
"BeaconProxy: beacon is not a contract"
);
require(
Address.isContract(IBeacon(beacon).implementation()),
"BeaconProxy: beacon implementation is not a contract"
);
bytes32 slot = _BEACON_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, beacon)
}
if (data.length > 0) {
Address.functionDelegateCall(_implementation(), data, "BeaconProxy: function call failed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
} | Public callable function for claiming unbonded stake in the event of admin failure/incapacitation. Can only be called after a period of manager inactivity. Can only be called after a 30-day unbonding period, and must be called within 72 hours of unbound period expiry. Makes a claim for all staking proxies/ Claim everything | function emergencyClaim() external override {
require(adminActiveTimestamp.add(LIQUIDATION_TIME_PERIOD) < block.timestamp, "Liquidation time not elapsed");
require(emergencyUnbondTimestamp != 0, "Emergency unbond not called");
emergencyUnbondTimestamp = 0;
for (uint256 i = 0; i < stakingFactory.getStakingProxyProxiesLength(); i++) {
_claim(i);
}
}
| 10,295,839 |
./full_match/80001/0x59a753Ed44FCa823870Ae337B00331Ceac257DEE/sources/contracts/Kisaki.sol | Script to transform hash to picture / | function setScript(string calldata _script) public onlyOwner {
script = _script;
}
mapping(bytes32 => uint256) public hashToToken;
constructor(
address _royaltyRecipient,
uint128 _royaltyBps,
address _primarySaleRecipient,
string memory _script
)
ERC721Drop(
"Kisaki",
"KST",
_royaltyRecipient,
_royaltyBps,
_primarySaleRecipient
)
| 5,672,824 |
./full_match/3/0xe9460c6987061d3D3ae8d7007E2C7bFDb82CF1af/sources/contracts/mood.sol | This is going to get mood | function getMood() public view returns(string memory) {
return mood;
}
| 14,145,988 |
// 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 (last updated v4.5.0-rc.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.0;
/**
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
*
* _Available since v4.5._
*/
interface IVotes {
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) external view returns (uint256);
/**
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
*/
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*/
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) external view returns (address);
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) external;
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (governance/utils/Votes.sol)
pragma solidity ^0.8.0;
import "../../utils/Context.sol";
import "../../utils/Counters.sol";
import "../../utils/Checkpoints.sol";
import "../../utils/cryptography/draft-EIP712.sol";
import "./IVotes.sol";
/**
* @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be
* transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of
* "representative" that will pool delegated voting units from different accounts and can then use it to vote in
* decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to
* delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative.
*
* This contract is often combined with a token contract such that voting units correspond to token units. For an
* example, see {ERC721Votes}.
*
* The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed
* at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the
* cost of this history tracking optional.
*
* When using this module the derived contract must implement {_getVotingUnits} (for example, make it return
* {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the
* previous example, it would be included in {ERC721-_beforeTokenTransfer}).
*
* _Available since v4.5._
*/
abstract contract Votes is IVotes, Context, EIP712 {
using Checkpoints for Checkpoints.History;
using Counters for Counters.Counter;
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegation;
mapping(address => Checkpoints.History) private _delegateCheckpoints;
Checkpoints.History private _totalCheckpoints;
mapping(address => Counters.Counter) private _nonces;
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) public view virtual override returns (uint256) {
return _delegateCheckpoints[account].latest();
}
/**
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
return _delegateCheckpoints[account].getAtBlock(blockNumber);
}
/**
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) {
require(blockNumber < block.number, "Votes: block not yet mined");
return _totalCheckpoints.getAtBlock(blockNumber);
}
/**
* @dev Returns the current total supply of votes.
*/
function _getTotalSupply() internal view virtual returns (uint256) {
return _totalCheckpoints.latest();
}
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) public view virtual override returns (address) {
return _delegation[account];
}
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual override {
address account = _msgSender();
_delegate(account, delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= expiry, "Votes: signature expired");
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "Votes: invalid nonce");
_delegate(signer, delegatee);
}
/**
* @dev Delegate all of `account`'s voting units to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address account, address delegatee) internal virtual {
address oldDelegate = delegates(account);
_delegation[account] = delegatee;
emit DelegateChanged(account, oldDelegate, delegatee);
_moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));
}
/**
* @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to`
* should be zero. Total supply of voting units will be adjusted with mints and burns.
*/
function _transferVotingUnits(
address from,
address to,
uint256 amount
) internal virtual {
if (from == address(0)) {
_totalCheckpoints.push(_add, amount);
}
if (to == address(0)) {
_totalCheckpoints.push(_subtract, amount);
}
_moveDelegateVotes(delegates(from), delegates(to), amount);
}
/**
* @dev Moves delegated votes from one delegate to another.
*/
function _moveDelegateVotes(
address from,
address to,
uint256 amount
) private {
if (from != to && amount > 0) {
if (from != address(0)) {
(uint256 oldValue, uint256 newValue) = _delegateCheckpoints[from].push(_subtract, amount);
emit DelegateVotesChanged(from, oldValue, newValue);
}
if (to != address(0)) {
(uint256 oldValue, uint256 newValue) = _delegateCheckpoints[to].push(_add, amount);
emit DelegateVotesChanged(to, oldValue, newValue);
}
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
/**
* @dev Returns an address nonce.
*/
function nonces(address owner) public view virtual returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev Returns the contract's {EIP712} domain separator.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev Must return the voting units held by an account.
*/
function _getVotingUnits(address) internal virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (token/ERC721/ERC721.sol)
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 {
_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);
_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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, 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
// 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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
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
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (token/ERC721/extensions/draft-ERC721Votes.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../governance/utils/Votes.sol";
/**
* @dev Extension of ERC721 to support voting and delegation as implemented by {Votes}, where each individual NFT counts
* as 1 vote unit.
*
* Tokens do not count as votes until they are delegated, because votes must be tracked which incurs an additional cost
* on every transfer. Token holders can either delegate to a trusted representative who will decide how to make use of
* the votes in governance decisions, or they can delegate to themselves to be their own representative.
*
* _Available since v4.5._
*/
abstract contract ERC721Votes is ERC721, Votes {
/**
* @dev Adjusts votes when tokens are transferred.
*
* Emits a {Votes-DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
_transferVotingUnits(from, to, 1);
super._afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Returns the balance of `account`.
*/
function _getVotingUnits(address account) internal virtual override returns (uint256) {
return balanceOf(account);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.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);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Checkpoints.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SafeCast.sol";
/**
* @dev This library defines the `History` struct, for checkpointing values as they change at different points in
* time, and later looking up past values by block number. See {Votes} as an example.
*
* To create a history of checkpoints define a variable type `Checkpoints.History` in your contract, and store a new
* checkpoint for the current transaction block using the {push} function.
*
* _Available since v4.5._
*/
library Checkpoints {
struct Checkpoint {
uint32 _blockNumber;
uint224 _value;
}
struct History {
Checkpoint[] _checkpoints;
}
/**
* @dev Returns the value in the latest checkpoint, or zero if there are no checkpoints.
*/
function latest(History storage self) internal view returns (uint256) {
uint256 pos = self._checkpoints.length;
return pos == 0 ? 0 : self._checkpoints[pos - 1]._value;
}
/**
* @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one
* before it is returned, or zero otherwise.
*/
function getAtBlock(History storage self, uint256 blockNumber) internal view returns (uint256) {
require(blockNumber < block.number, "Checkpoints: block not yet mined");
uint256 high = self._checkpoints.length;
uint256 low = 0;
while (low < high) {
uint256 mid = Math.average(low, high);
if (self._checkpoints[mid]._blockNumber > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : self._checkpoints[high - 1]._value;
}
/**
* @dev Pushes a value onto a History so that it is stored as the checkpoint for the current block.
*
* Returns previous value and new value.
*/
function push(History storage self, uint256 value) internal returns (uint256, uint256) {
uint256 pos = self._checkpoints.length;
uint256 old = latest(self);
if (pos > 0 && self._checkpoints[pos - 1]._blockNumber == block.number) {
self._checkpoints[pos - 1]._value = SafeCast.toUint224(value);
} else {
self._checkpoints.push(
Checkpoint({_blockNumber: SafeCast.toUint32(block.number), _value: SafeCast.toUint224(value)})
);
}
return (old, value);
}
/**
* @dev Pushes a value onto a History, by updating the latest value using binary operation `op`. The new value will
* be set to `op(latest, delta)`.
*
* Returns previous value and new value.
*/
function push(
History storage self,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) internal returns (uint256, uint256) {
return push(self, op(latest(self), delta));
}
}
// 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/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;
}
}
// 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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.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 v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/math/Math.sol)
pragma solidity ^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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// 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
pragma solidity 0.8.6;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/draft-ERC721Votes.sol';
import './abstract/JBOperatable.sol';
import './interfaces/IJBProjects.sol';
import './libraries/JBOperations.sol';
/**
@notice
Stores project ownership and metadata.
@dev
Projects are represented as ERC-721's.
@dev
Adheres to:
IJBProjects: General interface for the methods in this contract that interact with the blockchain's state according to the protocol's rules.
@dev
Inherits from:
JBOperatable: Includes convenience functionality for checking a message sender's permissions before executing certain transactions.
ERC721Votes: A checkpointable standard definition for non-fungible tokens (NFTs).
Ownable: Includes convenience functionality for checking a message sender's permissions before executing certain transactions.
*/
contract JBProjects is IJBProjects, JBOperatable, ERC721Votes, Ownable {
//*********************************************************************//
// --------------------- public stored properties -------------------- //
//*********************************************************************//
/**
@notice
The number of projects that have been created using this contract.
@dev
The count is incremented with each new project created.
The resulting ERC-721 token ID for each project is the newly incremented count value.
*/
uint256 public override count = 0;
/**
@notice
The metadata for each project, which can be used across several domains.
_projectId The ID of the project to which the metadata belongs.
_domain The domain within which the metadata applies. Applications can use the domain namespace as they wish.
*/
mapping(uint256 => mapping(uint256 => string)) public override metadataContentOf;
/**
@notice
The contract resolving each project ID to its ERC721 URI.
*/
IJBTokenUriResolver public override tokenUriResolver;
//*********************************************************************//
// ------------------------- external views -------------------------- //
//*********************************************************************//
/**
@notice
Returns the URI where the ERC-721 standard JSON of a project is hosted.
@param _projectId The ID of the project to get a URI of.
@return The token URI to use for the provided `_projectId`.
*/
function tokenURI(uint256 _projectId) public view override returns (string memory) {
// If there's no resolver, there's no URI.
if (tokenUriResolver == IJBTokenUriResolver(address(0))) return '';
// Return the resolved URI.
return tokenUriResolver.getUri(_projectId);
}
//*********************************************************************//
// -------------------------- constructor ---------------------------- //
//*********************************************************************//
/**
@param _operatorStore A contract storing operator assignments.
*/
constructor(IJBOperatorStore _operatorStore)
ERC721('Juicebox Projects', 'JUICEBOX')
EIP712('Juicebox Projects', '1')
JBOperatable(_operatorStore)
// solhint-disable-next-line no-empty-blocks
{
}
//*********************************************************************//
// ---------------------- external transactions ---------------------- //
//*********************************************************************//
/**
@notice
Create a new project for the specified owner, which mints an NFT (ERC-721) into their wallet.
@dev
Anyone can create a project on an owner's behalf.
@param _owner The address that will be the owner of the project.
@param _metadata A struct containing metadata content about the project, and domain within which the metadata applies.
@return projectId The token ID of the newly created project.
*/
function createFor(address _owner, JBProjectMetadata calldata _metadata)
external
override
returns (uint256 projectId)
{
// Increment the count, which will be used as the ID.
projectId = ++count;
// Mint the project.
_safeMint(_owner, projectId);
// Set the metadata if one was provided.
if (bytes(_metadata.content).length > 0)
metadataContentOf[projectId][_metadata.domain] = _metadata.content;
emit Create(projectId, _owner, _metadata, msg.sender);
}
/**
@notice
Allows a project owner to set the project's metadata content for a particular domain namespace.
@dev
Only a project's owner or operator can set its metadata.
@dev
Applications can use the domain namespace as they wish.
@param _projectId The ID of the project who's metadata is being changed.
@param _metadata A struct containing metadata content, and domain within which the metadata applies.
*/
function setMetadataOf(uint256 _projectId, JBProjectMetadata calldata _metadata)
external
override
requirePermission(ownerOf(_projectId), _projectId, JBOperations.SET_METADATA)
{
// Set the project's new metadata content within the specified domain.
metadataContentOf[_projectId][_metadata.domain] = _metadata.content;
emit SetMetadata(_projectId, _metadata, msg.sender);
}
/**
@notice
Sets the address of the resolver used to retrieve the tokenURI of projects.
@param _newResolver The address of the new resolver.
*/
function setTokenUriResolver(IJBTokenUriResolver _newResolver) external override onlyOwner {
// Store the new resolver.
tokenUriResolver = _newResolver;
emit SetTokenUriResolver(_newResolver, msg.sender);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBOperatable.sol';
//*********************************************************************//
// --------------------------- custom errors -------------------------- //
//*********************************************************************//
error UNAUTHORIZED();
/**
@notice
Modifiers to allow access to functions based on the message sender's operator status.
*/
abstract contract JBOperatable is IJBOperatable {
//*********************************************************************//
// ---------------------------- modifiers ---------------------------- //
//*********************************************************************//
modifier requirePermission(
address _account,
uint256 _domain,
uint256 _permissionIndex
) {
_requirePermission(_account, _domain, _permissionIndex);
_;
}
modifier requirePermissionAllowingOverride(
address _account,
uint256 _domain,
uint256 _permissionIndex,
bool _override
) {
_requirePermissionAllowingOverride(_account, _domain, _permissionIndex, _override);
_;
}
//*********************************************************************//
// ---------------- public immutable stored properties --------------- //
//*********************************************************************//
/**
@notice
A contract storing operator assignments.
*/
IJBOperatorStore public immutable override operatorStore;
//*********************************************************************//
// -------------------------- constructor ---------------------------- //
//*********************************************************************//
/**
@param _operatorStore A contract storing operator assignments.
*/
constructor(IJBOperatorStore _operatorStore) {
operatorStore = _operatorStore;
}
//*********************************************************************//
// -------------------------- internal views ------------------------- //
//*********************************************************************//
/**
@notice
Require the message sender is either the account or has the specified permission.
@param _account The account to allow.
@param _domain The domain within which the permission index will be checked.
@param _domain The permission index that an operator must have within the specified domain to be allowed.
*/
function _requirePermission(
address _account,
uint256 _domain,
uint256 _permissionIndex
) internal view {
if (
msg.sender != _account &&
!operatorStore.hasPermission(msg.sender, _account, _domain, _permissionIndex) &&
!operatorStore.hasPermission(msg.sender, _account, 0, _permissionIndex)
) revert UNAUTHORIZED();
}
/**
@notice
Require the message sender is either the account, has the specified permission, or the override condition is true.
@param _account The account to allow.
@param _domain The domain within which the permission index will be checked.
@param _domain The permission index that an operator must have within the specified domain to be allowed.
@param _override The override condition to allow.
*/
function _requirePermissionAllowingOverride(
address _account,
uint256 _domain,
uint256 _permissionIndex,
bool _override
) internal view {
if (
!_override &&
msg.sender != _account &&
!operatorStore.hasPermission(msg.sender, _account, _domain, _permissionIndex) &&
!operatorStore.hasPermission(msg.sender, _account, 0, _permissionIndex)
) revert UNAUTHORIZED();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
enum JBBallotState {
Active,
Approved,
Failed
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../structs/JBFundingCycleData.sol';
import './../structs/JBFundingCycleMetadata.sol';
import './../structs/JBProjectMetadata.sol';
import './../structs/JBGroupedSplits.sol';
import './../structs/JBFundAccessConstraints.sol';
import './../structs/JBProjectMetadata.sol';
import './IJBDirectory.sol';
import './IJBToken.sol';
import './IJBPaymentTerminal.sol';
import './IJBFundingCycleStore.sol';
import './IJBTokenStore.sol';
import './IJBSplitsStore.sol';
interface IJBController {
event LaunchProject(uint256 configuration, uint256 projectId, string memo, address caller);
event LaunchFundingCycles(uint256 configuration, uint256 projectId, string memo, address caller);
event ReconfigureFundingCycles(
uint256 configuration,
uint256 projectId,
string memo,
address caller
);
event SetFundAccessConstraints(
uint256 indexed fundingCycleConfiguration,
uint256 indexed fundingCycleNumber,
uint256 indexed projectId,
JBFundAccessConstraints constraints,
address caller
);
event DistributeReservedTokens(
uint256 indexed fundingCycleConfiguration,
uint256 indexed fundingCycleNumber,
uint256 indexed projectId,
address beneficiary,
uint256 tokenCount,
uint256 beneficiaryTokenCount,
string memo,
address caller
);
event DistributeToReservedTokenSplit(
uint256 indexed projectId,
uint256 indexed domain,
uint256 indexed group,
JBSplit split,
uint256 tokenCount,
address caller
);
event MintTokens(
address indexed beneficiary,
uint256 indexed projectId,
uint256 tokenCount,
uint256 beneficiaryTokenCount,
string memo,
uint256 reservedRate,
address caller
);
event BurnTokens(
address indexed holder,
uint256 indexed projectId,
uint256 tokenCount,
string memo,
address caller
);
event Migrate(uint256 indexed projectId, IJBController to, address caller);
event PrepMigration(uint256 indexed projectId, IJBController from, address caller);
function projects() external view returns (IJBProjects);
function fundingCycleStore() external view returns (IJBFundingCycleStore);
function tokenStore() external view returns (IJBTokenStore);
function splitsStore() external view returns (IJBSplitsStore);
function directory() external view returns (IJBDirectory);
function reservedTokenBalanceOf(uint256 _projectId, uint256 _reservedRate)
external
view
returns (uint256);
function distributionLimitOf(
uint256 _projectId,
uint256 _configuration,
IJBPaymentTerminal _terminal,
address _token
) external view returns (uint256 distributionLimit, uint256 distributionLimitCurrency);
function overflowAllowanceOf(
uint256 _projectId,
uint256 _configuration,
IJBPaymentTerminal _terminal,
address _token
) external view returns (uint256 overflowAllowance, uint256 overflowAllowanceCurrency);
function totalOutstandingTokensOf(uint256 _projectId, uint256 _reservedRate)
external
view
returns (uint256);
function currentFundingCycleOf(uint256 _projectId)
external
returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);
function queuedFundingCycleOf(uint256 _projectId)
external
returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);
function launchProjectFor(
address _owner,
JBProjectMetadata calldata _projectMetadata,
JBFundingCycleData calldata _data,
JBFundingCycleMetadata calldata _metadata,
uint256 _mustStartAtOrAfter,
JBGroupedSplits[] memory _groupedSplits,
JBFundAccessConstraints[] memory _fundAccessConstraints,
IJBPaymentTerminal[] memory _terminals,
string calldata _memo
) external returns (uint256 projectId);
function launchFundingCyclesFor(
uint256 _projectId,
JBFundingCycleData calldata _data,
JBFundingCycleMetadata calldata _metadata,
uint256 _mustStartAtOrAfter,
JBGroupedSplits[] memory _groupedSplits,
JBFundAccessConstraints[] memory _fundAccessConstraints,
IJBPaymentTerminal[] memory _terminals,
string calldata _memo
) external returns (uint256 configuration);
function reconfigureFundingCyclesOf(
uint256 _projectId,
JBFundingCycleData calldata _data,
JBFundingCycleMetadata calldata _metadata,
uint256 _mustStartAtOrAfter,
JBGroupedSplits[] memory _groupedSplits,
JBFundAccessConstraints[] memory _fundAccessConstraints,
string calldata _memo
) external returns (uint256);
function issueTokenFor(
uint256 _projectId,
string calldata _name,
string calldata _symbol
) external returns (IJBToken token);
function changeTokenOf(
uint256 _projectId,
IJBToken _token,
address _newOwner
) external;
function mintTokensOf(
uint256 _projectId,
uint256 _tokenCount,
address _beneficiary,
string calldata _memo,
bool _preferClaimedTokens,
bool _useReservedRate
) external returns (uint256 beneficiaryTokenCount);
function burnTokensOf(
address _holder,
uint256 _projectId,
uint256 _tokenCount,
string calldata _memo,
bool _preferClaimedTokens
) external;
function distributeReservedTokensOf(uint256 _projectId, string memory _memo)
external
returns (uint256);
function prepForMigrationOf(uint256 _projectId, IJBController _from) external;
function migrate(uint256 _projectId, IJBController _to) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBPaymentTerminal.sol';
import './IJBProjects.sol';
import './IJBFundingCycleStore.sol';
import './IJBController.sol';
interface IJBDirectory {
event SetController(uint256 indexed projectId, IJBController indexed controller, address caller);
event AddTerminal(uint256 indexed projectId, IJBPaymentTerminal indexed terminal, address caller);
event SetTerminals(uint256 indexed projectId, IJBPaymentTerminal[] terminals, address caller);
event SetPrimaryTerminal(
uint256 indexed projectId,
address indexed token,
IJBPaymentTerminal indexed terminal,
address caller
);
event SetIsAllowedToSetFirstController(address indexed addr, bool indexed flag, address caller);
function projects() external view returns (IJBProjects);
function fundingCycleStore() external view returns (IJBFundingCycleStore);
function controllerOf(uint256 _projectId) external view returns (IJBController);
function isAllowedToSetFirstController(address _address) external view returns (bool);
function terminalsOf(uint256 _projectId) external view returns (IJBPaymentTerminal[] memory);
function isTerminalOf(uint256 _projectId, IJBPaymentTerminal _terminal)
external
view
returns (bool);
function primaryTerminalOf(uint256 _projectId, address _token)
external
view
returns (IJBPaymentTerminal);
function setControllerOf(uint256 _projectId, IJBController _controller) external;
function setTerminalsOf(uint256 _projectId, IJBPaymentTerminal[] calldata _terminals) external;
function setPrimaryTerminalOf(
uint256 _projectId,
address _token,
IJBPaymentTerminal _terminal
) external;
function setIsAllowedToSetFirstController(address _address, bool _flag) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleStore.sol';
import './../enums/JBBallotState.sol';
interface IJBFundingCycleBallot {
function duration() external view returns (uint256);
function stateOf(
uint256 _projectId,
uint256 _configuration,
uint256 _start
) external view returns (JBBallotState);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleStore.sol';
import './IJBPayDelegate.sol';
import './IJBRedemptionDelegate.sol';
import './../structs/JBPayParamsData.sol';
import './../structs/JBRedeemParamsData.sol';
interface IJBFundingCycleDataSource {
function payParams(JBPayParamsData calldata _data)
external
view
returns (
uint256 weight,
string memory memo,
IJBPayDelegate delegate
);
function redeemParams(JBRedeemParamsData calldata _data)
external
view
returns (
uint256 reclaimAmount,
string memory memo,
IJBRedemptionDelegate delegate
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleBallot.sol';
import './../enums/JBBallotState.sol';
import './../structs/JBFundingCycle.sol';
import './../structs/JBFundingCycleData.sol';
interface IJBFundingCycleStore {
event Configure(
uint256 indexed configuration,
uint256 indexed projectId,
JBFundingCycleData data,
uint256 metadata,
uint256 mustStartAtOrAfter,
address caller
);
event Init(uint256 indexed configuration, uint256 indexed projectId, uint256 indexed basedOn);
function latestConfigurationOf(uint256 _projectId) external view returns (uint256);
function get(uint256 _projectId, uint256 _configuration)
external
view
returns (JBFundingCycle memory);
function queuedOf(uint256 _projectId) external view returns (JBFundingCycle memory);
function currentOf(uint256 _projectId) external view returns (JBFundingCycle memory);
function currentBallotStateOf(uint256 _projectId) external view returns (JBBallotState);
function configureFor(
uint256 _projectId,
JBFundingCycleData calldata _data,
uint256 _metadata,
uint256 _mustStartAtOrAfter
) external returns (JBFundingCycle memory fundingCycle);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBOperatorStore.sol';
interface IJBOperatable {
function operatorStore() external view returns (IJBOperatorStore);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../structs/JBOperatorData.sol';
interface IJBOperatorStore {
event SetOperator(
address indexed operator,
address indexed account,
uint256 indexed domain,
uint256[] permissionIndexes,
uint256 packed
);
function permissionsOf(
address _operator,
address _account,
uint256 _domain
) external view returns (uint256);
function hasPermission(
address _operator,
address _account,
uint256 _domain,
uint256 _permissionIndex
) external view returns (bool);
function hasPermissions(
address _operator,
address _account,
uint256 _domain,
uint256[] calldata _permissionIndexes
) external view returns (bool);
function setOperator(JBOperatorData calldata _operatorData) external;
function setOperators(JBOperatorData[] calldata _operatorData) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../structs/JBDidPayData.sol';
interface IJBPayDelegate {
function didPay(JBDidPayData calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBDirectory.sol';
interface IJBPaymentTerminal {
function acceptsToken(address _token) external view returns (bool);
function currencyForToken(address _token) external view returns (uint256);
function decimalsForToken(address _token) external view returns (uint256);
// Return value must be a fixed point number with 18 decimals.
function currentEthOverflowOf(uint256 _projectId) external view returns (uint256);
function pay(
uint256 _projectId,
uint256 _amount,
address _token,
address _beneficiary,
uint256 _minReturnedTokens,
bool _preferClaimedTokens,
string calldata _memo,
bytes calldata _metadata
) external payable returns (uint256 beneficiaryTokenCount);
function addToBalanceOf(
uint256 _projectId,
uint256 _amount,
address _token,
string calldata _memo
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import './IJBPaymentTerminal.sol';
import './IJBTokenUriResolver.sol';
import './../structs/JBProjectMetadata.sol';
import './IJBTokenUriResolver.sol';
interface IJBProjects is IERC721 {
event Create(
uint256 indexed projectId,
address indexed owner,
JBProjectMetadata metadata,
address caller
);
event SetMetadata(uint256 indexed projectId, JBProjectMetadata metadata, address caller);
event SetTokenUriResolver(IJBTokenUriResolver resolver, address caller);
function count() external view returns (uint256);
function metadataContentOf(uint256 _projectId, uint256 _domain)
external
view
returns (string memory);
function tokenUriResolver() external view returns (IJBTokenUriResolver);
function createFor(address _owner, JBProjectMetadata calldata _metadata)
external
returns (uint256 projectId);
function setMetadataOf(uint256 _projectId, JBProjectMetadata calldata _metadata) external;
function setTokenUriResolver(IJBTokenUriResolver _newResolver) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBFundingCycleStore.sol';
import './../structs/JBDidRedeemData.sol';
interface IJBRedemptionDelegate {
function didRedeem(JBDidRedeemData calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import '../structs/JBSplitAllocationData.sol';
interface IJBSplitAllocator {
function allocate(JBSplitAllocationData calldata _data) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBOperatorStore.sol';
import './IJBProjects.sol';
import './IJBDirectory.sol';
import './IJBSplitAllocator.sol';
import './../structs/JBSplit.sol';
interface IJBSplitsStore {
event SetSplit(
uint256 indexed projectId,
uint256 indexed domain,
uint256 indexed group,
JBSplit split,
address caller
);
function projects() external view returns (IJBProjects);
function directory() external view returns (IJBDirectory);
function splitsOf(
uint256 _projectId,
uint256 _domain,
uint256 _group
) external view returns (JBSplit[] memory);
function set(
uint256 _projectId,
uint256 _domain,
uint256 _group,
JBSplit[] memory _splits
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
interface IJBToken {
function decimals() external view returns (uint8);
function totalSupply(uint256 _projectId) external view returns (uint256);
function balanceOf(address _account, uint256 _projectId) external view returns (uint256);
function mint(
uint256 _projectId,
address _account,
uint256 _amount
) external;
function burn(
uint256 _projectId,
address _account,
uint256 _amount
) external;
function approve(
uint256,
address _spender,
uint256 _amount
) external;
function transfer(
uint256 _projectId,
address _to,
uint256 _amount
) external;
function transferFrom(
uint256 _projectId,
address _from,
address _to,
uint256 _amount
) external;
function transferOwnership(address _newOwner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './IJBProjects.sol';
import './IJBToken.sol';
interface IJBTokenStore {
event Issue(
uint256 indexed projectId,
IJBToken indexed token,
string name,
string symbol,
address caller
);
event Mint(
address indexed holder,
uint256 indexed projectId,
uint256 amount,
bool tokensWereClaimed,
bool preferClaimedTokens,
address caller
);
event Burn(
address indexed holder,
uint256 indexed projectId,
uint256 amount,
uint256 initialUnclaimedBalance,
uint256 initialClaimedBalance,
bool preferClaimedTokens,
address caller
);
event Claim(
address indexed holder,
uint256 indexed projectId,
uint256 initialUnclaimedBalance,
uint256 amount,
address caller
);
event ShouldRequireClaim(uint256 indexed projectId, bool indexed flag, address caller);
event Change(
uint256 indexed projectId,
IJBToken indexed newToken,
IJBToken indexed oldToken,
address owner,
address caller
);
event Transfer(
address indexed holder,
uint256 indexed projectId,
address indexed recipient,
uint256 amount,
address caller
);
function tokenOf(uint256 _projectId) external view returns (IJBToken);
function projectOf(IJBToken _token) external view returns (uint256);
function projects() external view returns (IJBProjects);
function unclaimedBalanceOf(address _holder, uint256 _projectId) external view returns (uint256);
function unclaimedTotalSupplyOf(uint256 _projectId) external view returns (uint256);
function totalSupplyOf(uint256 _projectId) external view returns (uint256);
function balanceOf(address _holder, uint256 _projectId) external view returns (uint256 _result);
function requireClaimFor(uint256 _projectId) external view returns (bool);
function issueFor(
uint256 _projectId,
string calldata _name,
string calldata _symbol
) external returns (IJBToken token);
function changeFor(
uint256 _projectId,
IJBToken _token,
address _newOwner
) external returns (IJBToken oldToken);
function burnFrom(
address _holder,
uint256 _projectId,
uint256 _amount,
bool _preferClaimedTokens
) external;
function mintFor(
address _holder,
uint256 _projectId,
uint256 _amount,
bool _preferClaimedTokens
) external;
function shouldRequireClaimingFor(uint256 _projectId, bool _flag) external;
function claimFor(
address _holder,
uint256 _projectId,
uint256 _amount
) external;
function transferFrom(
address _holder,
uint256 _projectId,
address _recipient,
uint256 _amount
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
interface IJBTokenUriResolver {
function getUri(uint256 _projectId) external view returns (string memory tokenUri);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
library JBOperations {
uint256 public constant RECONFIGURE = 1;
uint256 public constant REDEEM = 2;
uint256 public constant MIGRATE_CONTROLLER = 3;
uint256 public constant MIGRATE_TERMINAL = 4;
uint256 public constant PROCESS_FEES = 5;
uint256 public constant SET_METADATA = 6;
uint256 public constant ISSUE = 7;
uint256 public constant CHANGE_TOKEN = 8;
uint256 public constant MINT = 9;
uint256 public constant BURN = 10;
uint256 public constant CLAIM = 11;
uint256 public constant TRANSFER = 12;
uint256 public constant REQUIRE_CLAIM = 13;
uint256 public constant SET_CONTROLLER = 14;
uint256 public constant SET_TERMINALS = 15;
uint256 public constant SET_PRIMARY_TERMINAL = 16;
uint256 public constant USE_ALLOWANCE = 17;
uint256 public constant SET_SPLITS = 18;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
library JBSplitsGroups {
uint256 public constant ETH_PAYOUT = 1;
uint256 public constant RESERVED_TOKENS = 2;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBTokenAmount.sol';
struct JBDidPayData {
// The address from which the payment originated.
address payer;
// The ID of the project for which the payment was made.
uint256 projectId;
// The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
JBTokenAmount amount;
// The number of project tokens minted for the beneficiary.
uint256 projectTokenCount;
// The address to which the tokens were minted.
address beneficiary;
// The memo that is being emitted alongside the payment.
string memo;
// Metadata to send to the delegate.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBTokenAmount.sol';
struct JBDidRedeemData {
// The holder of the tokens being redeemed.
address holder;
// The project to which the redeemed tokens are associated.
uint256 projectId;
// The number of project tokens being redeemed.
uint256 projectTokenCount;
// The reclaimed amount. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
JBTokenAmount reclaimedAmount;
// The address to which the reclaimed amount will be sent.
address payable beneficiary;
// The memo that is being emitted alongside the redemption.
string memo;
// Metadata to send to the delegate.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBPaymentTerminal.sol';
struct JBFundAccessConstraints {
// The terminal within which the distribution limit and the overflow allowance applies.
IJBPaymentTerminal terminal;
// The token for which the fund access constraints apply.
address token;
// The amount of the distribution limit, as a fixed point number with the same number of decimals as the terminal within which the limit applies.
uint256 distributionLimit;
// The currency of the distribution limit.
uint256 distributionLimitCurrency;
// The amount of the allowance, as a fixed point number with the same number of decimals as the terminal within which the allowance applies.
uint256 overflowAllowance;
// The currency of the overflow allowance.
uint256 overflowAllowanceCurrency;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBFundingCycleBallot.sol';
struct JBFundingCycle {
// The funding cycle number for each project.
// Each funding cycle has a number that is an increment of the cycle that directly preceded it.
// Each project's first funding cycle has a number of 1.
uint256 number;
// The timestamp when the parameters for this funding cycle were configured.
// This value will stay the same for subsequent funding cycles that roll over from an originally configured cycle.
uint256 configuration;
// The `configuration` of the funding cycle that was active when this cycle was created.
uint256 basedOn;
// The timestamp marking the moment from which the funding cycle is considered active.
// It is a unix timestamp measured in seconds.
uint256 start;
// The number of seconds the funding cycle lasts for, after which a new funding cycle will start.
// A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties.
// If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active β any proposed changes will apply to the subsequent cycle.
// If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`.
uint256 duration;
// A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on.
// For example, payment terminals can use this to determine how many tokens should be minted when a payment is received.
uint256 weight;
// A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`.
// If it's 0, each funding cycle will have equal weight.
// If the number is 90%, the next funding cycle will have a 10% smaller weight.
// This weight is out of `JBConstants.MAX_DISCOUNT_RATE`.
uint256 discountRate;
// An address of a contract that says whether a proposed reconfiguration should be accepted or rejected.
// It can be used to create rules around how a project owner can change funding cycle parameters over time.
IJBFundingCycleBallot ballot;
// Extra data that can be associated with a funding cycle.
uint256 metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBFundingCycleBallot.sol';
struct JBFundingCycleData {
// The number of seconds the funding cycle lasts for, after which a new funding cycle will start.
// A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties.
// If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active β any proposed changes will apply to the subsequent cycle.
// If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`.
uint256 duration;
// A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on.
// For example, payment terminals can use this to determine how many tokens should be minted when a payment is received.
uint256 weight;
// A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`.
// If it's 0, each funding cycle will have equal weight.
// If the number is 90%, the next funding cycle will have a 10% smaller weight.
// This weight is out of `JBConstants.MAX_DISCOUNT_RATE`.
uint256 discountRate;
// An address of a contract that says whether a proposed reconfiguration should be accepted or rejected.
// It can be used to create rules around how a project owner can change funding cycle parameters over time.
IJBFundingCycleBallot ballot;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBFundingCycleDataSource.sol';
struct JBFundingCycleMetadata {
// The reserved rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_RESERVED_RATE`.
uint256 reservedRate;
// The redemption rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`.
uint256 redemptionRate;
// The redemption rate to use during an active ballot of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`.
uint256 ballotRedemptionRate;
// If the pay functionality should be paused during the funding cycle.
bool pausePay;
// If the distribute functionality should be paused during the funding cycle.
bool pauseDistributions;
// If the redeem functionality should be paused during the funding cycle.
bool pauseRedeem;
// If the burn functionality should be paused during the funding cycle.
bool pauseBurn;
// If the mint functionality should be allowed during the funding cycle.
bool allowMinting;
// If changing tokens should be allowed during this funding cycle.
bool allowChangeToken;
// If migrating terminals should be allowed during this funding cycle.
bool allowTerminalMigration;
// If migrating controllers should be allowed during this funding cycle.
bool allowControllerMigration;
// If setting terminals should be allowed during this funding cycle.
bool allowSetTerminals;
// If setting a new controller should be allowed during this funding cycle.
bool allowSetController;
// If fees should be held during this funding cycle.
bool holdFees;
// If redemptions should use the project's balance held in all terminals instead of the project's local terminal balance from which the redemption is being fulfilled.
bool useTotalOverflowForRedemptions;
// If the data source should be used for pay transactions during this funding cycle.
bool useDataSourceForPay;
// If the data source should be used for redeem transactions during this funding cycle.
bool useDataSourceForRedeem;
// The data source to use during this funding cycle.
IJBFundingCycleDataSource dataSource;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBSplit.sol';
import '../libraries/JBSplitsGroups.sol';
struct JBGroupedSplits {
// The group indentifier.
uint256 group;
// The splits to associate with the group.
JBSplit[] splits;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
struct JBOperatorData {
// The address of the operator.
address operator;
// The domain within which the operator is being given permissions.
// A domain of 0 is a wildcard domain, which gives an operator access to all domains.
uint256 domain;
// The indexes of the permissions the operator is being given.
uint256[] permissionIndexes;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBPaymentTerminal.sol';
import './JBTokenAmount.sol';
struct JBPayParamsData {
// The terminal that is facilitating the payment.
IJBPaymentTerminal terminal;
// The address from which the payment originated.
address payer;
// The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
JBTokenAmount amount;
// The ID of the project being paid.
uint256 projectId;
// The weight of the funding cycle during which the payment is being made.
uint256 weight;
// The reserved rate of the funding cycle during which the payment is being made.
uint256 reservedRate;
// The memo that was sent alongside the payment.
string memo;
// Arbitrary metadata provided by the payer.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
struct JBProjectMetadata {
// Metadata content.
string content;
// The domain within which the metadata applies.
uint256 domain;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBPaymentTerminal.sol';
struct JBRedeemParamsData {
// The terminal that is facilitating the redemption.
IJBPaymentTerminal terminal;
// The holder of the tokens being redeemed.
address holder;
// The ID of the project whos tokens are being redeemed.
uint256 projectId;
// The proposed number of tokens being redeemed, as a fixed point number with 18 decimals.
uint256 tokenCount;
// The total supply of tokens used in the calculation, as a fixed point number with 18 decimals.
uint256 totalSupply;
// The amount of overflow used in the reclaim amount calculation.
uint256 overflow;
// The number of decimals included in the reclaim amount fixed point number.
uint256 decimals;
// The currency that the reclaim amount is expected to be in terms of.
uint256 currency;
// The amount that should be reclaimed by the redeemer using the protocol's standard bonding curve redemption formula.
uint256 reclaimAmount;
// If overflow across all of a project's terminals is being used when making redemptions.
bool useTotalOverflow;
// The redemption rate of the funding cycle during which the redemption is being made.
uint256 redemptionRate;
// The ballot redemption rate of the funding cycle during which the redemption is being made.
uint256 ballotRedemptionRate;
// The proposed memo that is being emitted alongside the redemption.
string memo;
// Arbitrary metadata provided by the redeemer.
bytes metadata;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './../interfaces/IJBSplitAllocator.sol';
struct JBSplit {
// A flag that only has effect if a projectId is also specified, and the project has a token contract attached.
// If so, this flag indicates if the tokens that result from making a payment to the project should be delivered claimed into the beneficiary's wallet, or unclaimed to save gas.
bool preferClaimed;
// A flag indicating if a distribution to a project should prefer triggering it's addToBalance function instead of its pay function.
bool preferAddToBalance;
// The percent of the whole group that this split occupies. This number is out of `JBConstants.SPLITS_TOTAL_PERCENT`.
uint256 percent;
// If an allocator is not set but a projectId is set, funds will be sent to the protocol treasury belonging to the project who's ID is specified.
// Resulting tokens will be routed to the beneficiary with the claimed token preference respected.
uint256 projectId;
// The role the of the beneficary depends on whether or not projectId is specified, and whether or not an allocator is specified.
// If allocator is set, the beneficiary will be forwarded to the allocator for it to use.
// If allocator is not set but projectId is set, the beneficiary is the address to which the project's tokens will be sent that result from a payment to it.
// If neither allocator or projectId are set, the beneficiary is where the funds from the split will be sent.
address payable beneficiary;
// Specifies if the split should be unchangeable until the specified time, with the exception of extending the locked period.
uint256 lockedUntil;
// If an allocator is specified, funds will be sent to the allocator contract along with all properties of this split.
IJBSplitAllocator allocator;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import './JBSplit.sol';
import './JBTokenAmount.sol';
struct JBSplitAllocationData {
// The token being sent to the split allocator.
address token;
// The amount being sent to the split allocator, as a fixed point number.
uint256 amount;
// The number of decimals in the amount.
uint256 decimals;
// The project to which the split belongs.
uint256 projectId;
// The group to which the split belongs.
uint256 group;
// The split that caused the allocation.
JBSplit split;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
struct JBTokenAmount {
// The token the payment was made in.
address token;
// The amount of tokens that was paid, as a fixed point number.
uint256 value;
// The number of decimals included in the value fixed point number.
uint256 decimals;
// The expected currency of the value.
uint256 currency;
} | Returns the current total supply of votes./ | function _getTotalSupply() internal view virtual returns (uint256) {
return _totalCheckpoints.latest();
}
| 634,756 |
./full_match/1/0xCbb07CB17f3EF0A10fA881C5E961A29d8367DA37/sources/contracts/words_final.sol | Check whether tokens are still available return the available token count | function availableTokenCount() public view returns (uint256) {
return maxSupply - totalSupply();
}
| 4,857,679 |
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
/**
* @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.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice 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 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/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @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: contracts/lib/TimeLockUpgradeV2.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title TimeLockUpgradeV2
* @author Set Protocol
*
* The TimeLockUpgradeV2 contract contains a modifier for handling minimum time period updates
*
* CHANGELOG:
* - Requires that the caller is the owner
* - New function to allow deletion of existing timelocks
* - Added upgradeData to UpgradeRegistered event
*/
contract TimeLockUpgradeV2 is
Ownable
{
using SafeMath for uint256;
/* ============ State Variables ============ */
// Timelock Upgrade Period in seconds
uint256 public timeLockPeriod;
// Mapping of maps hash of registered upgrade to its registration timestam
mapping(bytes32 => uint256) public timeLockedUpgrades;
/* ============ Events ============ */
event UpgradeRegistered(
bytes32 indexed _upgradeHash,
uint256 _timestamp,
bytes _upgradeData
);
event RemoveRegisteredUpgrade(
bytes32 indexed _upgradeHash
);
/* ============ Modifiers ============ */
modifier timeLockUpgrade() {
require(
isOwner(),
"TimeLockUpgradeV2: The caller must be the owner"
);
// If the time lock period is 0, then allow non-timebound upgrades.
// This is useful for initialization of the protocol and for testing.
if (timeLockPeriod > 0) {
// The upgrade hash is defined by the hash of the transaction call data,
// which uniquely identifies the function as well as the passed in arguments.
bytes32 upgradeHash = keccak256(
abi.encodePacked(
msg.data
)
);
uint256 registrationTime = timeLockedUpgrades[upgradeHash];
// If the upgrade hasn't been registered, register with the current time.
if (registrationTime == 0) {
timeLockedUpgrades[upgradeHash] = block.timestamp;
emit UpgradeRegistered(
upgradeHash,
block.timestamp,
msg.data
);
return;
}
require(
block.timestamp >= registrationTime.add(timeLockPeriod),
"TimeLockUpgradeV2: Time lock period must have elapsed."
);
// Reset the timestamp to 0
timeLockedUpgrades[upgradeHash] = 0;
}
// Run the rest of the upgrades
_;
}
/* ============ Function ============ */
/**
* Removes an existing upgrade.
*
* @param _upgradeHash Keccack256 hash that uniquely identifies function called and arguments
*/
function removeRegisteredUpgrade(
bytes32 _upgradeHash
)
external
onlyOwner
{
require(
timeLockedUpgrades[_upgradeHash] != 0,
"TimeLockUpgradeV2.removeRegisteredUpgrade: Upgrade hash must be registered"
);
// Reset the timestamp to 0
timeLockedUpgrades[_upgradeHash] = 0;
emit RemoveRegisteredUpgrade(
_upgradeHash
);
}
/**
* Change timeLockPeriod period. Generally called after initially settings have been set up.
*
* @param _timeLockPeriod Time in seconds that upgrades need to be evaluated before execution
*/
function setTimeLockPeriod(
uint256 _timeLockPeriod
)
external
onlyOwner
{
// Only allow setting of the timeLockPeriod if the period is greater than the existing
require(
_timeLockPeriod > timeLockPeriod,
"TimeLockUpgradeV2: New period must be greater than existing"
);
timeLockPeriod = _timeLockPeriod;
}
}
// File: contracts/lib/AddressArrayUtils.sol
// Pulled in from Cryptofin Solidity package in order to control Solidity compiler version
// https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol
pragma solidity 0.5.7;
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (0, false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
bool isIn;
(, isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Returns the array with a appended to A.
* @param A The first array
* @param a The value to append
* @return Returns A appended by a
*/
function append(address[] memory A, address a) internal pure returns (address[] memory) {
address[] memory newAddresses = new address[](A.length + 1);
for (uint256 i = 0; i < A.length; i++) {
newAddresses[i] = A[i];
}
newAddresses[A.length] = a;
return newAddresses;
}
/**
* Returns the intersection of two arrays. Arrays are treated as collections, so duplicates are kept.
* @param A The first array
* @param B The second array
* @return The intersection of the two arrays
*/
function intersect(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 newLength = 0;
for (uint256 i = 0; i < length; i++) {
if (contains(B, A[i])) {
includeMap[i] = true;
newLength++;
}
}
address[] memory newAddresses = new address[](newLength);
uint256 j = 0;
for (uint256 k = 0; k < length; k++) {
if (includeMap[k]) {
newAddresses[j] = A[k];
j++;
}
}
return newAddresses;
}
/**
* Returns the union of the two arrays. Order is not guaranteed.
* @param A The first array
* @param B The second array
* @return The union of the two arrays
*/
function union(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
address[] memory leftDifference = difference(A, B);
address[] memory rightDifference = difference(B, A);
address[] memory intersection = intersect(A, B);
return extend(leftDifference, extend(intersection, rightDifference));
}
/**
* Computes the difference of two arrays. Assumes there are no duplicates.
* @param A The first array
* @param B The second array
* @return The difference of the two arrays
*/
function difference(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 count = 0;
// First count the new length because can't push for in-memory arrays
for (uint256 i = 0; i < length; i++) {
address e = A[i];
if (!contains(B, e)) {
includeMap[i] = true;
count++;
}
}
address[] memory newAddresses = new address[](count);
uint256 j = 0;
for (uint256 k = 0; k < length; k++) {
if (includeMap[k]) {
newAddresses[j] = A[k];
j++;
}
}
return newAddresses;
}
/**
* Removes specified index from array
* Resulting ordering is not guaranteed
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* @return Returns the new array
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert();
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* Returns whether or not there's a duplicate. Runs in O(n^2).
* @param A Array to search
* @return Returns true if duplicate, false otherwise
*/
function hasDuplicate(address[] memory A) internal pure returns (bool) {
if (A.length == 0) {
return false;
}
for (uint256 i = 0; i < A.length - 1; i++) {
for (uint256 j = i + 1; j < A.length; j++) {
if (A[i] == A[j]) {
return true;
}
}
}
return false;
}
/**
* Returns whether the two arrays are equal.
* @param A The first array
* @param B The second array
* @return True is the arrays are equal, false if not.
*/
function isEqual(address[] memory A, address[] memory B) internal pure returns (bool) {
if (A.length != B.length) {
return false;
}
for (uint256 i = 0; i < A.length; i++) {
if (A[i] != B[i]) {
return false;
}
}
return true;
}
}
// File: contracts/lib/OracleWhiteList.sol
/*
Copyright 2019 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title OracleWhiteList
* @author Set Protocol
*
* WhiteList that matches whitelisted tokens to their on chain price oracle
*/
contract OracleWhiteList is
Ownable,
TimeLockUpgradeV2
{
using AddressArrayUtils for address[];
/* ============ State Variables ============ */
address[] public addresses;
mapping(address => address) public oracleWhiteList;
/* ============ Events ============ */
event TokenOraclePairAdded(
address _tokenAddress,
address _oracleAddress
);
event TokenOraclePairRemoved(
address _tokenAddress,
address _oracleAddress
);
/* ============ Constructor ============ */
/**
* Constructor function for OracleWhiteList
*
* Allow initial addresses to be passed in so a separate transaction is not required for each.
* Each token address passed is matched with a corresponding oracle address at the same index.
* The _initialTokenAddresses and _initialOracleAddresses arrays must be equal length.
*
* @param _initialTokenAddresses Starting set of toke addresses to whitelist
* @param _initialOracleAddresses Starting set of oracle addresses to whitelist
*/
constructor(
address[] memory _initialTokenAddresses,
address[] memory _initialOracleAddresses
)
public
{
require(
_initialTokenAddresses.length == _initialOracleAddresses.length,
"OracleWhiteList.constructor: Token and Oracle array lengths must match."
);
// Add each of initial addresses to state
for (uint256 i = 0; i < _initialTokenAddresses.length; i++) {
address tokenAddressToAdd = _initialTokenAddresses[i];
addresses.push(tokenAddressToAdd);
oracleWhiteList[tokenAddressToAdd] = _initialOracleAddresses[i];
}
}
/* ============ External Functions ============ */
/**
* Add an address to the whitelist
*
* @param _tokenAddress Token address to add to the whitelist
* @param _oracleAddress Oracle address to add to the whitelist under _tokenAddress
*/
function addTokenOraclePair(
address _tokenAddress,
address _oracleAddress
)
external
onlyOwner
timeLockUpgrade
{
require(
oracleWhiteList[_tokenAddress] == address(0),
"OracleWhiteList.addTokenOraclePair: Token and Oracle pair already exists."
);
addresses.push(_tokenAddress);
oracleWhiteList[_tokenAddress] = _oracleAddress;
emit TokenOraclePairAdded(_tokenAddress, _oracleAddress);
}
/**
* Remove a token oracle pair from the whitelist
*
* @param _tokenAddress Token address to remove to the whitelist
*/
function removeTokenOraclePair(
address _tokenAddress
)
external
onlyOwner
{
address oracleAddress = oracleWhiteList[_tokenAddress];
require(
oracleAddress != address(0),
"OracleWhiteList.removeTokenOraclePair: Token Address is not current whitelisted."
);
addresses = addresses.remove(_tokenAddress);
oracleWhiteList[_tokenAddress] = address(0);
emit TokenOraclePairRemoved(_tokenAddress, oracleAddress);
}
/**
* Edit oracle address associated with a token address
*
* @param _tokenAddress Token address to add to the whitelist
* @param _oracleAddress Oracle address to add to the whitelist under _tokenAddress
*/
function editTokenOraclePair(
address _tokenAddress,
address _oracleAddress
)
external
onlyOwner
timeLockUpgrade
{
require(
oracleWhiteList[_tokenAddress] != address(0),
"OracleWhiteList.editTokenOraclePair: Token and Oracle pair must exist."
);
// Set new oracle address for passed token address
oracleWhiteList[_tokenAddress] = _oracleAddress;
emit TokenOraclePairAdded(
_tokenAddress,
_oracleAddress
);
}
/**
* Return array of all whitelisted addresses
*
* @return address[] Array of addresses
*/
function validAddresses()
external
view
returns (address[] memory)
{
return addresses;
}
/**
* Return array of oracle addresses based on passed in token addresses
*
* @param _tokenAddresses Array of token addresses to get oracle addresses for
* @return address[] Array of oracle addresses
*/
function getOracleAddressesByToken(
address[] calldata _tokenAddresses
)
external
view
returns (address[] memory)
{
// Get length of passed array
uint256 arrayLength = _tokenAddresses.length;
// Check that passed array length is greater than 0
require(
arrayLength > 0,
"OracleWhiteList.getOracleAddressesByToken: Array length must be greater than 0."
);
// Instantiate oracle addresses array
address[] memory oracleAddresses = new address[](arrayLength);
for (uint256 i = 0; i < arrayLength; i++) {
// Get oracle address for token address at index i
oracleAddresses[i] = getOracleAddressByToken(
_tokenAddresses[i]
);
}
return oracleAddresses;
}
/**
* Return oracle address associated with a passed token address
*
* @param _tokenAddress Address of token
* @return address Address of oracle associated with token
*/
function getOracleAddressByToken(
address _tokenAddress
)
public
view
returns (address)
{
// Require token address to have matching oracle address
require(
oracleWhiteList[_tokenAddress] != address(0),
"OracleWhiteList.getOracleAddressFromToken: No Oracle for that address."
);
// Return oracle address associated with token address
return oracleWhiteList[_tokenAddress];
}
/**
* Verifies an array of addresses against the whitelist
*
* @param _tokenAddresses Array of token addresses to check if oracle exists
* @return bool Whether all addresses in the list are whitelsited
*/
function areValidAddresses(
address[] calldata _tokenAddresses
)
external
view
returns (bool)
{
// Get length of passed array
uint256 arrayLength = _tokenAddresses.length;
// Check that passed array length is greater than 0
require(
arrayLength > 0,
"OracleWhiteList.areValidAddresses: Array length must be greater than 0."
);
for (uint256 i = 0; i < arrayLength; i++) {
// Return false if token address doesn't have matching oracle address
if (oracleWhiteList[_tokenAddresses[i]] == address(0)) {
return false;
}
}
return true;
}
} | Edit oracle address associated with a token address _tokenAddress Token address to add to the whitelist _oracleAddress Oracle address to add to the whitelist under _tokenAddress/ Set new oracle address for passed token address | function editTokenOraclePair(
address _tokenAddress,
address _oracleAddress
)
external
onlyOwner
timeLockUpgrade
{
require(
oracleWhiteList[_tokenAddress] != address(0),
"OracleWhiteList.editTokenOraclePair: Token and Oracle pair must exist."
);
oracleWhiteList[_tokenAddress] = _oracleAddress;
emit TokenOraclePairAdded(
_tokenAddress,
_oracleAddress
);
}
| 14,090,941 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
//
abstract contract Context {
function _MSGSENDER742() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA476() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
//
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED603(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER742();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED603(address(0), msgSender);
}
function OWNER943() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER460() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER742(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP291() public virtual ONLYOWNER460 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED603(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP407(address newOwner) public virtual ONLYOWNER460 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED603(_owner, newOwner);
_owner = newOwner;
}
}
abstract contract PriceProvider is Ownable {
address public manager;
string public providerName;
uint8 public constant decimals686 = 2; // decimals of ethereum price //inject NONSTANDARD NAMING
bool public updateRequred;
constructor(string memory _providerName, address _manager, bool _updateRequred) public Ownable() {
providerName = _providerName;
manager = _manager;
updateRequred = _updateRequred;
}
function SETMANAGER980(address _manager) external ONLYOWNER460 { //inject NONSTANDARD NAMING
manager = _manager;
}
function LASTPRICE690() public virtual view returns (uint32); //inject NONSTANDARD NAMING
}
//
interface IERC20 {
function TOTALSUPPLY861() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF276(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER827(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE661(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE898(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM273(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER185(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL8(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
abstract contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME190() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL403() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS571() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
// 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 resolution887 = 112; //inject NONSTANDARD NAMING
// encode a uint112 as a UQ112x112
function ENCODE375(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
return uq112x112(uint224(x) << resolution887);
}
// encodes a uint144 as a UQ144x112
function ENCODE144305(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING
return uq144x112(uint256(x) << resolution887);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function DIV530(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
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 MUL252(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING
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 FRACTION125(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << resolution887) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function DECODE122(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING
return uint112(self._x >> resolution887);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function DECODE144956(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING
return uint144(self._x >> resolution887);
}
}
interface IUniswapV2Pair {
event APPROVAL8(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER185(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME190() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL403() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS571() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY861() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF276(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE661(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE898(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER827(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM273(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR374() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH748() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES344(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT537(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT421(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN632(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP642( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC872(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY496() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY810() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0628() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1909() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES186() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST525() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST405() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST975() external view returns (uint); //inject NONSTANDARD NAMING
function MINT537(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN439(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP853(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM750(address to) external; //inject NONSTANDARD NAMING
function SYNC911() external; //inject NONSTANDARD NAMING
function INITIALIZE196(address, address) external; //inject NONSTANDARD NAMING
}
// 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 CURRENTBLOCKTIMESTAMP220() internal view returns (uint32) { //inject NONSTANDARD NAMING
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function CURRENTCUMULATIVEPRICES765( //inject NONSTANDARD NAMING
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = CURRENTBLOCKTIMESTAMP220();
price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST525();
price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST405();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES186();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.FRACTION125(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.FRACTION125(reserve0, reserve1)._x) * timeElapsed;
}
}
}
//
library SafeMath {
function ADD549(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB879(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB879(a, b, "SafeMath: subtraction overflow");
}
function SUB879(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 MUL252(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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 DIV530(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV530(a, b, "SafeMath: division by zero");
}
function DIV530(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
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 MOD417(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD417(a, b, "SafeMath: modulo by zero");
}
function MOD417(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function SORTTOKENS809(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING
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 PAIRFOR391(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING
(address token0, address token1) = SORTTOKENS809(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 GETRESERVES186(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING
(address token0,) = SORTTOKENS809(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR391(factory, tokenA, tokenB)).GETRESERVES186();
(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 QUOTE986(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.MUL252(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function GETAMOUNTOUT221(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.MUL252(997);
uint numerator = amountInWithFee.MUL252(reserveOut);
uint denominator = reserveIn.MUL252(1000).ADD549(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function GETAMOUNTIN900(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.MUL252(amountOut).MUL252(1000);
uint denominator = reserveOut.SUB879(amountOut).MUL252(997);
amountIn = (numerator / denominator).ADD549(1);
}
// performs chained getAmountOut calculations on any number of pairs
function GETAMOUNTSOUT486(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING
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) = GETRESERVES186(factory, path[i], path[i + 1]);
amounts[i + 1] = GETAMOUNTOUT221(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function GETAMOUNTSIN740(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING
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) = GETRESERVES186(factory, path[i - 1], path[i]);
amounts[i - 1] = GETAMOUNTIN900(amounts[i], reserveIn, reserveOut);
}
}
}
contract PriceProviderUniswap is PriceProvider {
using FixedPoint for *;
using SafeMath for uint;
IUniswapV2Pair public immutable pair;
address immutable weth;
address public immutable stableToken;
uint priceCumulativeLast;
uint price1CumulativeLast;
uint32 blockTimestampLast;
bool wethIsToken0;
FixedPoint.uq112x112 priceAverage;
constructor(address _manager, address _factory, address _weth, address _stableToken) public PriceProvider("Uniswap", _manager, true) {
IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.PAIRFOR391(_factory, _weth, _stableToken));
pair = _pair;
weth = _weth;
if (_weth == _pair.TOKEN0628()) {
wethIsToken0 = true;
} else {
wethIsToken0 = false;
}
stableToken = _stableToken;
if (wethIsToken0 == true) {
priceCumulativeLast = _pair.PRICE0CUMULATIVELAST525();
} else {
priceCumulativeLast = _pair.PRICE1CUMULATIVELAST405();
}
(,,blockTimestampLast) = _pair.GETRESERVES186();
}
function UPDATE754() external { //inject NONSTANDARD NAMING
require(msg.sender == manager, "manager!");
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES765(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
if (wethIsToken0 == true) {
priceAverage = FixedPoint.uq112x112(uint224((price0Cumulative - priceCumulativeLast) / timeElapsed));
priceCumulativeLast = price0Cumulative;
} else {
priceAverage = FixedPoint.uq112x112(uint224((price1Cumulative - priceCumulativeLast) / timeElapsed));
priceCumulativeLast = price1Cumulative;
}
blockTimestampLast = blockTimestamp;
}
function LASTPRICE690() public override view returns (uint32 price) { //inject NONSTANDARD NAMING
uint amountOut = priceAverage.MUL252(1 ether).DECODE144956();
uint8 stableTokenDecimals = ERC20Detailed(stableToken).DECIMALS571();
if (stableTokenDecimals >= decimals686) {
price = uint32(amountOut.DIV530(10 ** uint(stableTokenDecimals - decimals686)));
} else {
price = uint32(amountOut.MUL252(10 ** uint(decimals686 - stableTokenDecimals)));
}
}
} | inject NONSTANDARD NAMING | function TOTALSUPPLY861() external view returns (uint); | 12,546,417 |
/**
*Submitted for verification at Etherscan.io on 2021-04-22
*/
// SPDX-License-Identifier: MIT
/*
This is a Stacker.vc FarmTreasury version 1 contract. It deploys a rebase token where it rebases to be equivalent to it's underlying token. 1 stackUSDT = 1 USDT.
The underlying assets are used to farm on different smart contract and produce yield via the ever-expanding DeFi ecosystem.
THANKS! To Lido DAO for the inspiration in more ways than one, but especially for a lot of the code here.
If you haven't already, stake your ETH for ETH2.0 with Lido.fi!
Also thanks for Aragon for hosting our Stacker Ventures DAO, and for more inspiration!
*/
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.11;
/*
* @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;
}
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
/**
* @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;
}
}
/**
* @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);
}
/**
* @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");
}
}
}
abstract contract FarmTokenV1 is IERC20 {
using SafeMath for uint256;
using Address for address;
// shares are how a users balance is generated. For rebase tokens, balances are always generated at runtime, while shares stay constant.
// shares is your proportion of the total pool of invested UnderlyingToken
// shares are like a Compound.finance cToken, while our token balances are like an Aave aToken.
mapping(address => uint256) private shares;
mapping(address => mapping (address => uint256)) private allowances;
uint256 public totalShares;
string public name;
string public symbol;
string public underlying;
address public underlyingContract;
uint8 public decimals;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(string memory _name, uint8 _decimals, address _underlyingContract) public {
name = string(abi.encodePacked(abi.encodePacked("Stacker Ventures ", _name), " v1"));
symbol = string(abi.encodePacked("stack", _name));
underlying = _name;
decimals = _decimals;
underlyingContract = _underlyingContract;
}
// 1 stackToken = 1 underlying token
function totalSupply() external override view returns (uint256){
return _getTotalUnderlying();
}
function totalUnderlying() external view returns (uint256){
return _getTotalUnderlying();
}
function balanceOf(address _account) public override view returns (uint256){
return getUnderlyingForShares(_sharesOf(_account));
}
// transfer tokens, not shares
function transfer(address _recipient, uint256 _amount) external override returns (bool){
_verify(msg.sender, _amount);
_transfer(msg.sender, _recipient, _amount);
return true;
}
function transferFrom(address _sender, address _recipient, uint256 _amount) external override returns (bool){
_verify(_sender, _amount);
uint256 _currentAllowance = allowances[_sender][msg.sender];
require(_currentAllowance >= _amount, "FARMTOKENV1: not enough allowance");
_transfer(_sender, _recipient, _amount);
_approve(_sender, msg.sender, _currentAllowance.sub(_amount));
return true;
}
// this checks if a transfer/transferFrom/withdraw is allowed. There are some conditions on withdraws/transfers from new deposits
// function stub, this needs to be implemented in a contract which inherits this for a valid deployment
// IMPLEMENT THIS
function _verify(address _account, uint256 _amountUnderlyingToSend) internal virtual;
// allow tokens, not shares
function allowance(address _owner, address _spender) external override view returns (uint256){
return allowances[_owner][_spender];
}
// approve tokens, not shares
function approve(address _spender, uint256 _amount) external override returns (bool){
_approve(msg.sender, _spender, _amount);
return true;
}
// shares of _account
function sharesOf(address _account) external view returns (uint256) {
return _sharesOf(_account);
}
// how many shares for _amount of underlying?
// if there are no shares, or no underlying yet, we are initing the contract or suffered a total loss
// either way, init this state at 1:1 shares:underlying
function getSharesForUnderlying(uint256 _amountUnderlying) public view returns (uint256){
uint256 _totalUnderlying = _getTotalUnderlying();
if (_totalUnderlying == 0){
return _amountUnderlying; // this will init at 1:1 _underlying:_shares
}
uint256 _totalShares = totalShares;
if (_totalShares == 0){
return _amountUnderlying; // this will init the first shares, expected contract underlying balance == 0, or there will be a bonus (doesn't belong to anyone so ok)
}
return _amountUnderlying.mul(_totalShares).div(_totalUnderlying);
}
// how many underlying for _amount of shares?
// if there are no shares, or no underlying yet, we are initing the contract or suffered a total loss
// either way, init this state at 1:1 shares:underlying
function getUnderlyingForShares(uint256 _amountShares) public view returns (uint256){
uint256 _totalShares = totalShares;
if (_totalShares == 0){
return _amountShares; // this will init at 1:1 _shares:_underlying
}
uint256 _totalUnderlying = _getTotalUnderlying();
if (_totalUnderlying == 0){
return _amountShares; // this will init at 1:1
}
return _amountShares.mul(_totalUnderlying).div(_totalShares);
}
function _sharesOf(address _account) internal view returns (uint256){
return shares[_account];
}
// function stub, this needs to be implemented in a contract which inherits this for a valid deployment
// sum the contract balance + working balance withdrawn from the contract and actively farming
// IMPLEMENT THIS
function _getTotalUnderlying() internal virtual view returns (uint256);
// in underlying
function _transfer(address _sender, address _recipient, uint256 _amount) internal {
uint256 _sharesToTransfer = getSharesForUnderlying(_amount);
_transferShares(_sender, _recipient, _sharesToTransfer);
emit Transfer(_sender, _recipient, _amount);
}
// in underlying
function _approve(address _owner, address _spender, uint256 _amount) internal {
require(_owner != address(0), "FARMTOKENV1: from == 0x0");
require(_spender != address(0), "FARMTOKENV1: to == 0x00");
allowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
function _transferShares(address _sender, address _recipient, uint256 _amountShares) internal {
require(_sender != address(0), "FARMTOKENV1: from == 0x00");
require(_recipient != address(0), "FARMTOKENV1: to == 0x00");
uint256 _currentSenderShares = shares[_sender];
require(_amountShares <= _currentSenderShares, "FARMTOKENV1: transfer amount exceeds balance");
shares[_sender] = _currentSenderShares.sub(_amountShares);
shares[_recipient] = shares[_recipient].add(_amountShares);
}
function _mintShares(address _recipient, uint256 _amountShares) internal {
require(_recipient != address(0), "FARMTOKENV1: to == 0x00");
totalShares = totalShares.add(_amountShares);
shares[_recipient] = shares[_recipient].add(_amountShares);
// NOTE: we're not emitting a Transfer event from the zero address here
// If we mint shares with no underlying, we basically just diluted everyone
// It's not possible to send events from _everyone_ to reflect each balance dilution (ie: balance going down)
// Not compliant to ERC20 standard...
}
function _burnShares(address _account, uint256 _amountShares) internal {
require(_account != address(0), "FARMTOKENV1: burn from == 0x00");
uint256 _accountShares = shares[_account];
require(_amountShares <= _accountShares, "FARMTOKENV1: burn amount exceeds balance");
totalShares = totalShares.sub(_amountShares);
shares[_account] = _accountShares.sub(_amountShares);
// NOTE: we're not emitting a Transfer event to the zero address here
// If we burn shares without burning/withdrawing the underlying
// then it looks like a system wide credit to everyones balance
// It's not possible to send events to _everyone_ to reflect each balance credit (ie: balance going up)
// Not compliant to ERC20 standard...
}
}
contract FarmTreasuryV1 is ReentrancyGuard, FarmTokenV1 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Address for address;
mapping(address => DepositInfo) public userDeposits;
mapping(address => bool) public noLockWhitelist;
struct DepositInfo {
uint256 amountUnderlyingLocked;
uint256 timestampDeposit;
uint256 timestampUnlocked;
}
uint256 internal constant LOOP_LIMIT = 200;
address payable public governance;
address payable public farmBoss;
bool public paused = false;
bool public pausedDeposits = false;
// fee schedule, can be changed by governance, in bips
// performance fee is on any gains, base fee is on AUM/yearly
uint256 public constant max = 10000;
uint256 public performanceToTreasury = 1000;
uint256 public performanceToFarmer = 1000;
uint256 public baseToTreasury = 100;
uint256 public baseToFarmer = 100;
// limits on rebalancing from the farmer, trying to negate errant rebalances
uint256 public rebalanceUpLimit = 100; // maximum of a 1% gain per rebalance
uint256 public rebalanceUpWaitTime = 23 hours;
uint256 public lastRebalanceUpTime;
// waiting period on withdraws from time of deposit
// locked amount linearly decreases until the time is up, so at waitPeriod/2 after deposit, you can withdraw depositAmt/2 funds.
uint256 public waitPeriod = 1 weeks;
// hot wallet holdings for instant withdraw, in bips
// if the hot wallet balance expires, the users will need to wait for the next rebalance period in order to withdraw
uint256 public hotWalletHoldings = 1000; // 10% initially
uint256 public ACTIVELY_FARMED;
event RebalanceHot(uint256 amountIn, uint256 amountToFarmer, uint256 timestamp);
event ProfitDeclared(bool profit, uint256 amount, uint256 timestamp, uint256 totalAmountInPool, uint256 totalSharesInPool, uint256 performanceFeeTotal, uint256 baseFeeTotal);
event Deposit(address depositor, uint256 amount, address referral);
event Withdraw(address withdrawer, uint256 amount);
constructor(string memory _nameUnderlying, uint8 _decimalsUnderlying, address _underlying) public FarmTokenV1(_nameUnderlying, _decimalsUnderlying, _underlying) {
governance = msg.sender;
lastRebalanceUpTime = block.timestamp;
}
function setGovernance(address payable _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
governance = _new;
}
// the "farmBoss" is a trusted smart contract that functions kind of like an EOA.
// HOWEVER specific contract addresses need to be whitelisted in order for this contract to be allowed to interact w/ them
// the governance has full control over the farmBoss, and other addresses can have partial control for strategy rotation/rebalancing
function setFarmBoss(address payable _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
farmBoss = _new;
}
function setNoLockWhitelist(address[] calldata _accounts, bool[] calldata _noLock) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_accounts.length == _noLock.length && _accounts.length <= LOOP_LIMIT, "FARMTREASURYV1: check array lengths");
for (uint256 i = 0; i < _accounts.length; i++){
noLockWhitelist[_accounts[i]] = _noLock[i];
}
}
function pause() external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
paused = true;
}
function unpause() external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
paused = false;
}
function pauseDeposits() external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
pausedDeposits = true;
}
function unpauseDeposits() external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
pausedDeposits = false;
}
function setFeeDistribution(uint256 _performanceToTreasury, uint256 _performanceToFarmer, uint256 _baseToTreasury, uint256 _baseToFarmer) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_performanceToTreasury.add(_performanceToFarmer) < max, "FARMTREASURYV1: too high performance");
require(_baseToTreasury.add(_baseToFarmer) <= 500, "FARMTREASURYV1: too high base");
performanceToTreasury = _performanceToTreasury;
performanceToFarmer = _performanceToFarmer;
baseToTreasury = _baseToTreasury;
baseToFarmer = _baseToFarmer;
}
function setWaitPeriod(uint256 _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_new <= 10 weeks, "FARMTREASURYV1: too long wait");
waitPeriod = _new;
}
function setHotWalletHoldings(uint256 _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_new <= max && _new >= 100, "FARMTREASURYV1: hot wallet values bad");
hotWalletHoldings = _new;
}
function setRebalanceUpLimit(uint256 _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_new < max, "FARMTREASURYV1: >= max");
rebalanceUpLimit = _new;
}
function setRebalanceUpWaitTime(uint256 _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_new <= 1 weeks, "FARMTREASURYV1: > 1 week");
rebalanceUpWaitTime = _new;
}
function deposit(uint256 _amountUnderlying, address _referral) external nonReentrant {
require(_amountUnderlying > 0, "FARMTREASURYV1: amount == 0");
require(!paused && !pausedDeposits, "FARMTREASURYV1: paused");
_deposit(_amountUnderlying, _referral);
IERC20 _underlying = IERC20(underlyingContract);
uint256 _before = _underlying.balanceOf(address(this));
_underlying.safeTransferFrom(msg.sender, address(this), _amountUnderlying);
uint256 _after = _underlying.balanceOf(address(this));
uint256 _total = _after.sub(_before);
require(_total >= _amountUnderlying, "FARMTREASURYV1: bad transfer");
}
function _deposit(uint256 _amountUnderlying, address _referral) internal {
// determine how many shares this will be
uint256 _sharesToMint = getSharesForUnderlying(_amountUnderlying);
_mintShares(msg.sender, _sharesToMint);
// store some important info for this deposit, that will be checked on withdraw/transfer of tokens
_storeDepositInfo(msg.sender, _amountUnderlying);
// emit deposit w/ referral event... can't refer yourself
if (_referral != msg.sender){
emit Deposit(msg.sender, _amountUnderlying, _referral);
}
else {
emit Deposit(msg.sender, _amountUnderlying, address(0));
}
emit Transfer(address(0), msg.sender, _amountUnderlying);
}
function _storeDepositInfo(address _account, uint256 _amountUnderlying) internal {
DepositInfo memory _existingInfo = userDeposits[_account];
// first deposit, make a new entry in the mapping, lock all funds for "waitPeriod"
if (_existingInfo.timestampDeposit == 0){
DepositInfo memory _info = DepositInfo(
{
amountUnderlyingLocked: _amountUnderlying,
timestampDeposit: block.timestamp,
timestampUnlocked: block.timestamp.add(waitPeriod)
}
);
userDeposits[_account] = _info;
}
// not the first deposit, if there are still funds locked, then average out the waits (ie: 1 BTC locked 10 days = 2 BTC locked 5 days)
else {
uint256 _lockedAmt = _getLockedAmount(_account, _existingInfo.amountUnderlyingLocked, _existingInfo.timestampDeposit, _existingInfo.timestampUnlocked);
// if there's no lock, disregard old info and make a new lock
if (_lockedAmt == 0){
DepositInfo memory _info = DepositInfo(
{
amountUnderlyingLocked: _amountUnderlying,
timestampDeposit: block.timestamp,
timestampUnlocked: block.timestamp.add(waitPeriod)
}
);
userDeposits[_account] = _info;
}
// funds are still locked from a past deposit, average out the waittime remaining with the waittime for this new deposit
/*
solve this equation:
newDepositAmt * waitPeriod + remainingAmt * existingWaitPeriod = (newDepositAmt + remainingAmt) * X waitPeriod
therefore:
(newDepositAmt * waitPeriod + remainingAmt * existingWaitPeriod)
X waitPeriod = ----------------------------------------------------------------
(newDepositAmt + remainingAmt)
Example: 7 BTC new deposit, with wait period of 2 weeks
1 BTC remaining, with remaining wait period of 1 week
...
(7 BTC * 2 weeks + 1 BTC * 1 week) / 8 BTC = 1.875 weeks
*/
else {
uint256 _lockedAmtTime = _lockedAmt.mul(_existingInfo.timestampUnlocked.sub(block.timestamp));
uint256 _newAmtTime = _amountUnderlying.mul(waitPeriod);
uint256 _total = _amountUnderlying.add(_lockedAmt);
uint256 _newLockedTime = (_lockedAmtTime.add(_newAmtTime)).div(_total);
DepositInfo memory _info = DepositInfo(
{
amountUnderlyingLocked: _total,
timestampDeposit: block.timestamp,
timestampUnlocked: block.timestamp.add(_newLockedTime)
}
);
userDeposits[_account] = _info;
}
}
}
function getLockedAmount(address _account) public view returns (uint256) {
DepositInfo memory _existingInfo = userDeposits[_account];
return _getLockedAmount(_account, _existingInfo.amountUnderlyingLocked, _existingInfo.timestampDeposit, _existingInfo.timestampUnlocked);
}
// the locked amount linearly decreases until the timestampUnlocked time, then it's zero
// Example: if 5 BTC contributed (2 week lock), then after 1 week there will be 2.5 BTC locked, the rest is free to transfer/withdraw
function _getLockedAmount(address _account, uint256 _amountLocked, uint256 _timestampDeposit, uint256 _timestampUnlocked) internal view returns (uint256) {
if (_timestampUnlocked <= block.timestamp || noLockWhitelist[_account]){
return 0;
}
else {
uint256 _remainingTime = _timestampUnlocked.sub(block.timestamp);
uint256 _totalTime = _timestampUnlocked.sub(_timestampDeposit);
return _amountLocked.mul(_remainingTime).div(_totalTime);
}
}
function withdraw(uint256 _amountUnderlying) external nonReentrant {
require(_amountUnderlying > 0, "FARMTREASURYV1: amount == 0");
require(!paused, "FARMTREASURYV1: paused");
_withdraw(_amountUnderlying);
IERC20(underlyingContract).safeTransfer(msg.sender, _amountUnderlying);
}
function _withdraw(uint256 _amountUnderlying) internal {
_verify(msg.sender, _amountUnderlying);
// try and catch the more obvious error of hot wallet being depleted, otherwise proceed
if (IERC20(underlyingContract).balanceOf(address(this)) < _amountUnderlying){
revert("FARMTREASURYV1: Hot wallet balance depleted. Please try smaller withdraw or wait for rebalancing.");
}
uint256 _sharesToBurn = getSharesForUnderlying(_amountUnderlying);
_burnShares(msg.sender, _sharesToBurn); // they must have >= _sharesToBurn, checked here
emit Transfer(msg.sender, address(0), _amountUnderlying);
emit Withdraw(msg.sender, _amountUnderlying);
}
// wait time verification
function _verify(address _account, uint256 _amountUnderlyingToSend) internal override {
DepositInfo memory _existingInfo = userDeposits[_account];
uint256 _lockedAmt = _getLockedAmount(_account, _existingInfo.amountUnderlyingLocked, _existingInfo.timestampDeposit, _existingInfo.timestampUnlocked);
uint256 _balance = balanceOf(_account);
// require that any funds locked are not leaving the account in question.
require(_balance.sub(_amountUnderlyingToSend) >= _lockedAmt, "FARMTREASURYV1: requested funds are temporarily locked");
}
// this means that we made a GAIN, due to standard farming gains
// operaratable by farmBoss, this is standard operating procedure, farmers can only report gains
function rebalanceUp(uint256 _amount, address _farmerRewards) external nonReentrant returns (bool, uint256) {
require(msg.sender == farmBoss, "FARMTREASURYV1: !farmBoss");
require(!paused, "FARMTREASURYV1: paused");
// fee logic & profit recording
// check farmer limits on rebalance wait time for earning reportings. if there is no _amount reported, we don't take any fees and skip these checks
// we should always allow pure hot wallet rebalances, however earnings needs some checks and restrictions
if (_amount > 0){
require(block.timestamp.sub(lastRebalanceUpTime) >= rebalanceUpWaitTime, "FARMTREASURYV1: <rebalanceUpWaitTime");
require(ACTIVELY_FARMED.mul(rebalanceUpLimit).div(max) >= _amount, "FARMTREASURYV1 _amount > rebalanceUpLimit");
// farmer incurred a gain of _amount, add this to the amount being farmed
ACTIVELY_FARMED = ACTIVELY_FARMED.add(_amount);
uint256 _totalPerformance = _performanceFee(_amount, _farmerRewards);
uint256 _totalAnnual = _annualFee(_farmerRewards);
// for farmer controls, and also for the annual fee time
// only update this if there is a reported gain, otherwise this is just a hot wallet rebalance, and we should always allow these
lastRebalanceUpTime = block.timestamp;
// for off-chain APY calculations, fees assessed
emit ProfitDeclared(true, _amount, block.timestamp, _getTotalUnderlying(), totalShares, _totalPerformance, _totalAnnual);
}
else {
// for off-chain APY calculations, no fees assessed
emit ProfitDeclared(true, _amount, block.timestamp, _getTotalUnderlying(), totalShares, 0, 0);
}
// end fee logic & profit recording
// funds are in the contract and gains are accounted for, now determine if we need to further rebalance the hot wallet up, or can take funds in order to farm
// start hot wallet and farmBoss rebalance logic
(bool _fundsNeeded, uint256 _amountChange) = _calcHotWallet();
_rebalanceHot(_fundsNeeded, _amountChange); // if the hot wallet rebalance fails, revert() the entire function
// end logic
return (_fundsNeeded, _amountChange); // in case we need them, FE simulations and such
}
// this means that the system took a loss, and it needs to be reflected in the next rebalance
// only operatable by governance, (large) losses should be extremely rare by good farming practices
// this would look like a farmed smart contract getting exploited/hacked, and us not having the necessary insurance for it
// possible that some more aggressive IL strategies could also need this function called
function rebalanceDown(uint256 _amount, bool _rebalanceHotWallet) external nonReentrant returns (bool, uint256) {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
// require(!paused, "FARMTREASURYV1: paused"); <-- governance can only call this anyways, leave this commented out
ACTIVELY_FARMED = ACTIVELY_FARMED.sub(_amount);
if (_rebalanceHotWallet){
(bool _fundsNeeded, uint256 _amountChange) = _calcHotWallet();
_rebalanceHot(_fundsNeeded, _amountChange); // if the hot wallet rebalance fails, revert() the entire function
return (_fundsNeeded, _amountChange); // in case we need them, FE simulations and such
}
// for off-chain APY calculations, no fees assessed
emit ProfitDeclared(false, _amount, block.timestamp, _getTotalUnderlying(), totalShares, 0, 0);
return (false, 0);
}
function _performanceFee(uint256 _amount, address _farmerRewards) internal returns (uint256){
uint256 _existingShares = totalShares;
uint256 _balance = _getTotalUnderlying();
uint256 _performanceToFarmerUnderlying = _amount.mul(performanceToFarmer).div(max);
uint256 _performanceToTreasuryUnderlying = _amount.mul(performanceToTreasury).div(max);
uint256 _performanceTotalUnderlying = _performanceToFarmerUnderlying.add(_performanceToTreasuryUnderlying);
if (_performanceTotalUnderlying == 0){
return 0;
}
uint256 _sharesToMint = _underlyingFeeToShares(_performanceTotalUnderlying, _balance, _existingShares);
uint256 _sharesToFarmer = _sharesToMint.mul(_performanceToFarmerUnderlying).div(_performanceTotalUnderlying); // by the same ratio
uint256 _sharesToTreasury = _sharesToMint.sub(_sharesToFarmer);
_mintShares(_farmerRewards, _sharesToFarmer);
_mintShares(governance, _sharesToTreasury);
uint256 _underlyingFarmer = getUnderlyingForShares(_sharesToFarmer);
uint256 _underlyingTreasury = getUnderlyingForShares(_sharesToTreasury);
// do two mint events, in underlying, not shares
emit Transfer(address(0), _farmerRewards, _underlyingFarmer);
emit Transfer(address(0), governance, _underlyingTreasury);
return _underlyingFarmer.add(_underlyingTreasury);
}
// we are taking baseToTreasury + baseToFarmer each year, every time this is called, look when we took fee last, and linearize the fee to now();
function _annualFee(address _farmerRewards) internal returns (uint256) {
uint256 _lastAnnualFeeTime = lastRebalanceUpTime;
if (_lastAnnualFeeTime >= block.timestamp){
return 0;
}
uint256 _elapsedTime = block.timestamp.sub(_lastAnnualFeeTime);
uint256 _existingShares = totalShares;
uint256 _balance = _getTotalUnderlying();
uint256 _annualPossibleUnderlying = _balance.mul(_elapsedTime).div(365 days);
uint256 _annualToFarmerUnderlying = _annualPossibleUnderlying.mul(baseToFarmer).div(max);
uint256 _annualToTreasuryUnderlying = _annualPossibleUnderlying.mul(baseToFarmer).div(max);
uint256 _annualTotalUnderlying = _annualToFarmerUnderlying.add(_annualToTreasuryUnderlying);
if (_annualTotalUnderlying == 0){
return 0;
}
uint256 _sharesToMint = _underlyingFeeToShares(_annualTotalUnderlying, _balance, _existingShares);
uint256 _sharesToFarmer = _sharesToMint.mul(_annualToFarmerUnderlying).div(_annualTotalUnderlying); // by the same ratio
uint256 _sharesToTreasury = _sharesToMint.sub(_sharesToFarmer);
_mintShares(_farmerRewards, _sharesToFarmer);
_mintShares(governance, _sharesToTreasury);
uint256 _underlyingFarmer = getUnderlyingForShares(_sharesToFarmer);
uint256 _underlyingTreasury = getUnderlyingForShares(_sharesToTreasury);
// do two mint events, in underlying, not shares
emit Transfer(address(0), _farmerRewards, _underlyingFarmer);
emit Transfer(address(0), governance, _underlyingTreasury);
return _underlyingFarmer.add(_underlyingTreasury);
}
function _underlyingFeeToShares(uint256 _totalFeeUnderlying, uint256 _balance, uint256 _existingShares) pure internal returns (uint256 _sharesToMint){
// to mint the required amount of fee shares, solve:
/*
ratio:
currentShares newShares
-------------------------- : --------------------, where newShares = (currentShares + mintShares)
(totalUnderlying - feeAmt) totalUnderlying
solved:
---> (currentShares / (totalUnderlying - feeAmt) * totalUnderlying) - currentShares = mintShares, where newBalanceLessFee = (totalUnderlying - feeAmt)
*/
return _existingShares
.mul(_balance)
.div(_balance.sub(_totalFeeUnderlying))
.sub(_existingShares);
}
function _calcHotWallet() internal view returns (bool _fundsNeeded, uint256 _amountChange) {
uint256 _balanceHere = IERC20(underlyingContract).balanceOf(address(this));
uint256 _balanceFarmed = ACTIVELY_FARMED;
uint256 _totalAmount = _balanceHere.add(_balanceFarmed);
uint256 _hotAmount = _totalAmount.mul(hotWalletHoldings).div(max);
// we have too much in hot wallet, send to farmBoss
if (_balanceHere >= _hotAmount){
return (false, _balanceHere.sub(_hotAmount));
}
// we have too little in hot wallet, pull from farmBoss
if (_balanceHere < _hotAmount){
return (true, _hotAmount.sub(_balanceHere));
}
}
// usually paired with _calcHotWallet()
function _rebalanceHot(bool _fundsNeeded, uint256 _amountChange) internal {
if (_fundsNeeded){
uint256 _before = IERC20(underlyingContract).balanceOf(address(this));
IERC20(underlyingContract).safeTransferFrom(farmBoss, address(this), _amountChange);
uint256 _after = IERC20(underlyingContract).balanceOf(address(this));
uint256 _total = _after.sub(_before);
require(_total >= _amountChange, "FARMTREASURYV1: bad rebalance, hot wallet needs funds!");
// we took funds from the farmBoss to refill the hot wallet, reflect this in ACTIVELY_FARMED
ACTIVELY_FARMED = ACTIVELY_FARMED.sub(_amountChange);
emit RebalanceHot(_amountChange, 0, block.timestamp);
}
else {
require(farmBoss != address(0), "FARMTREASURYV1: !FarmBoss"); // don't burn funds
IERC20(underlyingContract).safeTransfer(farmBoss, _amountChange); // _calcHotWallet() guarantees we have funds here to send
// we sent more funds for the farmer to farm, reflect this
ACTIVELY_FARMED = ACTIVELY_FARMED.add(_amountChange);
emit RebalanceHot(0, _amountChange, block.timestamp);
}
}
function _getTotalUnderlying() internal override view returns (uint256) {
uint256 _balanceHere = IERC20(underlyingContract).balanceOf(address(this));
uint256 _balanceFarmed = ACTIVELY_FARMED;
return _balanceHere.add(_balanceFarmed);
}
function rescue(address _token, uint256 _amount) external nonReentrant {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
if (_token != address(0)){
IERC20(_token).safeTransfer(governance, _amount);
}
else { // if _tokenContract is 0x0, then escape ETH
governance.transfer(_amount);
}
}
}
interface IUniswapRouterV2 {
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint[] memory amounts);
}
abstract contract FarmBossV1 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Address for address;
mapping(address => mapping(bytes4 => uint256)) public whitelist; // contracts -> mapping (functionSig -> allowed, msg.value allowed)
mapping(address => bool) public farmers;
// constants for the whitelist logic
bytes4 constant internal FALLBACK_FN_SIG = 0xffffffff;
// 0 = not allowed ... 1 = allowed however value must be zero ... 2 = allowed with msg.value either zero or non-zero
uint256 constant internal NOT_ALLOWED = 0;
uint256 constant internal ALLOWED_NO_MSG_VALUE = 1;
uint256 constant internal ALLOWED_W_MSG_VALUE = 2;
uint256 internal constant LOOP_LIMIT = 200;
uint256 public constant max = 10000;
uint256 public CRVTokenTake = 1500; // pct of max
// for passing to functions more cleanly
struct WhitelistData {
address account;
bytes4 fnSig;
bool valueAllowed;
}
// for passing to functions more cleanly
struct Approves {
address token;
address allow;
}
address payable public governance;
address public daoCouncilMultisig;
address public treasury;
address public underlying;
// constant - if the addresses change, assume that the functions will be different too and this will need a rewrite
address public constant UniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant SushiswapRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant CRVToken = 0xD533a949740bb3306d119CC777fa900bA034cd52;
event NewFarmer(address _farmer);
event RmFarmer(address _farmer);
event NewWhitelist(address _contract, bytes4 _fnSig, uint256 _allowedType);
event RmWhitelist(address _contract, bytes4 _fnSig);
event NewApproval(address _token, address _contract);
event RmApproval(address _token, address _contract);
event ExecuteSuccess(bytes _returnData);
event ExecuteERROR(bytes _returnData);
constructor(address payable _governance, address _daoMultisig, address _treasury, address _underlying) public {
governance = _governance;
daoCouncilMultisig = _daoMultisig;
treasury = _treasury;
underlying = _underlying;
farmers[msg.sender] = true;
emit NewFarmer(msg.sender);
// no need to set to zero first on safeApprove, is brand new contract
IERC20(_underlying).safeApprove(_treasury, type(uint256).max); // treasury has full control over underlying in this contract
_initFirstFarms();
}
receive() payable external {}
// function stub, this needs to be implemented in a contract which inherits this for a valid deployment
// some fixed logic to set up the first farmers, farms, whitelists, approvals, etc. future farms will need to be approved by governance
// called on init only
// IMPLEMENT THIS
function _initFirstFarms() internal virtual;
function setGovernance(address payable _new) external {
require(msg.sender == governance, "FARMBOSSV1: !governance");
governance = _new;
}
function setDaoCouncilMultisig(address _new) external {
require(msg.sender == governance || msg.sender == daoCouncilMultisig, "FARMBOSSV1: !(governance || multisig)");
daoCouncilMultisig = _new;
}
function setCRVTokenTake(uint256 _new) external {
require(msg.sender == governance || msg.sender == daoCouncilMultisig, "FARMBOSSV1: !(governance || multisig)");
require(_new <= max.div(2), "FARMBOSSV1: >half CRV to take");
CRVTokenTake = _new;
}
function getWhitelist(address _contract, bytes4 _fnSig) external view returns (uint256){
return whitelist[_contract][_fnSig];
}
function changeFarmers(address[] calldata _newFarmers, address[] calldata _rmFarmers) external {
require(msg.sender == governance, "FARMBOSSV1: !governance");
require(_newFarmers.length.add(_rmFarmers.length) <= LOOP_LIMIT, "FARMBOSSV1: >LOOP_LIMIT"); // dont allow unbounded loops
// add the new farmers in
for (uint256 i = 0; i < _newFarmers.length; i++){
farmers[_newFarmers[i]] = true;
emit NewFarmer(_newFarmers[i]);
}
// remove farmers
for (uint256 j = 0; j < _rmFarmers.length; j++){
farmers[_rmFarmers[j]] = false;
emit RmFarmer(_rmFarmers[j]);
}
}
// callable by the DAO Council multisig, we can instantly remove a group of malicious farmers (no delay needed from DAO voting)
function emergencyRemoveFarmers(address[] calldata _rmFarmers) external {
require(msg.sender == daoCouncilMultisig, "FARMBOSSV1: !multisig");
require(_rmFarmers.length <= LOOP_LIMIT, "FARMBOSSV1: >LOOP_LIMIT"); // dont allow unbounded loops
// remove farmers
for (uint256 j = 0; j < _rmFarmers.length; j++){
farmers[_rmFarmers[j]] = false;
emit RmFarmer(_rmFarmers[j]);
}
}
function changeWhitelist(WhitelistData[] calldata _newActions, WhitelistData[] calldata _rmActions, Approves[] calldata _newApprovals, Approves[] calldata _newDepprovals) external {
require(msg.sender == governance, "FARMBOSSV1: !governance");
require(_newActions.length.add(_rmActions.length).add(_newApprovals.length).add(_newDepprovals.length) <= LOOP_LIMIT, "FARMBOSSV1: >LOOP_LIMIT"); // dont allow unbounded loops
// add to whitelist, or change a whitelist entry if want to allow/disallow msg.value
for (uint256 i = 0; i < _newActions.length; i++){
_addWhitelist(_newActions[i].account, _newActions[i].fnSig, _newActions[i].valueAllowed);
}
// remove from whitelist
for (uint256 j = 0; j < _rmActions.length; j++){
whitelist[_rmActions[j].account][_rmActions[j].fnSig] = NOT_ALLOWED;
emit RmWhitelist(_rmActions[j].account, _rmActions[j].fnSig);
}
// approve safely, needs to be set to zero, then max.
for (uint256 k = 0; k < _newApprovals.length; k++){
_approveMax(_newApprovals[k].token, _newApprovals[k].allow);
}
// de-approve these contracts
for (uint256 l = 0; l < _newDepprovals.length; l++){
IERC20(_newDepprovals[l].token).safeApprove(_newDepprovals[l].allow, 0);
emit RmApproval(_newDepprovals[l].token, _newDepprovals[l].allow);
}
}
function _addWhitelist(address _contract, bytes4 _fnSig, bool _msgValueAllowed) internal {
if (_msgValueAllowed){
whitelist[_contract][_fnSig] = ALLOWED_W_MSG_VALUE;
emit NewWhitelist(_contract, _fnSig, ALLOWED_W_MSG_VALUE);
}
else {
whitelist[_contract][_fnSig] = ALLOWED_NO_MSG_VALUE;
emit NewWhitelist(_contract, _fnSig, ALLOWED_NO_MSG_VALUE);
}
}
function _approveMax(address _token, address _account) internal {
IERC20(_token).safeApprove(_account, 0);
IERC20(_token).safeApprove(_account, type(uint256).max);
emit NewApproval(_token, _account);
}
// callable by the DAO Council multisig, we can instantly remove a group of malicious contracts / approvals (no delay needed from DAO voting)
function emergencyRemoveWhitelist(WhitelistData[] calldata _rmActions, Approves[] calldata _newDepprovals) external {
require(msg.sender == daoCouncilMultisig, "FARMBOSSV1: !multisig");
require(_rmActions.length.add(_newDepprovals.length) <= LOOP_LIMIT, "FARMBOSSV1: >LOOP_LIMIT"); // dont allow unbounded loops
// remove from whitelist
for (uint256 j = 0; j < _rmActions.length; j++){
whitelist[_rmActions[j].account][_rmActions[j].fnSig] = NOT_ALLOWED;
emit RmWhitelist(_rmActions[j].account, _rmActions[j].fnSig);
}
// de-approve these contracts
for (uint256 l = 0; l < _newDepprovals.length; l++){
IERC20(_newDepprovals[l].token).safeApprove(_newDepprovals[l].allow, 0);
emit RmApproval(_newDepprovals[l].token, _newDepprovals[l].allow);
}
}
function govExecute(address payable _target, uint256 _value, bytes calldata _data) external returns (bool, bytes memory){
require(msg.sender == governance, "FARMBOSSV1: !governance");
return _execute(_target, _value, _data);
}
function farmerExecute(address payable _target, uint256 _value, bytes calldata _data) external returns (bool, bytes memory){
require(farmers[msg.sender] || msg.sender == daoCouncilMultisig, "FARMBOSSV1: !(farmer || multisig)");
require(_checkContractAndFn(_target, _value, _data), "FARMBOSSV1: target.fn() not allowed. ask DAO for approval.");
return _execute(_target, _value, _data);
}
// farmer is NOT allowed to call the functions approve, transfer on an ERC20
// this will give the farmer direct control over assets held by the contract
// governance must approve() farmer to interact with contracts & whitelist these contracts
// even if contracts are whitelisted, farmer cannot call transfer/approve (many vault strategies will have ERC20 inheritance)
// these approvals must also be called when setting up a new strategy from governance
// if there is a strategy that has additonal functionality for the farmer to take control of assets ie: Uniswap "add a send"
// then a "safe" wrapper contract must be made, ie: you can call Uniswap but "add a send is disabled, only msg.sender in this field"
// strategies must be checked carefully so that farmers cannot take control of assets. trustless farming!
function _checkContractAndFn(address _target, uint256 _value, bytes calldata _data) internal view returns (bool) {
bytes4 _fnSig;
if (_data.length < 4){ // we are calling a payable function, or the data is otherwise invalid (need 4 bytes for any fn call)
_fnSig = FALLBACK_FN_SIG;
}
else { // we are calling a normal function, get the function signature from the calldata (first 4 bytes of calldata)
//////////////////
// NOTE: here we must use assembly in order to covert bytes -> bytes4
// See consensys code for bytes -> bytes32: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
//////////////////
bytes memory _fnSigBytes = bytes(_data[0:4]);
assembly {
_fnSig := mload(add(add(_fnSigBytes, 0x20), 0))
}
// _fnSig = abi.decode(bytes(_data[0:4]), (bytes4)); // NOTE: does not work, open solidity issue: https://github.com/ethereum/solidity/issues/9170
}
bytes4 _transferSig = 0xa9059cbb;
bytes4 _approveSig = 0x095ea7b3;
if (_fnSig == _transferSig || _fnSig == _approveSig || whitelist[_target][_fnSig] == NOT_ALLOWED){
return false;
}
// check if value not allowed & value
else if (whitelist[_target][_fnSig] == ALLOWED_NO_MSG_VALUE && _value > 0){
return false;
}
// either ALLOWED_W_MSG_VALUE or ALLOWED_NO_MSG_VALUE with zero value
return true;
}
// call arbitrary contract & function, forward all gas, return success? & data
function _execute(address payable _target, uint256 _value, bytes memory _data) internal returns (bool, bytes memory){
bool _success;
bytes memory _returnData;
if (_data.length == 4 && _data[0] == 0xff && _data[1] == 0xff && _data[2] == 0xff && _data[3] == 0xff){ // check if fallback function is invoked, send w/ no data
(_success, _returnData) = _target.call{value: _value}("");
}
else {
(_success, _returnData) = _target.call{value: _value}(_data);
}
if (_success){
emit ExecuteSuccess(_returnData);
}
else {
emit ExecuteERROR(_returnData);
}
return (_success, _returnData);
}
// we can call this function on the treasury from farmer/govExecute, but let's make it easy
function rebalanceUp(uint256 _amount, address _farmerRewards) external {
require(msg.sender == governance || farmers[msg.sender] || msg.sender == daoCouncilMultisig, "FARMBOSSV1: !(governance || farmer || multisig)");
FarmTreasuryV1(treasury).rebalanceUp(_amount, _farmerRewards);
}
// is a Sushi/Uniswap wrapper to sell tokens for extra safety. This way, the swapping routes & destinations are checked & much safer than simply whitelisting the function
// the function takes the calldata directly as an input. this way, calling the function is very similar to a normal farming call
function sellExactTokensForUnderlyingToken(bytes calldata _data, bool _isSushi) external returns (uint[] memory amounts){
require(msg.sender == governance || farmers[msg.sender] || msg.sender == daoCouncilMultisig, "FARMBOSSV1: !(governance || farmer || multisig)");
(uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline) = abi.decode(_data[4:], (uint256, uint256, address[], address, uint256));
// check the data to make sure it's an allowed sell
require(to == address(this), "FARMBOSSV1: invalid sell, to != address(this)");
// strictly require paths to be [token, WETH, underlying]
// note: underlying can be WETH --> [token, WETH]
if (underlying == WETH){
require(path.length == 2, "FARMBOSSV1: path.length != 2");
require(path[1] == WETH, "FARMBOSSV1: WETH invalid sell, output != underlying");
}
else {
require(path.length == 3, "FARMBOSSV1: path.length != 3");
require(path[1] == WETH, "FARMBOSSV1: path[1] != WETH");
require(path[2] == underlying, "FARMBOSSV1: invalid sell, output != underlying");
}
// DAO takes some percentage of CRVToken pre-sell as part of a long term strategy
if (path[0] == CRVToken && CRVTokenTake > 0){
uint256 _amtTake = amountIn.mul(CRVTokenTake).div(max); // take some portion, and send to governance
// redo the swap input variables, to account for the amount taken
amountIn = amountIn.sub(_amtTake);
amountOutMin = amountOutMin.mul(max.sub(CRVTokenTake)).div(max); // reduce the amountOutMin by the same ratio, therefore target slippage pct is the same
IERC20(CRVToken).safeTransfer(governance, _amtTake);
}
if (_isSushi){ // sell on Sushiswap
return IUniswapRouterV2(SushiswapRouter).swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline);
}
else { // sell on Uniswap
return IUniswapRouterV2(UniswapRouter).swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline);
}
}
function rescue(address _token, uint256 _amount) external {
require(msg.sender == governance, "FARMBOSSV1: !governance");
if (_token != address(0)){
IERC20(_token).safeTransfer(governance, _amount);
}
else { // if _tokenContract is 0x0, then escape ETH
governance.transfer(_amount);
}
}
}
contract FarmBossV1_USDC is FarmBossV1 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Address for address;
// breaking some constants out here, getting stack ;) issues
// CRV FUNCTIONS
/*
CRV Notes:
add_liquidity takes a fixed size array of input, so it will change the function signature
0x0b4c7e4d --> 2 coin pool --> add_liquidity(uint256[2] uamounts, uint256 min_mint_amount)
0x4515cef3 --> 3 coin pool --> add_liquidity(uint256[3] amounts, uint256 min_mint_amount)
0x029b2f34 --> 4 coin pool --> add_liquidity(uint256[4] amounts, uint256 min_mint_amount)
0xee22be23 --> 2 coin pool underlying --> add_liquidity(uint256[2] _amounts, uint256 _min_mint_amount, bool _use_underlying)
0x2b6e993a -> 3 coin pool underlying --> add_liquidity(uint256[3] _amounts, uint256 _min_mint_amount, bool _use_underlying)
remove_liquidity_one_coin has an optional end argument, bool donate_dust
0x517a55a3 --> remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust)
0x1a4d01d2 --> remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount)
remove_liquidity_imbalance takes a fixes array of input too
0x18a7bd76 --> 4 coin pool --> remove_liquidity_imbalance(uint256[4] amounts, uint256 max_burn_amount)
*/
bytes4 constant private add_liquidity_2 = 0x0b4c7e4d;
bytes4 constant private add_liquidity_3 = 0x4515cef3;
bytes4 constant private add_liquidity_4 = 0x029b2f34;
bytes4 constant private add_liquidity_u_2 = 0xee22be23;
bytes4 constant private add_liquidity_u_3 = 0x2b6e993a;
bytes4 constant private remove_liquidity_one_burn = 0x517a55a3;
bytes4 constant private remove_liquidity_one = 0x1a4d01d2;
bytes4 constant private remove_liquidity_4 = 0x18a7bd76;
bytes4 constant private deposit_gauge = 0xb6b55f25; // deposit(uint256 _value)
bytes4 constant private withdraw_gauge = 0x2e1a7d4d; // withdraw(uint256 _value)
bytes4 constant private mint = 0x6a627842; // mint(address gauge_addr)
bytes4 constant private mint_many = 0xa51e1904; // mint_many(address[8])
bytes4 constant private claim_rewards = 0x84e9bd7e; // claim_rewards(address addr)
// YEARN FUNCTIONS
bytes4 constant private deposit = 0xb6b55f25; // deposit(uint256 _amount)
bytes4 constant private withdraw = 0x2e1a7d4d; // withdraw(uint256 _shares)
// AlphaHomora FUNCTIONS
bytes4 constant private claim = 0x2f52ebb7;
// COMP FUNCTIONS
bytes4 constant private mint_ctoken = 0xa0712d68; // mint(uint256 mintAmount)
bytes4 constant private redeem_ctoken = 0xdb006a75; // redeem(uint256 redeemTokens)
bytes4 constant private claim_COMP = 0x1c3db2e0; // claimComp(address holder, address[] cTokens)
// IDLE FINANCE FUNCTIONS
bytes4 constant private mint_idle = 0x2befabbf; // mintIdleToken(uint256 _amount, bool _skipRebalance, address _referral)
bytes4 constant private redeem_idle = 0x8b30b516; // redeemIdleToken(uint256 _amount)
constructor(address payable _governance, address _daoMultisig, address _treasury, address _underlying) public FarmBossV1(_governance, _daoMultisig, _treasury, _underlying){
}
function _initFirstFarms() internal override {
/*
For our intro USDC strategies, we are using:
-- Curve.fi strategies for their good yielding USDC pools
-- AlphaHomoraV2 USDC
-- yEarn USDC
-- Compound USDC
-- IDLE Finance USDC
*/
////////////// ALLOW CURVE 3, s, y, ib, comp, busd, aave, usdt pools //////////////
////////////// ALLOW crv3pool //////////////
address _crv3Pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
address _crv3PoolToken = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;
_approveMax(underlying, _crv3Pool);
_addWhitelist(_crv3Pool, add_liquidity_3, false);
_addWhitelist(_crv3Pool, remove_liquidity_one, false);
////////////// ALLOW crv3 Gauge //////////////
address _crv3Gauge = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A;
_approveMax(_crv3PoolToken, _crv3Gauge);
_addWhitelist(_crv3Pool, deposit_gauge, false);
_addWhitelist(_crv3Pool, withdraw_gauge, false);
////////////// ALLOW crvSUSD Pool //////////////
// deposit USDC to SUSDpool, receive _crvSUSDToken
// this is a weird pool, like it was configured for lending accidentally... we will allow the swap and zap contract both
address _crvSUSDPool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD;
address _crvSUSDToken = 0xC25a3A3b969415c80451098fa907EC722572917F;
_approveMax(underlying, _crvSUSDPool);
_addWhitelist(_crvSUSDPool, add_liquidity_4, false);
_addWhitelist(_crvSUSDPool, remove_liquidity_4, false);
address _crvSUSDWithdraw = 0xFCBa3E75865d2d561BE8D220616520c171F12851; // because crv frontend is misconfigured to think this is a lending pool
_approveMax(underlying, _crvSUSDWithdraw);
_approveMax(_crvSUSDToken, _crvSUSDWithdraw);
_addWhitelist(_crvSUSDWithdraw, add_liquidity_4, false);
_addWhitelist(_crvSUSDWithdraw, remove_liquidity_one_burn, false);
////////////// ALLOW crvSUSD Gauge, SNX REWARDS //////////////
address _crvSUSDGauge = 0xA90996896660DEcC6E997655E065b23788857849;
_approveMax(_crvSUSDToken, _crvSUSDGauge);
_addWhitelist(_crvSUSDGauge, deposit_gauge, false);
_addWhitelist(_crvSUSDGauge, withdraw_gauge, false);
_addWhitelist(_crvSUSDGauge, claim_rewards, false);
address _SNXToken = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F;
_approveMax(_SNXToken, SushiswapRouter);
_approveMax(_SNXToken, UniswapRouter);
////////////// ALLOW crvCOMP Pool //////////////
address _crvCOMPDeposit = 0xeB21209ae4C2c9FF2a86ACA31E123764A3B6Bc06;
address _crvCOMPToken = 0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2;
_approveMax(underlying, _crvCOMPDeposit);
_approveMax(_crvCOMPToken, _crvCOMPDeposit); // allow withdraws, lending pool
_addWhitelist(_crvCOMPDeposit, add_liquidity_2, false);
_addWhitelist(_crvCOMPDeposit, remove_liquidity_one_burn, false);
////////////// ALLOW crvCOMP Gauge //////////////
address _crvCOMPGauge = 0x7ca5b0a2910B33e9759DC7dDB0413949071D7575;
_approveMax(_crvCOMPToken, _crvCOMPGauge);
_addWhitelist(_crvCOMPGauge, deposit_gauge, false);
_addWhitelist(_crvCOMPGauge, withdraw_gauge, false);
////////////// ALLOW crvBUSD Pool //////////////
address _crvBUSDDeposit = 0xb6c057591E073249F2D9D88Ba59a46CFC9B59EdB;
address _crvBUSDToken = 0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B;
_approveMax(underlying, _crvBUSDDeposit);
_approveMax(_crvBUSDToken, _crvBUSDDeposit);
_addWhitelist(_crvBUSDDeposit, add_liquidity_4, false);
_addWhitelist(_crvBUSDDeposit, remove_liquidity_one_burn, false);
////////////// ALLOW crvBUSD Gauge //////////////
address _crvBUSDGauge = 0x69Fb7c45726cfE2baDeE8317005d3F94bE838840;
_approveMax(_crvBUSDToken, _crvBUSDGauge);
_addWhitelist(_crvBUSDGauge, deposit_gauge, false);
_addWhitelist(_crvBUSDGauge, withdraw_gauge, false);
////////////// ALLOW crvAave Pool //////////////
address _crvAavePool = 0xDeBF20617708857ebe4F679508E7b7863a8A8EeE; // new style lending pool w/o second approve needed... direct burn from msg.sender
address _crvAaveToken = 0xFd2a8fA60Abd58Efe3EeE34dd494cD491dC14900;
_approveMax(underlying, _crvAavePool);
_addWhitelist(_crvAavePool, add_liquidity_u_3, false);
_addWhitelist(_crvAavePool, remove_liquidity_one_burn, false);
////////////// ALLOW crvAave Gauge //////////////
address _crvAaveGauge = 0xd662908ADA2Ea1916B3318327A97eB18aD588b5d;
_approveMax(_crvAaveToken, _crvAaveGauge);
_addWhitelist(_crvAaveGauge, deposit_gauge, false);
_addWhitelist(_crvAaveGauge, withdraw_gauge, false);
////////////// ALLOW crvYpool //////////////
address _crvYDeposit = 0xbBC81d23Ea2c3ec7e56D39296F0cbB648873a5d3;
address _crvYToken = 0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8;
_approveMax(underlying, _crvYDeposit);
_approveMax(_crvYToken, _crvYDeposit); // allow withdraws, lending pool
_addWhitelist(_crvYDeposit, add_liquidity_4, false);
_addWhitelist(_crvYDeposit, remove_liquidity_one_burn, false);
////////////// ALLOW crvY Gauge //////////////
address _crvYGauge = 0xFA712EE4788C042e2B7BB55E6cb8ec569C4530c1;
_approveMax(_crvYToken, _crvYGauge);
_addWhitelist(_crvYGauge, deposit_gauge, false);
_addWhitelist(_crvYGauge, withdraw_gauge, false);
////////////// ALLOW crvUSDTComp Pool //////////////
address _crvUSDTCompDeposit = 0xac795D2c97e60DF6a99ff1c814727302fD747a80;
address _crvUSDTCompToken = 0x9fC689CCaDa600B6DF723D9E47D84d76664a1F23;
_approveMax(underlying, _crvUSDTCompDeposit);
_approveMax(_crvUSDTCompToken, _crvUSDTCompDeposit); // allow withdraws, lending pool
_addWhitelist(_crvUSDTCompDeposit, add_liquidity_3, false);
_addWhitelist(_crvUSDTCompDeposit, remove_liquidity_one_burn, false);
////////////// ALLOW crvUSDTComp Gauge //////////////
address _crvUSDTCompGauge = 0xBC89cd85491d81C6AD2954E6d0362Ee29fCa8F53;
_approveMax(_crvUSDTCompToken, _crvUSDTCompGauge);
_addWhitelist(_crvUSDTCompGauge, deposit_gauge, false);
_addWhitelist(_crvUSDTCompGauge, withdraw_gauge, false);
////////////// ALLOW crvIBPool Pool //////////////
address _crvIBPool = 0x2dded6Da1BF5DBdF597C45fcFaa3194e53EcfeAF;
_approveMax(underlying, _crvIBPool);
_addWhitelist(_crvIBPool, add_liquidity_u_3, false);
_addWhitelist(_crvIBPool, remove_liquidity_one_burn, false);
////////////// ALLOW crvIBPool Gauge //////////////
address _crvIBGauge = 0xF5194c3325202F456c95c1Cf0cA36f8475C1949F;
address _crvIBToken = 0x5282a4eF67D9C33135340fB3289cc1711c13638C;
_approveMax(_crvIBToken, _crvIBGauge);
_addWhitelist(_crvIBGauge, deposit_gauge, false);
_addWhitelist(_crvIBGauge, withdraw_gauge, false);
////////////// CRV tokens mint, sell Sushi/Uni //////////////
address _crvMintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
_addWhitelist(_crvMintr, mint, false);
_addWhitelist(_crvMintr, mint_many, false);
// address CRVToken = 0xD533a949740bb3306d119CC777fa900bA034cd52; -- already in FarmBossV1
_approveMax(CRVToken, SushiswapRouter);
_approveMax(CRVToken, UniswapRouter);
////////////// END ALLOW CURVE 3, s, y, ib, comp, busd, aave, usdt pools //////////////
////////////// ALLOW AlphaHomoraV2 USDC //////////////
address _ahUSDC = 0x08bd64BFC832F1C2B3e07e634934453bA7Fa2db2;
IERC20(underlying).safeApprove(_ahUSDC, type(uint256).max);
whitelist[_ahUSDC][deposit] = ALLOWED_NO_MSG_VALUE;
whitelist[_ahUSDC][withdraw] = ALLOWED_NO_MSG_VALUE;
whitelist[_ahUSDC][claim] = ALLOWED_NO_MSG_VALUE; // claim ALPHA token reward
_approveMax(underlying, _ahUSDC);
_addWhitelist(_ahUSDC, deposit, false);
_addWhitelist(_ahUSDC, withdraw, false);
_addWhitelist(_ahUSDC, claim, false);
address ALPHA_TOKEN = 0xa1faa113cbE53436Df28FF0aEe54275c13B40975;
_approveMax(ALPHA_TOKEN, SushiswapRouter);
_approveMax(ALPHA_TOKEN, UniswapRouter);
////////////// END ALLOW AlphaHomoraV2 USDC //////////////
////////////// ALLOW yEarn USDC //////////////
address _yearnUSDC = 0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9;
IERC20(underlying).safeApprove(_yearnUSDC, type(uint256).max);
whitelist[_yearnUSDC][deposit] = ALLOWED_NO_MSG_VALUE;
whitelist[_yearnUSDC][withdraw] = ALLOWED_NO_MSG_VALUE;
_approveMax(underlying, _yearnUSDC);
_addWhitelist(_yearnUSDC, deposit, false);
_addWhitelist(_yearnUSDC, withdraw, false);
////////////// END ALLOW yEarn USDC //////////////
////////////// ALLOW Compound USDC //////////////
address _compUSDC = 0x39AA39c021dfbaE8faC545936693aC917d5E7563;
_approveMax(underlying, _compUSDC);
_addWhitelist(_compUSDC, mint_ctoken, false);
_addWhitelist(_compUSDC, redeem_ctoken, false);
address _comptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; // claimComp
_addWhitelist(_comptroller, claim_COMP, false);
address _COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
_approveMax(_COMP, SushiswapRouter);
_approveMax(_COMP, UniswapRouter);
////////////// END ALLOW Compound USDC //////////////
////////////// ALLOW IDLE Finance USDC //////////////
address _idleBestUSDCv4 = 0x5274891bEC421B39D23760c04A6755eCB444797C;
_approveMax(underlying, _idleBestUSDCv4);
_addWhitelist(_idleBestUSDCv4, mint_idle, false);
_addWhitelist(_idleBestUSDCv4, redeem_idle, false);
// IDLEUSDC doesn't have a pure IDLEClaim() function, you need to either deposit/withdraw again, and then your IDLE & COMP will be sent
address IDLEToken = 0x875773784Af8135eA0ef43b5a374AaD105c5D39e;
_approveMax(IDLEToken, SushiswapRouter);
_approveMax(IDLEToken, UniswapRouter);
// NOTE: Comp rewards already are approved for liquidation above
////////////// END ALLOW IDLE Finance USDC //////////////
}
} | we have too much in hot wallet, send to farmBoss we have too little in hot wallet, pull from farmBoss | function _calcHotWallet() internal view returns (bool _fundsNeeded, uint256 _amountChange) {
uint256 _balanceHere = IERC20(underlyingContract).balanceOf(address(this));
uint256 _balanceFarmed = ACTIVELY_FARMED;
uint256 _totalAmount = _balanceHere.add(_balanceFarmed);
uint256 _hotAmount = _totalAmount.mul(hotWalletHoldings).div(max);
if (_balanceHere >= _hotAmount){
return (false, _balanceHere.sub(_hotAmount));
}
if (_balanceHere < _hotAmount){
return (true, _hotAmount.sub(_balanceHere));
}
}
| 1,571,247 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title OptimismMintableERC20
* This contract represents the remote representation
* of an ERC20 token. It is linked to the address of
* a token in another domain and tokens can be locked
* in the StandardBridge which will mint tokens in the
* other domain.
*/
contract OptimismMintableERC20 is ERC20 {
event Mint(address indexed _account, uint256 _amount);
event Burn(address indexed _account, uint256 _amount);
/**
* @notice The address of the token in the remote domain
*/
address public remoteToken;
/**
* @notice The address of the bridge responsible for
* minting. It is in the same domain.
*/
address public bridge;
/**
* @param _bridge Address of the L2 standard bridge.
* @param _remoteToken Address of the corresponding L1 token.
* @param _name ERC20 name.
* @param _symbol ERC20 symbol.
*/
constructor(
address _bridge,
address _remoteToken,
string memory _name,
string memory _symbol
) ERC20(_name, _symbol) {
remoteToken = _remoteToken;
bridge = _bridge;
}
/**
* @notice Returns the corresponding L1 token address.
* This is a legacy function and wraps the remoteToken value.
*/
function l1Token() public view returns (address) {
return remoteToken;
}
/**
* @notice The address of the bridge contract
* responsible for minting tokens. This is a legacy
* getter function
*/
function l2Bridge() public view returns (address) {
return bridge;
}
/**
* @notice A modifier that only allows the bridge to call
*/
modifier onlyBridge() {
require(msg.sender == bridge, "Only L2 Bridge can mint and burn");
_;
}
/**
* @notice ERC165
*/
// slither-disable-next-line external-function
function supportsInterface(bytes4 _interfaceId) public pure returns (bool) {
bytes4 iface1 = bytes4(keccak256("supportsInterface(bytes4)")); // ERC165
bytes4 iface2 = this.l1Token.selector ^ this.mint.selector ^ this.burn.selector;
bytes4 iface3 = this.remoteToken.selector ^ this.mint.selector ^ this.burn.selector;
return _interfaceId == iface1 || _interfaceId == iface3 || _interfaceId == iface2;
}
/**
* @notice The bridge can mint tokens
*/
// slither-disable-next-line external-function
function mint(address _to, uint256 _amount) public virtual onlyBridge {
_mint(_to, _amount);
emit Mint(_to, _amount);
}
/**
* @notice The bridge can burn tokens
*/
// slither-disable-next-line external-function
function burn(address _from, uint256 _amount) public virtual onlyBridge {
_burn(_from, _amount);
emit Burn(_from, _amount);
}
}
| Returns the corresponding L1 token address. This is a legacy function and wraps the remoteToken value./ | function l1Token() public view returns (address) {
return remoteToken;
}
| 12,681,735 |
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.6;
import "./Interfaces.sol";
// solhint-disable const-name-snakecase
// solhint-disable private-vars-leading-underscore
// solhint-disable not-rely-on-time
contract GovernorBravo is GovernorBravoDelegateStorageV1, GovernorBravoEvents {
/// @notice The name of this contract
string public constant name = "DeFiHelper Governor Bravo";
/// @notice The minimum setable proposal threshold
uint256 public constant MIN_PROPOSAL_THRESHOLD = 3_000_000e18; // 3,000,000 DFH (0,3%)
/// @notice The maximum setable proposal threshold
uint256 public constant MAX_PROPOSAL_THRESHOLD = 40_000_000e18; //40,000,000 DFH (4%)
/// @notice The minimum setable voting period
uint256 public constant MIN_VOTING_PERIOD = 5760; // About 24 hours
/// @notice The max setable voting period
uint256 public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks
/// @notice The min setable voting delay
uint256 public constant MIN_VOTING_DELAY = 1;
/// @notice The max setable voting delay
uint256 public constant MAX_VOTING_DELAY = 40320; // About 1 week
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
uint256 public constant quorumVotes = 40_000_000e18; // 40,000,000 = 4% of DFH
/// @notice The maximum number of actions that can be included in a proposal
uint256 public constant proposalMaxOperations = 10; // 10 actions
/// @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 ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
/**
* @notice Used to initialize the contract during delegator contructor
* @param timelock_ The address of the Timelock
* @param governanceToken_ The address of the governance token
* @param votingPeriod_ The initial voting period
* @param votingDelay_ The initial voting delay
* @param proposalThreshold_ The initial proposal threshold
*/
function initialize(
address timelock_,
address governanceToken_,
uint256 votingPeriod_,
uint256 votingDelay_,
uint256 proposalThreshold_
) public {
require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once");
require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address");
require(governanceToken_ != address(0), "GovernorBravo::initialize: invalid governance token address");
require(
votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD,
"GovernorBravo::initialize: invalid voting period"
);
require(
votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY,
"GovernorBravo::initialize: invalid voting delay"
);
require(
proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD,
"GovernorBravo::initialize: invalid proposal threshold"
);
admin = timelock_;
timelock = TimelockInterface(timelock_);
governanceToken = GovernanceTokenInterface(governanceToken_);
votingPeriod = votingPeriod_;
votingDelay = votingDelay_;
proposalThreshold = proposalThreshold_;
}
/**
* @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold
* @param targets Target addresses for proposal calls
* @param values Eth values for proposal calls
* @param signatures Function signatures for proposal calls
* @param calldatas Calldatas for proposal calls
* @param description String description of the proposal
* @return Proposal id of new proposal
*/
function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public returns (uint256) {
require(
governanceToken.getPriorVotes(msg.sender, block.number - 1) > proposalThreshold,
"GovernorBravo::propose: proposer votes below proposal threshold"
);
require(
targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length,
"GovernorBravo::propose: proposal function information arity mismatch"
);
require(targets.length != 0, "GovernorBravo::propose: must provide actions");
require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions");
uint256 latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(
proposersLatestProposalState != ProposalState.Active,
"GovernorBravo::propose: one live proposal per proposer, found an already active proposal"
);
require(
proposersLatestProposalState != ProposalState.Pending,
"GovernorBravo::propose: one live proposal per proposer, found an already pending proposal"
);
}
uint256 startBlock = block.number + votingDelay;
uint256 endBlock = startBlock + votingPeriod;
proposalCount++;
/// @dev https://docs.soliditylang.org/en/v0.7.1/070-breaking-changes.html#mappings-outside-storage
Proposal storage newProposal = proposals[proposalCount];
newProposal.id = proposalCount;
newProposal.proposer = msg.sender;
newProposal.targets = targets;
newProposal.values = values;
newProposal.signatures = signatures;
newProposal.calldatas = calldatas;
newProposal.startBlock = startBlock;
newProposal.endBlock = endBlock;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(
newProposal.id,
msg.sender,
targets,
values,
signatures,
calldatas,
startBlock,
endBlock,
description
);
return newProposal.id;
}
/**
* @notice Queues a proposal of state succeeded
* @param proposalId The id of the proposal to queue
*/
function queue(uint256 proposalId) external {
require(
state(proposalId) == ProposalState.Succeeded,
"GovernorBravo::queue: proposal can only be queued if it is succeeded"
);
Proposal storage proposal = proposals[proposalId];
uint256 eta = block.timestamp + timelock.delay();
for (uint256 i = 0; i < proposal.targets.length; i++) {
queueOrRevertInternal(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
eta
);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function queueOrRevertInternal(
address target,
uint256 value,
string memory signature,
bytes memory data,
uint256 eta
) internal {
require(
!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))),
"GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta"
);
timelock.queueTransaction(target, value, signature, data, eta);
}
/**
* @notice Executes a queued proposal if eta has passed
* @param proposalId The id of the proposal to execute
*/
function execute(uint256 proposalId) external payable {
require(
state(proposalId) == ProposalState.Queued,
"GovernorBravo::execute: proposal can only be executed if it is queued"
);
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction{value: proposal.values[i]}(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalExecuted(proposalId);
}
/**
* @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold
* @param proposalId The id of the proposal to cancel
*/
function cancel(uint256 proposalId) external {
require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(
msg.sender == proposal.proposer ||
governanceToken.getPriorVotes(proposal.proposer, block.number - 1) < proposalThreshold,
"GovernorBravo::cancel: proposer above threshold"
);
proposal.canceled = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(
proposal.targets[i],
proposal.values[i],
proposal.signatures[i],
proposal.calldatas[i],
proposal.eta
);
}
emit ProposalCanceled(proposalId);
}
/**
* @notice Gets actions of a proposal
* @param proposalId the id of the proposal
* @return targets Targets of the proposal actions
* @return values Values of the proposal actions
* @return signatures Signatures of the proposal actions
* @return calldatas Calldatas of the proposal actions
*/
function getActions(uint256 proposalId)
external
view
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
)
{
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice Gets the receipt for a voter on a given proposal
* @param proposalId the id of proposal
* @param voter The address of the voter
* @return The voting receipt
*/
function getReceipt(uint256 proposalId, address voter) external view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
/**
* @notice Gets the state of a proposal
* @param proposalId The id of the proposal
* @return Proposal state
*/
function state(uint256 proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId, "GovernorBravo::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= proposal.eta + timelock.GRACE_PERIOD()) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @notice Cast a vote for a proposal
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
*/
function castVote(uint256 proposalId, uint8 support) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), "");
}
/**
* @notice Cast a vote for a proposal with a reason
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @param reason The reason given for the vote by the voter
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason);
}
/**
* @notice Cast a vote for a proposal by signature
* @dev External function that accepts EIP-712 signatures for voting on proposals.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this))
);
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature");
emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), "");
}
/**
* @notice Internal function that caries out voting logic
* @param voter The voter that is casting their vote
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @return The number of votes cast
*/
function castVoteInternal(
address voter,
uint256 proposalId,
uint8 support
) internal returns (uint96) {
require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed");
require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted");
uint96 votes = governanceToken.getPriorVotes(voter, proposal.startBlock);
if (support == 0) {
proposal.againstVotes = proposal.againstVotes + votes;
} else if (support == 1) {
proposal.forVotes = proposal.forVotes + votes;
} else if (support == 2) {
proposal.abstainVotes = proposal.abstainVotes + votes;
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
return votes;
}
/**
* @notice Admin function for setting the voting delay
* @param newVotingDelay new voting delay, in blocks
*/
function _setVotingDelay(uint256 newVotingDelay) external {
require(msg.sender == admin, "GovernorBravo::_setVotingDelay: admin only");
require(
newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY,
"GovernorBravo::_setVotingDelay: invalid voting delay"
);
uint256 oldVotingDelay = votingDelay;
votingDelay = newVotingDelay;
emit VotingDelaySet(oldVotingDelay, votingDelay);
}
/**
* @notice Admin function for setting the voting period
* @param newVotingPeriod new voting period, in blocks
*/
function _setVotingPeriod(uint256 newVotingPeriod) external {
require(msg.sender == admin, "GovernorBravo::_setVotingPeriod: admin only");
require(
newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD,
"GovernorBravo::_setVotingPeriod: invalid voting period"
);
uint256 oldVotingPeriod = votingPeriod;
votingPeriod = newVotingPeriod;
emit VotingPeriodSet(oldVotingPeriod, votingPeriod);
}
/**
* @notice Admin function for setting the proposal threshold
* @dev newProposalThreshold must be greater than the hardcoded min
* @param newProposalThreshold new proposal threshold
*/
function _setProposalThreshold(uint256 newProposalThreshold) external {
require(msg.sender == admin, "GovernorBravo::_setProposalThreshold: admin only");
require(
newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD,
"GovernorBravo::_setProposalThreshold: invalid proposal threshold"
);
uint256 oldProposalThreshold = proposalThreshold;
proposalThreshold = newProposalThreshold;
emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address newPendingAdmin) external {
// Check caller = admin
require(msg.sender == admin, "GovernorBravo:_setPendingAdmin: admin only");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin β address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:_acceptAdmin: pending admin only");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
function getChainIdInternal() internal view returns (uint256) {
uint256 chainId;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
return chainId;
}
}
| Function used to propose a new proposal. Sender must have delegates above the proposal threshold targets Target addresses for proposal calls values Eth values for proposal calls signatures Function signatures for proposal calls calldatas Calldatas for proposal calls description String description of the proposal return Proposal id of new proposal/ | function propose(
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
string memory description
) public returns (uint256) {
require(
governanceToken.getPriorVotes(msg.sender, block.number - 1) > proposalThreshold,
"GovernorBravo::propose: proposer votes below proposal threshold"
);
require(
targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length,
"GovernorBravo::propose: proposal function information arity mismatch"
);
require(targets.length != 0, "GovernorBravo::propose: must provide actions");
require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions");
uint256 latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(
proposersLatestProposalState != ProposalState.Active,
"GovernorBravo::propose: one live proposal per proposer, found an already active proposal"
);
require(
proposersLatestProposalState != ProposalState.Pending,
"GovernorBravo::propose: one live proposal per proposer, found an already pending proposal"
);
}
uint256 startBlock = block.number + votingDelay;
uint256 endBlock = startBlock + votingPeriod;
proposalCount++;
newProposal.id = proposalCount;
newProposal.proposer = msg.sender;
newProposal.targets = targets;
newProposal.values = values;
newProposal.signatures = signatures;
newProposal.calldatas = calldatas;
newProposal.startBlock = startBlock;
newProposal.endBlock = endBlock;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(
newProposal.id,
msg.sender,
targets,
values,
signatures,
calldatas,
startBlock,
endBlock,
description
);
return newProposal.id;
}
| 5,354,330 |
./full_match/11155111/0xdbB6d1acdfd7A803401F377149a8C5a82c684F1f/sources/contracts/GameFactory.sol | uint256 _entryPrice = games[_gameId].entryPrice;require(msg.value >= _entryPrice, "Please send funds for the correct entry price");require(games[_gameId].status == Status.Open, "Game is not currently open"); | function buyEntries(uint256 _gameId, uint256 _numEntries) public payable {
require(!factoryPaused, "Game Factory is currently paused. Come back later");
require(msg.sender != games[_gameId].owner, "You own the Game. You can not enter");
bool matchingTierFlag = false;
for(uint i = 0; i < 5; i++) {
if(games[_gameId].prices[i].number == _numEntries && games[_gameId].prices[i].price == msg.value) {
matchingTierFlag = true;
}
}
require(matchingTierFlag, "That is not a valid purchase");
Purchase memory purchase = Purchase({
id: nextPurchaseId,
upperBound: nextEntryId + (_numEntries - 1),
owner: msg.sender,
parentGameId: _gameId,
amountSpent: msg.value,
numEntries: _numEntries
});
User memory user = users[msg.sender];
if(!user.hasValue) {
user.wallet = msg.sender;
user.hasValue = true;
users[msg.sender].purchaseList.push(purchase.id);
users[msg.sender].purchaseList.push(purchase.id);
}
if(!hasEnteredGame[msg.sender][_gameId]) {
hasEnteredGame[msg.sender][_gameId] = true;
games[_gameId].uniqueEntrants++;
}
purchases[purchase.id] = purchase;
games[_gameId].purchaseList.push(purchase.id);
games[_gameId].nextEntryId += _numEntries;
nextPurchaseId += 1;
| 3,798,153 |
./full_match/5/0x32ff4D05236E95FF60299E9b7BaB351179138389/sources/contracts/core/libraries/BaseSplitCodeFactory.sol | Returns the creation code that will result in a contract being deployed with `constructorArgs`./ This function exists because `abi.encode()` cannot be instructed to place its result at a specific address. We need for the ABI-encoded constructor arguments to be located immediately after the creation code, but cannot rely on `abi.encodePacked()` to perform concatenation as that would involve copying the creation code, which would be prohibitively expensive. Instead, we compute the creation code in a pre-allocated array that is large enough to hold both the creation code and the constructor arguments, and then copy the ABI-encoded arguments (which should not be overly long) right after the end of the creation code. Immutable variables cannot be used in assembly, so we store them in the stack first. First, we allocate memory for `code` by retrieving the free memory pointer and then moving it ahead of `code` by the size of the creation code plus constructor arguments, and 32 bytes for the array length. We now store the length of the code plus constructor arguments. Next, we concatenate the creation code stored in A and B. | function _getCreationCodeWithArgs(bytes memory constructorArgs)
private
view
returns (bytes memory code)
{
address creationCodeContractA = _creationCodeContractA;
uint256 creationCodeSizeA = _creationCodeSizeA;
address creationCodeContractB = _creationCodeContractB;
uint256 creationCodeSizeB = _creationCodeSizeB;
uint256 creationCodeSize = creationCodeSizeA + creationCodeSizeB;
uint256 constructorArgsSize = constructorArgs.length;
uint256 codeSize = creationCodeSize + constructorArgsSize;
assembly {
code := mload(0x40)
mstore(0x40, add(code, add(codeSize, 32)))
mstore(code, codeSize)
let dataStart := add(code, 32)
extcodecopy(creationCodeContractA, dataStart, 0, creationCodeSizeA)
extcodecopy(creationCodeContractB, add(dataStart, creationCodeSizeA), 0, creationCodeSizeB)
}
uint256 constructorArgsCodeDataPtr;
assembly {
constructorArgsDataPtr := add(constructorArgs, 32)
constructorArgsCodeDataPtr := add(add(code, 32), creationCodeSize)
}
_memcpy(constructorArgsCodeDataPtr, constructorArgsDataPtr, constructorArgsSize);
}
| 1,940,698 |
./full_match/5/0x1aF7041005ab72C4b0fF0365ad5Aa2c5D90b9901/sources/contracts/CrowdFunding.sol | Allow users to refund the money collected if target is not reached. Get the campaign. check if the campaign was successfully completed. Check if the deadline for the campaign is exceeded. Check if the target has been reached. Check if the owner is not calling the transaction. check if the amount is already withdrawn by campaign owner. Find the index of the donator in the donators array. | function refund(uint256 _id) public {
Campaign storage campaign = campaigns[_id];
require(
campaign.owner != address(0),
"Campaign was successfully completed"
);
require(campaign.deadline < block.timestamp, "Deadline not met");
require(campaign.AmountCollected < campaign.target, "Target reached");
require(msg.sender != campaign.owner, "Owner can't call transaction");
require(
campaign.AmountCollected > 0,
"Amount has already been withdrawn by campaign owner"
);
uint256 donatorIndex = 0;
bool foundDonator = false;
for (uint256 i = 0; i < campaign.donators.length; i++) {
if (campaign.donators[i] == msg.sender) {
donatorIndex = i;
foundDonator = true;
break;
}
}
foundDonator == true,
"You haven't donated to the campaign yet"
);
campaign.donators.length - 1
];
campaign.donators.pop();
campaign.donations.length - 1
];
campaign.donations.pop();
require(sent == true, "Failed to send refund");
}
| 1,910,898 |
/**
*Submitted for verification at FtmScan.com on 2021-10-11
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
/**
* @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 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 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);
}
}
interface RarityLandStorage {
function getLandFee(uint256 summoner)external view returns(bool,uint256);
function getLandCoordinates(uint256 summoner) external view returns(bool,uint256 x,uint256 y);
function getSummonerCoordinates(uint256 summoner)external view returns(bool,uint256 x,uint256 y);
function getLandIndex(uint256 summoner)external view returns(bool result,uint256 landIndex);
function getSummoner(uint256 lIndex)external view returns(bool result,uint256 summoner);
function totalSupply() external view returns (uint256 supply);
}
interface rarity {
function level(uint) external view returns (uint);
function getApproved(uint) external view returns (address);
function ownerOf(uint) external view returns (address);
function summoner(uint) external view returns (uint _xp, uint _log, uint _class, uint _level);
}
contract DarkPlanetUserBaseLayer is Ownable {
//main-Rarity: 0xce761D788DF608BD21bdd59d6f4B54b2e27F25Bb
rarity constant rm = rarity(0xce761D788DF608BD21bdd59d6f4B54b2e27F25Bb);
address public rlsAddr;
//Maximum number of summoners in a piece of land
uint256 private _maxSummoners;
//In this cycle, the summoner needs to be activated once, otherwise, it will enter a dangerous state.
uint256 private _activePeriod;
struct summonerInfo {
uint256 startActiveTime;
uint256 lastActiveTime;
//1-active, 0-dead
uint256 state;
uint256 currentLandIndex;
uint256 currentLocationIndex;
}
//summoner -> summonerInfo
mapping(uint256 => summonerInfo) private _summonersInfo;
//land -> summonersAmount(<100)
mapping(uint256 => uint256)private _landSummonersAmount;
mapping(uint256 => uint256)private _indexSummoner;
function isRarityOwner(uint256 summoner) internal view returns (bool) {
address rarityAddress = rm.ownerOf(summoner);
return rarityAddress == msg.sender;
}
function getRLS()internal view returns(RarityLandStorage){
require(rlsAddr != address(0),"no rlsAddr .");
return RarityLandStorage(rlsAddr);
}
function setRLS(address rls)public onlyOwner{
rlsAddr = rls;
}
function setMaxSummoners(uint256 maxValue)public onlyOwner {
_maxSummoners = maxValue;
}
function setActivePeriod(uint256 activePeriod)public onlyOwner {
require(activePeriod > 0,"activePeriod error .");
_activePeriod = activePeriod * 1 days;
}
function activate(uint256 summoner)public returns(bool){
require(summoner != 0, "no support 0 .");
require(isRarityOwner(summoner),"no owner .");
(bool result,uint256 lIndex) = getLandLocationForSummoner(summoner);
require(result,"(0,0),error .");
summonerInfo memory sInfo = _summonersInfo[summoner];
if( sInfo.state == 1 &&
_landSummonersAmount[sInfo.currentLandIndex] > 0){
if(lIndex == sInfo.currentLandIndex){
sInfo.lastActiveTime = block.timestamp;
_summonersInfo[summoner] = sInfo;
return true;
}else{
uint256 sLocation = sInfo.currentLandIndex * 100 + sInfo.currentLocationIndex;
uint256 last_sLocation = sInfo.currentLandIndex * 100 + _landSummonersAmount[sInfo.currentLandIndex] - 1;
if(sLocation == last_sLocation){
_indexSummoner[sLocation] = 0;
}else{
_indexSummoner[sLocation] = _indexSummoner[last_sLocation];
}
_landSummonersAmount[sInfo.currentLandIndex] = _landSummonersAmount[sInfo.currentLandIndex] - 1;
}
}
require(_landSummonersAmount[lIndex] < _maxSummoners, "Max value, error.");
sInfo.startActiveTime = block.timestamp;
sInfo.lastActiveTime = block.timestamp;
sInfo.state = 1;
sInfo.currentLandIndex = lIndex;
sInfo.currentLocationIndex = _landSummonersAmount[lIndex];
_summonersInfo[summoner] = sInfo;
uint256 sIndex = lIndex * 100 + _landSummonersAmount[lIndex];
_indexSummoner[sIndex] = summoner;
_landSummonersAmount[lIndex] = _landSummonersAmount[lIndex] + 1;
return true;
}
function exile(uint256 mySummoner,uint256 sIndex)public {
require(mySummoner != 0, "no support 0 .");
require(isRarityOwner(mySummoner),"no owner .");
(bool result,uint256 lIndex) = getRLS().getLandIndex(mySummoner);
require(result,"no land,error .");
uint256 lsAmount = _landSummonersAmount[lIndex];
require(sIndex < lsAmount,"exile,sIndex,error.");
uint256 sLocation = lIndex * 100 + sIndex;
uint256 summoner = _indexSummoner[sLocation];
(,uint256 state) = getSummonerState(summoner);
require(state != 1,"It is not a dangerous state. error !");
summonerInfo memory sInfo = _summonersInfo[summoner];
sInfo.state = 0;
_summonersInfo[summoner] = sInfo;
uint256 last_sLocation = lIndex * 100 + lsAmount - 1;
if(sLocation == last_sLocation){
_indexSummoner[sLocation] = 0;
}else{
_indexSummoner[sLocation] = _indexSummoner[last_sLocation];
}
_landSummonersAmount[lIndex] = _landSummonersAmount[lIndex] - 1;
}
function getLandLocationForSummoner(uint256 summoner) public view returns(bool,uint256){
(,uint256 x,uint256 y) = getRLS().getSummonerCoordinates(summoner);
if(x == 0 && y == 0){
//invalid
return(false,0);
}
uint256 lIndex = x / 1000;
return(true,lIndex);
}
//0-dead,1-safe, 2-dangerous(time expired), 3-dangerous(location error)
//severity: 0 > 3 > 2
function getSummonerState(uint256 summoner)public view returns(bool,uint256 state){
if(summoner == 0){
return (false,0);
}
summonerInfo memory sInfo = _summonersInfo[summoner];
if(sInfo.state == 0){
return(true,0);
}
(,uint256 x,) = getRLS().getSummonerCoordinates(summoner);
uint256 lIndex = x/1000;
if(lIndex != sInfo.currentLandIndex){
return(true,3);
}
if((block.timestamp - sInfo.lastActiveTime) > _activePeriod){
return(true,2);
}
return (true,1);
}
//time unit: s
function getSummonerTimeInfo(uint256 summoner)public view returns(
bool result,
uint256 state,
uint256 sTime,
uint256 lTime){
if(summoner == 0){
return (false,0,0,0);
}
(,uint256 s_state) = getSummonerState(summoner);
summonerInfo memory sInfo = _summonersInfo[summoner];
return(true,s_state,sInfo.startActiveTime,sInfo.lastActiveTime);
}
//time unit: s
function getSummonerInfo(uint256 summoner)public view returns(
bool r_result,
uint256 r_state,
uint256 tTime,
uint256 rTime){
if(summoner == 0){
return (false,0,0,0);
}
(,uint256 state) = getSummonerState(summoner);
summonerInfo memory sInfo = _summonersInfo[summoner];
if(state == 0){
return(true,0,0,0);
}
tTime = block.timestamp - sInfo.startActiveTime;
uint256 intervalTime = block.timestamp - sInfo.lastActiveTime;
if(intervalTime >= _activePeriod){
return (true,state,tTime,0);
}
return (true,state,tTime,(_activePeriod-intervalTime));
}
function getSummonerTimeInfo_MyLand(uint256 mySummoner,uint256 sIndex)public view returns(
bool r_result,
uint256 r_state,
uint256 sTime,
uint256 lTime){
if(mySummoner == 0){
return (false,0,0,0);
}
(bool result,uint256 lIndex) = getRLS().getLandIndex(mySummoner);
if(!result){
return (false,0,0,0);
}
uint256 lsAmount = _landSummonersAmount[lIndex];
if(sIndex >= lsAmount){
return (false,0,0,0);
}
uint256 sLocation = lIndex * 100 + sIndex;
uint256 summoner = _indexSummoner[sLocation];
(,uint256 state) = getSummonerState(summoner);
summonerInfo memory sInfo = _summonersInfo[summoner];
return(true,state,sInfo.startActiveTime,sInfo.lastActiveTime);
}
function getSummonerInfo_MyLand(uint256 mySummoner,uint256 sIndex)public view returns(
bool r_result,
uint256 r_state,
uint256 tTime,
uint256 rTime){
if(mySummoner == 0){
return (false,0,0,0);
}
(bool result,uint256 lIndex) = getRLS().getLandIndex(mySummoner);
if(!result){
return (false,0,0,0);
}
uint256 lsAmount = _landSummonersAmount[lIndex];
if(sIndex >= lsAmount){
return (false,0,0,0);
}
uint256 sLocation = lIndex * 100 + sIndex;
uint256 summoner = _indexSummoner[sLocation];
(,uint256 state) = getSummonerState(summoner);
summonerInfo memory sInfo = _summonersInfo[summoner];
if(state == 0){
return(true,0,0,0);
}
tTime = block.timestamp - sInfo.startActiveTime;
uint256 intervalTime = block.timestamp - sInfo.lastActiveTime;
if(intervalTime >= _activePeriod){
return (true,state,tTime,0);
}
return (true,state,tTime,(_activePeriod-intervalTime));
}
//The number of alive summoners on the current land
function getSummonerAmount_MyLand(uint256 summoner)public view returns(bool,uint256){
(bool result,uint256 lIndex) = getRLS().getLandIndex(summoner);
if(!result){
return (result,lIndex);
}
return (result,_landSummonersAmount[lIndex]);
}
function getMaxSummonersAmount_Land()public view returns(uint256){
return _maxSummoners;
}
function getActivePeriod()public view returns(uint256){
return _activePeriod;
}
} | 0-dead,1-safe, 2-dangerous(time expired), 3-dangerous(location error)severity: 0 > 3 > 2 | function getSummonerState(uint256 summoner)public view returns(bool,uint256 state){
if(summoner == 0){
return (false,0);
}
summonerInfo memory sInfo = _summonersInfo[summoner];
if(sInfo.state == 0){
return(true,0);
}
(,uint256 x,) = getRLS().getSummonerCoordinates(summoner);
uint256 lIndex = x/1000;
if(lIndex != sInfo.currentLandIndex){
return(true,3);
}
if((block.timestamp - sInfo.lastActiveTime) > _activePeriod){
return(true,2);
}
return (true,1);
}
| 925,995 |
./full_match/11155111/0xFCc8a75ab4e55E1E9c3d8d1A8d833CB7BF45F5B7/sources/_ganache/console.log/console.sol | Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution ```solidity uint256 count = 5; console.log('count: %d', count); console.log('count:', count); ``` See `util.format()` for more information./ | function log(string memory value1, bool value2, bool value3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", value1, value2, value3));
}
| 3,821,378 |
pragma solidity ^0.4.24;
/*************************************************
* Title: ERC20 Token
* Author: https://github.com/willitscale
* Date: NA
* Code version: NA
* Availability: https://github.com/willitscale/learning-solidity/blob/master/tutorial-10/MyFirstToken.sol
*************************************************/
/// @title Event Token (ET) implementation
/// @author keshik
/// @dev The contract declares the required functions, modifiers and events for the Event Token
import "./StandardToken.sol";
import "./ERC20.sol";
import "./ERC223.sol";
import "./EventContract.sol";
contract EventToken is StandardToken("EventToken", "ET", 18, 500000000), ERC20, ERC223{
using SafeMath for uint256;
address private _controller1;
address private _controller2;
bool private _paused;
uint256 private _numberOfEvents;
// MaxLimit of uint256
uint256 constant MAX_LIMIT = 2**256 -1;
// Mapping to store addresses and balances
mapping (address => uint256) internal _balanceOf;
// Nested Mapping to store allowances
mapping (address => mapping (address => uint256)) internal _allowance;
constructor (address _ctrl2) public{
_controller1 = msg.sender;
_controller2 = _ctrl2;
_balanceOf[msg.sender] = _totalSupply;
_paused = false;
_numberOfEvents = 0;
}
modifier onlyCtrlLevel{
require(msg.sender == _controller1 || msg.sender == _controller2);
_;
}
modifier onlyCtrl1{
require(msg.sender == _controller1);
_;
}
modifier onlyCtrl2{
require(msg.sender == _controller2);
_;
}
modifier isPaused{
require(_paused == true);
_;
}
modifier isNotPaused{
require(_paused == false);
_;
}
/// @param _owner The address
/// @return balance of the of the address
function balanceOf(address _owner) public view returns (uint256){
return _balanceOf[_owner];
}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) external isNotPaused returns (bool){
require(_balanceOf[msg.sender] >= _value);
require(_value > 0);
require(_value < MAX_LIMIT);
require(!isContract(_to));
require(_to != address(0));
require(_allowance[msg.sender][_to] >= _value);
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value);
_balanceOf[_to] = _balanceOf[_to].add(_value);
_allowance[msg.sender][_to] = _allowance[msg.sender][_to].sub(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @param _contractId Event pointer
/// @return Whether the transfer was successful or not
function transferToContract(address _to, uint256 _value, uint _contractId) external isNotPaused returns (bool){
require(_value > 0);
require(_value < MAX_LIMIT);
require(_balanceOf[msg.sender] >= _value);
require(isContract(_to));
require(_to != address(0));
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value);
_balanceOf[_to] = _balanceOf[_to].add(_value);
_allowance[msg.sender][_to] = _allowance[msg.sender][_to].sub(_value);
EventContract _contract = EventContract(_to);
_contract.tokenFallback(msg.sender, _value, _contractId);
emit Transfer(msg.sender, _to, _value, _contractId);
return true;
}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) external isNotPaused returns (bool){
require(_to != address(0));
require(_balanceOf[_from] >= _value);
require(_allowance[_from][msg.sender] >= _value);
require(_value > 0);
require(_value < MAX_LIMIT);
_balanceOf[_from] = _balanceOf[_from].sub(_value);
_balanceOf[_to] = _balanceOf[_to].add(_value);
_allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) external isNotPaused returns (bool){
require(_value > 0);
require(_value < MAX_LIMIT);
require(_spender != address(0));
_allowance[msg.sender][_spender] = _allowance[msg.sender][_spender].add(_value);
emit Approval(msg.sender, _spender, _value);
return true;
}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256){
return _allowance[_owner][_spender];
}
/// @param _address The ethereum address to be verified
/// @return Amount of remaining tokens allowed to spent
function isContract(address _address) public view returns (bool){
uint256 codeLength;
assembly{
codeLength := extcodesize(_address)
}
return codeLength > 0;
}
function getCtrlAddress1() public view returns (address){
return _controller1;
}
function getCtrlAddress2() public view returns (address){
return _controller2;
}
/// @notice change controller address 1. This function can only be called by the existing controller1
/// @param _newCtrl1 The address of the new controller
/// @return Whether the setter was successful or not
function setCtrlAddress1(address _newCtrl1) external onlyCtrl1 returns (bool){
require(_newCtrl1 != address(0));
_controller1 = _newCtrl1;
return true;
}
/// @notice change controller address 2. This function can only be called by the existing controller2
/// @param _newCtrl2 The address of the new controller
/// @return Whether the setter was successful or not
function setCtrlAddress2(address _newCtrl2) external onlyCtrl2 returns (bool){
require(_newCtrl2 != address(0));
_controller2 = _newCtrl2;
return true;
}
/// @notice Pause the contract. Can only be called by the controllers
/// @return Whether the contract was successfully paused or not
function pause() external onlyCtrlLevel isNotPaused returns (bool){
_paused = true;
return true;
}
/// @notice Resume the contract. Can only be called by the controllers
/// @return Whether the contract was successfully resumed or not
function resume() external onlyCtrlLevel isPaused returns (bool){
_paused = false;
return true;
}
/// @return Whether the contract is paused or not
function isActive() external view returns (bool){
return _paused == false;
}
}
| send `_value` token to `_to` from `_from` on the condition it is approved by `_from` _from The address of the sender _to The address of the recipient _value The amount of token to be transferred return Whether the transfer was successful or not | function transferFrom(address _from, address _to, uint256 _value) external isNotPaused returns (bool){
require(_to != address(0));
require(_balanceOf[_from] >= _value);
require(_allowance[_from][msg.sender] >= _value);
require(_value > 0);
require(_value < MAX_LIMIT);
_balanceOf[_from] = _balanceOf[_from].sub(_value);
_balanceOf[_to] = _balanceOf[_to].add(_value);
_allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
| 12,780,468 |
./full_match/4/0x88cd87A06D6b0F1dB961F02b321E3C071336b570/sources/contracts/L1/messaging/L1StandardBridge.sol | @inheritdoc IL1StandardBridge/ | function depositETHTo(
address _to,
uint32 _l2Gas,
bytes calldata _data
) external payable {
_initiateETHDeposit(msg.sender, _to, _l2Gas, _data);
}
| 650,606 |
./full_match/137/0x16D66b01664bc834f5db13D01E51E1Fa7C44f03B/sources/browser/NFT721.sol | Returns the number of values in the set. O(1)./ | function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
| 4,781,829 |
// SPDX-License-Identifier: MIT
/*
* Work in progress
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
contract NFT is ERC721, ERC721URIStorage, ERC721Enumerable {
address payable public _owner;
bool public selling;
uint256 public price;
uint256 public token_id;
event Purchase(address owner, uint256 price, uint256 id, string uri);
event AttemptPurchase(address owner, uint256 price, uint256 id, string uri);
constructor(address origin) ERC721("StoryElement", "SE") {
_owner = payable(origin);
price = 0;
}
function getOwner() public view returns (address) {
return _owner;
}
function isForSale() public view returns (bool) {
return selling;
}
function getPrice() public view returns (uint256) {
return price;
}
/*
* Overrides
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 _token_id
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, _token_id);
}
function _burn(uint256 _token_id)
internal
override(ERC721, ERC721URIStorage)
{
super._burn(_token_id);
}
function tokenURI(uint256 _token_id)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(_token_id);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
modifier onlyOwner(address origin) {
require(origin == _owner);
_;
}
function mint(
address origin,
string memory _tokenURI,
uint256 _token_id,
uint256 _price
) public onlyOwner(origin) returns (bool) {
//uint256 _token_id = totalSupply() + 1;
// @dev console.log not showing up
//console.log("TOKEN: %d", _token_id);
price = _price;
token_id = _token_id;
_mint(address(this), _token_id);
_setTokenURI(_token_id, _tokenURI);
return true;
}
function buy(address origin) external payable {
// _validate();
emit AttemptPurchase(origin, price, token_id, tokenURI(token_id));
require(selling, "Error, Token is not being sold");
require(msg.value >= price, "Error, Token costs more");
// _trade(origin);
// _transfer(address(this), origin, token_id);
_owner.transfer(msg.value);
_owner = payable(origin);
selling = false;
emit Purchase(origin, price, token_id, tokenURI(token_id));
}
function sell(address origin, uint256 new_price)
external
onlyOwner(origin)
{
price = new_price;
selling = true;
}
function _validate() internal {
require(selling, "Error, Token is not being sold");
require(msg.value >= price, "Error, Token costs more");
}
function _trade(address origin) internal {
_transfer(address(this), origin, token_id);
_owner.transfer(msg.value);
selling = false;
}
}
| uint256 _token_id = totalSupply() + 1; console.log not showing upconsole.log("TOKEN: %d", _token_id); | function mint(
address origin,
string memory _tokenURI,
uint256 _token_id,
uint256 _price
) public onlyOwner(origin) returns (bool) {
price = _price;
token_id = _token_id;
_mint(address(this), _token_id);
_setTokenURI(_token_id, _tokenURI);
return true;
}
| 6,439,505 |
./partial_match/56/0x15B3d410fCd0d695E1bbe4F717F8E1B6D0Fb2D0C/sources/KetchupBar.sol | Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair 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), "FRIES::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "FRIES::delegateBySig: invalid nonce");
require(now <= expiry, "FRIES::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 11,195,320 |
pragma solidity >=0.6.0;
pragma experimental ABIEncoderV2;
import './PriceAPI.sol';
import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/math/SafeMath.sol";
import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/ReentrancyGuard.sol";
/// @title Interface for Market Contract
/// @author Kuldeep K Srivastava
interface IMarket {
enum Action {lt, gt, eq}
enum State {active, inactive}
struct MarketDetails {
State state;
string token1;
string token2;
uint amount;
Action action;
uint startTime;
uint interval;
uint endTime;
uint totalVotes;
uint yesVotes;
uint noVotes;
uint yesPrice;
uint noPrice;
bool result;
}
struct Prediction {
uint share;
bool verdict;
}
event predicted(address indexed user, bool verdict, uint share);
event resultDeclared(address indexed market, address user);
event withdrawAmount(address indexed user, uint amount);
// @notice Get all the current details of the market
// @return Market struct with all the details
function getMarket() external returns (MarketDetails memory);
// @notice Allows an end-user to make prediction for the market
// @param _verdict Yes/No selected by end-user
// @param _share Amount of share that user is purchasing for his prediction
// @return Returns true if successful
function predict(bool, uint) external payable returns (bool);
// @notice Resolves the market after the market's prediction function is closed
// @return Returns true if successful
function result() external returns (bool);
// @notice Allows user to withdraw their winning amount after market is resolved
// @return Returns true if successful
function withdraw() external returns (bool);
}
/// @title Cryptocurrency Price Prediction Market
/// @dev Inherits IMarket Interface, APIConsumer Contract
/// @author Kuldeep K. Srivastava
contract Market is IMarket,ReentrancyGuard,APIConsumer {
using SafeMath for uint;
// @notice Address of the user who created this market
// @return Returns market owner's address
address public marketOwner;
MarketDetails private M;
mapping(address => Prediction) private predictions;
mapping(address => bool) private predictors;
constructor (
address owner,
string memory token1,
string memory token2,
Action action,
uint amount,
uint interval
) public {
marketOwner = owner;
M.state = State.active;
M.token1 = token1;
M.token2 = token2;
M.amount = amount;
M.action = action;
M.startTime = block.timestamp;
M.interval = interval;
M.endTime = M.startTime + interval;
M.totalVotes = 0;
M.yesVotes = 0;
M.noVotes = 0;
M.yesPrice = 50 wei;
M.noPrice= 50 wei;
}
bool private stopped = false;
modifier stopInEmergency { require(!stopped); _; }
modifier onlyInEmergency { require(stopped); _; }
modifier marketActive() {
require(M.endTime >= block.timestamp,"Market is not accepting prediction anymore");
_;
}
modifier marketInProgress() {
require(M.endTime < block.timestamp,"Market is still active");
require(M.state == State.active,"Market is already resolved");
require(marketResolved == false);
_;
}
modifier marketInactive() {
require(M.endTime < block.timestamp,"Market is still active");
require(M.state == State.inactive,"Market is not resolved yet");
require(marketResolved == true);
_;
}
// @notice Get all the current details of the market
// @return Market struct with all the details
function getMarket() public override returns (MarketDetails memory) {
return M;
}
// @notice Allows an end-user to make prediction for the market
// @dev It uses circuit breaker pattern.
// @param _verdict Yes/No selected by end-user
// @param _share Amount of share that user is purchasing for his prediction
// @return Returns true if successful
function predict(bool _verdict, uint _share) public override payable marketActive stopInEmergency returns (bool) {
// market not close
// not already predicted
// amount is correct
// create a new predict
// add to predictions list
// modify yes or no votes and profits
// return true
// use circuit breaker pattern
require(predictors[msg.sender] == false, "You have already participated in this market");
if(_verdict) {
require((M.yesPrice.mul(_share)) <= msg.value, "Not enough amount");
} else {
require((M.noPrice.mul(_share)) <= msg.value, "Not enough amount");
}
M.totalVotes = M.totalVotes.add(1);
if(_verdict) {
M.yesVotes = M.yesVotes.add(1);
M.yesPrice = ((M.yesVotes.mul(10**2)).div(M.totalVotes));
M.noPrice = ((M.noVotes.mul(10**2)).div(M.totalVotes));
} else {
M.noVotes = M.noVotes.add(1);
M.noPrice = ((M.noVotes.mul(10**2)).div(M.totalVotes));
M.yesPrice = ((M.yesVotes.mul(10**2)).div(M.totalVotes));
}
Prediction memory p = Prediction({
share:_share,
verdict: _verdict
});
predictions[msg.sender] = p;
predictors[msg.sender] = true;
emit predicted(msg.sender, _verdict, _share);
return true;
}
// @notice Resolves the market after the market's prediction function is closed
// @dev It uses chainlink oracle for doing the same.
// @return Returns true if successful
function result() public override marketInProgress returns(bool) {
// require only owner or one of the depositor
// call API
// get API response
// change result value
// change State to inactive
require(msg.sender == marketOwner || predictors[msg.sender], "Not authorised");
// resultAmount = 400;
// marketResolved = true;
requestVolumeData(M.token1, M.token2);
M.state = State.inactive;
stopped = true;
emit resultDeclared(address(this), msg.sender);
return true;
}
// @notice Allows user to withdraw their winning amount after market is resolved
// @dev It uses withdrawl pattern
// @return Returns true if successful
function withdraw() public override marketInactive onlyInEmergency nonReentrant returns(bool) {
// withdrawl pattern
// check user has deposited
// calculate amount to pay
// check if enough balance
// change share to 0
// tranfer eth to the user
require(predictors[msg.sender], "Not authorised");
require(predictions[msg.sender].share != 0, "Already withdrawn");
bool finalResult = false;
if(M.action == Action.lt) {
finalResult = M.amount.mul(10**18) < resultAmount;
} else if(M.action == Action.gt) {
finalResult = M.amount.mul(10**18) > resultAmount;
} else {
finalResult = M.amount.mul(10**18) == resultAmount;
}
Prediction memory p = predictions[msg.sender];
require(finalResult == p.verdict, "Sorry you lost");
uint winningAmount;
if(finalResult){
winningAmount = (address(this).balance).div(M.yesVotes);
} else {
winningAmount = (address(this).balance).div(M.noVotes);
}
require(address(this).balance >= (winningAmount.mul(p.share)), "Not enough balance");
msg.sender.transfer(winningAmount.mul(p.share));
emit withdrawAmount(msg.sender, winningAmount.mul(p.share));
predictions[msg.sender].share = 0;
return true;
}
// no price becomes 0 after first votes
// noprice + yesPrice sometimes < 100 eg. 66 + 33
// upgradablility
// share is not regarded in calculating final winning prize
// calculate winning prize only once when result comes from API
} | Allows user to withdraw their winning amount after market is resolved It uses withdrawl pattern return Returns true if successful withdrawl pattern check user has deposited calculate amount to pay check if enough balance change share to 0 tranfer eth to the user | function withdraw() public override marketInactive onlyInEmergency nonReentrant returns(bool) {
require(predictors[msg.sender], "Not authorised");
require(predictions[msg.sender].share != 0, "Already withdrawn");
bool finalResult = false;
if(M.action == Action.lt) {
finalResult = M.amount.mul(10**18) < resultAmount;
finalResult = M.amount.mul(10**18) > resultAmount;
finalResult = M.amount.mul(10**18) == resultAmount;
}
Prediction memory p = predictions[msg.sender];
require(finalResult == p.verdict, "Sorry you lost");
uint winningAmount;
if(finalResult){
winningAmount = (address(this).balance).div(M.yesVotes);
winningAmount = (address(this).balance).div(M.noVotes);
}
require(address(this).balance >= (winningAmount.mul(p.share)), "Not enough balance");
msg.sender.transfer(winningAmount.mul(p.share));
emit withdrawAmount(msg.sender, winningAmount.mul(p.share));
predictions[msg.sender].share = 0;
return true;
}
| 2,473,750 |
pragma solidity ^0.4.16;
// METADOLLAR (DOL) VAULT - COPYRIGHT 2018 METADOLLAR.ORG
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/issues/20
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
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.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint capacity) internal pure {
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
/**
* @dev Appends a byte array to the end of the buffer. Reverts if doing so
* would exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Reverts if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @dev Appends a byte to the end of the buffer. Reverts if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure 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 pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) throw;
}
}
contract ERC20Interface {
/// @notice Total supply of Metadollar
function totalSupply() constant returns (uint256 totalAmount);
/// @notice Get the account balance of another account with address_owner
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice Send_value amount of tokens to address_to
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice Send_value amount of tokens from address_from to address_to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice Allow_spender to withdraw from your account, multiple times, up to the _value amount.
/// @notice If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) returns (bool success);
/// @notice Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
/// @notice Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/// @notice Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract owned{
address public owner;
address constant supervisor = 0x772F3122a8687ee3401bafCA91e873CC37106a7A;//0x97f7298435e5a8180747E89DBa7759674c5c35a5;
function owned(){
owner = msg.sender;
}
/// @notice Functions with this modifier can only be executed by the owner
modifier isOwner {
assert(msg.sender == owner || msg.sender == supervisor);
_;
}
/// @notice Transfer the ownership of this contract
function transferOwnership(address newOwner);
event ownerChanged(address whoTransferredOwnership, address formerOwner, address newOwner);
}
contract METADOLLAR is ERC20Interface, owned, SafeMath, usingOraclize {
string public constant name = "METADOLLAR";
string public constant symbol = "DOL";
uint public constant decimals = 18;
uint256 public _totalSupply = 1000000000000000000000000000;
uint256 public icoMin = 1000000000000000000000000000;
uint256 public preIcoLimit = 1;
uint256 public countHolders = 0; // Number of DOL holders
uint256 public amountOfInvestments = 0; // amount of collected wei
uint256 bank;
uint256 preICOprice;
uint256 ICOprice;
uint256 public currentTokenPrice; // Current Price of DOL
uint256 public commRate;
bool public preIcoIsRunning;
bool public minimalGoalReached;
bool public icoIsClosed;
bool icoExitIsPossible;
//Balances for each account
mapping (address => uint256) public tokenBalanceOf;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
//list with information about frozen accounts
mapping(address => bool) frozenAccount;
//this generate a public event on a blockchain that will notify clients
event FrozenFunds(address initiator, address account, string status);
//this generate a public event on a blockchain that will notify clients
event BonusChanged(uint8 bonusOld, uint8 bonusNew);
//this generate a public event on a blockchain that will notify clients
event minGoalReached(uint256 minIcoAmount, string notice);
//this generate a public event on a blockchain that will notify clients
event preIcoEnded(uint256 preIcoAmount, string notice);
//this generate a public event on a blockchain that will notify clients
event priceUpdated(uint256 oldPrice, uint256 newPrice, string notice);
//this generate a public event on a blockchain that will notify clients
event withdrawed(address _to, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event deposited(address _from, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event orderToTransfer(address initiator, address _from, address _to, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event tokenCreated(address _creator, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event tokenDestroyed(address _destroyer, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event icoStatusUpdated(address _initiator, string status);
/// @notice Constructor of the contract
function METADOLLAR() {
preIcoIsRunning = false;
minimalGoalReached = true;
icoExitIsPossible = false;
icoIsClosed = false;
tokenBalanceOf[this] += _totalSupply;
allowed[this][owner] = _totalSupply;
allowed[this][supervisor] = _totalSupply;
currentTokenPrice = 728;
preICOprice = 780;
ICOprice = 1;
commRate = 100;
updatePrices();
updateICOPrice();
}
function () payable {
require(!frozenAccount[msg.sender]);
if(msg.value > 0 && !frozenAccount[msg.sender]) {
buyToken();
}
}
/// @notice Returns a whole amount of DOL
function totalSupply() constant returns (uint256 totalAmount) {
totalAmount = _totalSupply;
}
/// @notice What is the balance of a particular account?
function balanceOf(address _owner) constant returns (uint256 balance) {
return tokenBalanceOf[_owner];
}
/// @notice Shows how much tokens _spender can spend from _owner address
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice Calculates amount of ETH needed to buy DOL
/// @param howManyTokenToBuy - Amount of tokens to calculate
function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) {
if(howManyTokenToBuy > 0) {
summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice;
}else {
summarizedPriceInWeis = 0;
}
}
/// @notice Shows if account is frozen
/// @param account - Accountaddress to check
function checkFrozenAccounts(address account) constant returns (bool accountIsFrozen) {
accountIsFrozen = frozenAccount[account];
}
/// @notice Buy DOL from VAULT by sending ETH
function buy() payable public {
require(!frozenAccount[msg.sender]);
require(msg.value > 0);
buyToken();
}
/// @notice Sell DOL and receive ETH from VAULT
function sell(uint256 amount) {
require(!frozenAccount[msg.sender]);
require(tokenBalanceOf[msg.sender] >= amount); // checks if the sender has enough to sell
require(amount > 0);
require(currentTokenPrice > 0);
_transfer(msg.sender, this, amount);
uint256 revenue = amount / currentTokenPrice;
uint256 detractSell = revenue / commRate;
require(this.balance >= revenue);
msg.sender.transfer(revenue - detractSell); // sends ether to the seller: it's important to do this last to prevent recursion attacks
}
/// @notice Transfer amount of tokens from own wallet to someone else
function transfer(address _to, uint256 _value) returns (bool success) {
assert(msg.sender != address(0));
assert(_to != address(0));
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(tokenBalanceOf[msg.sender] >= _value);
require(tokenBalanceOf[msg.sender] - _value < tokenBalanceOf[msg.sender]);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(_value > 0);
_transfer(msg.sender, _to, _value);
return true;
}
/// @notice Send _value amount of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
assert(msg.sender != address(0));
assert(_from != address(0));
assert(_to != address(0));
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(tokenBalanceOf[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
require(tokenBalanceOf[_from] - _value < tokenBalanceOf[_from]);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(_value > 0);
orderToTransfer(msg.sender, _from, _to, _value, "Order to transfer tokens from allowed account");
_transfer(_from, _to, _value);
allowed[_from][msg.sender] -= _value;
return true;
}
/// @notice Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// @notice If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
assert(_spender != address(0));
require(_value >= 0);
allowed[msg.sender][_spender] = _value;
return true;
}
/// @notice Check if minimal goal is reached
function checkMinimalGoal() internal {
if(tokenBalanceOf[this] <= _totalSupply - icoMin) {
minimalGoalReached = true;
minGoalReached(icoMin, "Minimal goal of ICO is reached!");
}
}
/// @notice Check if service is ended
function checkPreIcoStatus() internal {
if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) {
preIcoIsRunning = false;
preIcoEnded(preIcoLimit, "Token amount for preICO sold!");
}
}
/// @notice Processing each buying
function buyToken() internal {
uint256 value = msg.value;
address sender = msg.sender;
address bank = 0xC51B05696Db965cE6C8efD69Aa1c6BA5540a92d7; // DEPOSIT
require(!icoIsClosed);
require(!frozenAccount[sender]);
require(value > 0);
require(currentTokenPrice > 0);
uint256 amount = value * currentTokenPrice; // calculates amount of tokens
uint256 detract = amount / commRate;
uint256 detract2 = value / commRate;
uint256 finalvalue = value - detract2;
require(tokenBalanceOf[this] >= amount); // checks if contract has enough to sell
amountOfInvestments = amountOfInvestments + (value);
updatePrices();
_transfer(this, sender, amount - detract);
require(this.balance >= finalvalue);
bank.transfer(finalvalue);
if(!minimalGoalReached) {
checkMinimalGoal();
}
}
/// @notice Internal transfer, can only be called by this contract
function _transfer(address _from, address _to, uint256 _value) internal {
assert(_from != address(0));
assert(_to != address(0));
require(_value > 0);
require(tokenBalanceOf[_from] >= _value);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
if(tokenBalanceOf[_to] == 0){
countHolders += 1;
}
tokenBalanceOf[_from] -= _value;
if(tokenBalanceOf[_from] == 0){
countHolders -= 1;
}
tokenBalanceOf[_to] += _value;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
Transfer(_from, _to, _value);
}
/// @notice Set current DOL prices
function updatePrices() internal {
uint256 oldPrice = currentTokenPrice;
if(preIcoIsRunning) {
checkPreIcoStatus();
}
if(preIcoIsRunning) {
currentTokenPrice = preICOprice;
}else{
currentTokenPrice = ICOprice;
}
if(oldPrice != currentTokenPrice) {
priceUpdated(oldPrice, currentTokenPrice, "Token price updated!");
}
}
/// @notice Set current price rate A
/// @param priceForPreIcoInWei - is the amount in wei for one token
function setPreICOPrice(uint256 priceForPreIcoInWei) isOwner {
require(priceForPreIcoInWei > 0);
require(preICOprice != priceForPreIcoInWei);
preICOprice = priceForPreIcoInWei;
updatePrices();
}
/// @notice Set current price rate B
/// @param priceForIcoInWei - is the amount in wei for one token
function setICOPrice(uint256 priceForIcoInWei) isOwner {
require(priceForIcoInWei > 0);
require(ICOprice != priceForIcoInWei);
ICOprice = priceForIcoInWei;
updatePrices();
}
/// @notice Set both prices at the same time
/// @param priceForPreIcoInWei - Price of the token in pre ICO
/// @param priceForIcoInWei - Price of the token in ICO
function setPrices(uint256 priceForPreIcoInWei, uint256 priceForIcoInWei) isOwner {
require(priceForPreIcoInWei > 0);
require(priceForIcoInWei > 0);
preICOprice = priceForPreIcoInWei;
ICOprice = priceForIcoInWei;
updatePrices();
}
/// @notice Set current Commission Rate
/// @param newCommRate - is the amount in wei for one token
function commRate(uint256 newCommRate) isOwner {
require(newCommRate > 0);
require(commRate != newCommRate);
commRate = newCommRate;
updatePrices();
}
/// @notice Set New Bank
/// @param newBank - is the new bank address
function changeBank(uint256 newBank) isOwner {
require(bank != newBank);
bank = newBank;
updatePrices();
}
/// @notice 'freeze? Prevent | Allow' 'account' from sending and receiving tokens
/// @param account - address to be frozen
/// @param freeze - select is the account frozen or not
function freezeAccount(address account, bool freeze) isOwner {
require(account != owner);
require(account != supervisor);
frozenAccount[account] = freeze;
if(freeze) {
FrozenFunds(msg.sender, account, "Account set frozen!");
}else {
FrozenFunds(msg.sender, account, "Account set free for use!");
}
}
/// @notice Create an amount of DOL
/// @param amount - DOL to create
function mintToken(uint256 amount) isOwner {
require(amount > 0);
require(tokenBalanceOf[this] <= icoMin); // owner can create token only if the initial amount is strongly not enough to supply and demand ICO
require(_totalSupply + amount > _totalSupply);
require(tokenBalanceOf[this] + amount > tokenBalanceOf[this]);
_totalSupply += amount;
tokenBalanceOf[this] += amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenCreated(msg.sender, amount, "Additional tokens created!");
}
/// @notice Destroy an amount of DOL
/// @param amount - DOL to destroy
function destroyToken(uint256 amount) isOwner {
require(amount > 0);
require(tokenBalanceOf[this] >= amount);
require(_totalSupply >= amount);
require(tokenBalanceOf[this] - amount >= 0);
require(_totalSupply - amount >= 0);
tokenBalanceOf[this] -= amount;
_totalSupply -= amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenDestroyed(msg.sender, amount, "An amount of tokens destroyed!");
}
/// @notice Transfer the ownership to another account
/// @param newOwner - address who get the ownership
function transferOwnership(address newOwner) isOwner {
assert(newOwner != address(0));
address oldOwner = owner;
owner = newOwner;
ownerChanged(msg.sender, oldOwner, newOwner);
allowed[this][oldOwner] = 0;
allowed[this][newOwner] = tokenBalanceOf[this];
}
/// @notice Transfer ether from smartcontract to admin
function collect() isOwner {
require(this.balance > 0);
withdraw(this.balance);
}
/// @notice Withdraw an amount of ether from VAULT
/// @param summeInWei - amout to withdraw
function withdraw(uint256 summeInWei) isOwner {
uint256 contractbalance = this.balance;
address sender = msg.sender;
require(contractbalance >= summeInWei);
withdrawed(sender, summeInWei, "wei withdrawed");
sender.transfer(summeInWei);
}
/// @notice Deposit an amount of ETH in the VAULT
function deposit() payable isOwner {
require(msg.value > 0);
require(msg.sender.balance >= msg.value);
deposited(msg.sender, msg.value, "wei deposited");
}
/// @notice Stop running VAULT
/// @param icoIsStopped - status if this ICO is stopped
function stopThisIco(bool icoIsStopped) isOwner {
require(icoIsClosed != icoIsStopped);
icoIsClosed = icoIsStopped;
if(icoIsStopped) {
icoStatusUpdated(msg.sender, "Coin offering was stopped!");
}else {
icoStatusUpdated(msg.sender, "Coin offering is running!");
}
}
// the function for setting of ICOPrice
function setICOPriceatDollar(uint val){
ICOprice = val;
}
event Log(string text);
function __callback(bytes32 _myid, string _result) {
require (msg.sender == oraclize_cbAddress());
Log(_result);
ICOprice = parseInt(_result); // let's save it as $ cents
}
function updateICOPrice() payable {
Log("Oraclize query was sent, waiting for the answer..");
oraclize_query("URL","json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD).USD");
}
} | Transfer the ownership to another account newOwner - address who get the ownership | function transferOwnership(address newOwner) isOwner {
assert(newOwner != address(0));
address oldOwner = owner;
owner = newOwner;
ownerChanged(msg.sender, oldOwner, newOwner);
allowed[this][oldOwner] = 0;
allowed[this][newOwner] = tokenBalanceOf[this];
}
| 1,594,760 |
// 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;
/**
* @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;
/**
* @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: 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: Unlicensed
pragma solidity ^0.6.8;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/IMintable.sol";
contract LPStaking is ReentrancyGuard, Ownable {
using SafeMath for uint256;
using Address for address;
using SafeERC20 for IERC20;
event Staked(address indexed from, uint256 amount);
event Withdrawn(address indexed to, uint256 amount);
event Claimed(address indexed to, uint256 amount);
IERC20 public stakeToken;
IMintable public rewardToken;
// reward rate per second
uint256 public rewardRate;
struct UserInfos {
uint256 balance; // stacked balance
uint256 pendingReward; // claimable reward
uint256 rewardPerTokenPaid; // accumulated reward
}
struct PoolInfos {
uint256 lastUpdateTimestamp;
uint256 rewardPerTokenStored;
uint256 totalValueStacked;
}
PoolInfos private _poolInfos;
mapping(address => UserInfos) private _usersInfos; // Users infos per address
uint256 public constant DURATION = 31 days;
uint256 public constant REWARD_ALLOCATION = 16500 * 1e18;
// Farming will be open on 15/03/2021 at 07:00:00 UTC
uint256 public constant FARMING_START_TIMESTAMP = 1615791600;
// No more rewards after 15/04/2021 at 07:00:00 UTC
uint256 public constant FARMING_END_TIMESTAMP =
FARMING_START_TIMESTAMP + DURATION;
bool public farmingStarted = false;
constructor(address stakeToken_, address rewardToken_) public {
require(
stakeToken_.isContract(),
"LPStaking: stakeToken_ should be a contract"
);
require(
stakeToken_.isContract(),
"LPStaking: rewardToken_ should be a contract"
);
stakeToken = IERC20(stakeToken_);
rewardToken = IMintable(rewardToken_);
rewardRate = REWARD_ALLOCATION.div(DURATION);
}
function stake(uint256 amount_) external nonReentrant {
_checkFarming();
_updateReward(msg.sender);
require(
!address(msg.sender).isContract(),
"LPStaking: Please use your individual account"
);
stakeToken.safeTransferFrom(msg.sender, address(this), amount_);
_poolInfos.totalValueStacked = _poolInfos.totalValueStacked.add(
amount_
);
// Add to balance
_usersInfos[msg.sender].balance = _usersInfos[msg.sender].balance.add(
amount_
);
emit Staked(msg.sender, amount_);
}
function withdraw(uint256 amount_) public nonReentrant {
_checkFarming();
_updateReward(msg.sender);
require(amount_ > 0, "LPStaking: Cannot withdraw 0");
require(
amount_ <= balanceOf(msg.sender),
"LPStaking: Insufficent balance"
);
if (amount_ == 0) amount_ = _usersInfos[msg.sender].balance;
// Reduce totalValue
_poolInfos.totalValueStacked = _poolInfos.totalValueStacked.sub(
amount_
);
// Reduce balance
_usersInfos[msg.sender].balance = _usersInfos[msg.sender].balance.sub(
amount_
);
stakeToken.safeTransfer(msg.sender, amount_);
emit Withdrawn(msg.sender, amount_);
}
function claim() public nonReentrant {
_checkFarming();
_updateReward(msg.sender);
uint256 reward = _usersInfos[msg.sender].pendingReward;
if (reward > 0) {
// Reduce first
_usersInfos[msg.sender].pendingReward = 0;
// Send reward
rewardToken.mint(msg.sender, reward);
emit Claimed(msg.sender, reward);
}
}
function withdrawAndClaim(uint256 amount_) public {
withdraw(amount_);
claim();
}
function exit() external {
withdrawAndClaim(balanceOf(msg.sender));
}
function totalValue() external view returns (uint256) {
return _poolInfos.totalValueStacked;
}
function balanceOf(address account_) public view returns (uint256) {
return _usersInfos[account_].balance;
}
function rewardPerToken() public view returns (uint256) {
if (_poolInfos.totalValueStacked == 0) {
return _poolInfos.rewardPerTokenStored;
}
return
_poolInfos.rewardPerTokenStored.add(
lastRewardTimestamp()
.sub(_poolInfos.lastUpdateTimestamp)
.mul(rewardRate) //rate per second
.mul(1e18)
.div(_poolInfos.totalValueStacked)
);
}
function lastRewardTimestamp() public view returns (uint256) {
return Math.min(block.timestamp, FARMING_END_TIMESTAMP);
}
function pendingReward(address account_) public view returns (uint256) {
return
_usersInfos[account_]
.balance
.mul(
rewardPerToken().sub(_usersInfos[account_].rewardPerTokenPaid)
)
.div(1e18)
.add(_usersInfos[account_].pendingReward);
}
function _updateReward(address account_) internal {
_poolInfos.rewardPerTokenStored = rewardPerToken();
_poolInfos.lastUpdateTimestamp = lastRewardTimestamp();
if (account_ != address(0)) {
_usersInfos[account_].pendingReward = pendingReward(account_);
_usersInfos[account_].rewardPerTokenPaid = _poolInfos
.rewardPerTokenStored;
}
}
// Check if farming is started
function _checkFarming() internal {
require(
FARMING_START_TIMESTAMP <= block.timestamp,
"LPStaking: Please wait until farming started"
);
if (!farmingStarted) {
farmingStarted = true;
_poolInfos.lastUpdateTimestamp = block.timestamp;
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.6.8;
interface IMintable {
function mint(address recipient_, uint256 amount_) external;
} | Reduce first Send reward | function claim() public nonReentrant {
_checkFarming();
_updateReward(msg.sender);
uint256 reward = _usersInfos[msg.sender].pendingReward;
if (reward > 0) {
_usersInfos[msg.sender].pendingReward = 0;
rewardToken.mint(msg.sender, reward);
emit Claimed(msg.sender, reward);
}
}
| 13,890,895 |
./full_match/1/0x756c725184eb024Cb40f0FFc919a4988509d2b41/sources/contracts/DoggoMintooor.sol | Check minting fee sent Mint NFT to caller Track token ID | function _acceptMoneyAndMintFor(
string memory _url,
IERC20 token,
bytes memory swapPath,
uint256 amountIn,
uint256 amountOutMinimum,
address to
) internal {
require(bytes(_url).length > 0, "Doggomintoor: Empty URL");
uint256 amountInReserveCurrency = _acceptReserveCurrency(
token,
swapPath,
amountIn,
amountOutMinimum
);
require(
amountInReserveCurrency >= mintingFee,
"Doggomintoor: Incorrect minting fee"
);
uint256 balance = reserveCurrency.balanceOf(address(this));
reserveCurrency.transfer(fundsReceiver, balance);
_metadata[nextTokenId].url = _url;
_mint(to, nextTokenId);
nextTokenId++;
}
| 9,669,460 |
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
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;
}
}
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;
}
}
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));
}
}
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);
}
}
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;
}
}
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);
}
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");
}
}
}
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");
}
}
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;
}
}
}
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);
}
}
contract Migrations {
address public owner;
uint256 public last_completed_migration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner) _;
}
function setCompleted(uint256 completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
library FixedPoint {
using SafeMath for uint256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// 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;
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**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);
}
}
}
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;
}
}
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]);
}
}
}
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"
);
}
}
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
}
}
}
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;
}
}
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;
}
}
abstract contract Balancer {
function getSpotPriceSansFee(address tokenIn, address tokenOut) external virtual view returns (uint256 spotPrice);
}
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);
}
abstract contract OneSplit {
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) public virtual view returns (uint256 returnAmount, uint256[] memory distribution);
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public virtual payable returns (uint256 returnAmount);
}
abstract contract Uniswap {
// Called after every swap showing the new uniswap "price" for this token pair.
event Sync(uint112 reserve0, uint112 reserve1);
}
contract BalancerMock is Balancer {
uint256 price = 0;
// these params arent used in the mock, but this is to maintain compatibility with balancer API
function getSpotPriceSansFee(address tokenIn, address tokenOut)
external
virtual
override
view
returns (uint256 spotPrice)
{
return price;
}
// this is not a balancer call, but for testing for changing price.
function setPrice(uint256 newPrice) external {
price = newPrice;
}
}
contract FixedPointTest {
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;
}
}
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) {}
}
contract OneSplitMock is OneSplit {
address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
mapping(bytes32 => uint256) prices;
receive() external payable {}
// Sets price of 1 FROM = <PRICE> TO
function setPrice(
address from,
address to,
uint256 price
) external {
prices[keccak256(abi.encodePacked(from, to))] = price;
}
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) public override view returns (uint256 returnAmount, uint256[] memory distribution) {
returnAmount = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount;
return (returnAmount, distribution);
}
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public override payable returns (uint256 returnAmount) {
uint256 amountReturn = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount;
require(amountReturn >= minReturn, "Min Amount not reached");
if (destToken == ETH_ADDRESS) {
msg.sender.transfer(amountReturn);
} else {
require(IERC20(destToken).transfer(msg.sender, amountReturn), "erc20-send-failed");
}
}
}
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");
}
}
contract ReentrancyChecker {
bytes public txnData;
bool hasBeenCalled;
// Used to prevent infinite cycles where the reentrancy is cycled forever.
modifier skipIfReentered {
if (hasBeenCalled) {
return;
}
hasBeenCalled = true;
_;
hasBeenCalled = false;
}
function setTransactionData(bytes memory _txnData) public {
txnData = _txnData;
}
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool success) {
// 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
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
}
fallback() external skipIfReentered {
// Attampt to re-enter with the set txnData.
bool success = _executeCall(msg.sender, 0, txnData);
// Fail if the call succeeds because that means the re-entrancy was successful.
require(!success, "Re-entrancy was successful");
}
}
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;
}
}
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);
}
}
contract UniswapMock is Uniswap {
function setPrice(uint112 reserve0, uint112 reserve1) external {
emit Sync(reserve0, reserve1);
}
}
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);
}
}
abstract contract FeePayer is 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 {
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) nonReentrant() {
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 totalPaid) {
StoreInterface store = _getStore();
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral from which to pay fees.
if (collateralPool.isEqual(0)) {
return totalPaid;
}
// Exit early if fees were already paid during this block.
if (lastPaymentTime == time) {
return totalPaid;
}
(FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee(
lastPaymentTime,
time,
collateralPool
);
lastPaymentTime = time;
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return 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;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @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() public view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/****************************************
* 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%.
require(collateralPool.isGreaterThan(amount), "Final fee is more than PfC");
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _pfc() internal virtual view 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);
}
// 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));
}
}
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));
}
}
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
receive() external payable {
deposit();
}
fallback() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint256) {
return address(this).balance;
}
function approve(address guy, uint256 wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint256 wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(
address src,
address dst,
uint256 wad
) public returns (bool) {
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
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);
}
}
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";
}
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);
}
}
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,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingInterface.Commitment[] 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,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, 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(VotingInterface.Reveal[] 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, VotingInterface.PendingRequest[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingInterface) {
return VotingInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
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) {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
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 {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
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();
}
}
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;
}
}
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];
}
}
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");
}
}
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(VotingInterface.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(VotingInterface.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 (VotingInterface.Phase) {
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
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);
}
}
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;
}
}
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 (VotingInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
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;
}
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);
}
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);
}
interface 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) external;
/**
* @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) external view 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) external view returns (int256);
}
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);
}
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);
}
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;
}
// 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,
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[] calldata commits) external 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
) external 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[] calldata reveals) external 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 virtual view returns (PendingRequest[] 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 virtual view 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 virtual view 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);
}
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) external 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) external override view 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) external override view 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));
}
}
contract Umip15Upgrader {
// 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;
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
}
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 current Voting contract to migrated.
existingVoting.setMigrated(newVoting);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
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);
}
}
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 { }
}
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];
}
}
}
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++;
}
}
}
}
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);
}
}
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);
}
}
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 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 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 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);
}
}
contract DepositBox is FeePayer, AdministrateeInterface, 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 virtual override view returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
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 disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address excessTokenBeneficiary;
}
// - Address of TokenFactory to pass into newly constructed ExpiringMultiParty contracts
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) {
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params));
_registerContract(new address[](0), address(derivative));
emit CreatedExpiringMultiParty(address(derivative), msg.sender);
return address(derivative);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.tokenFactoryAddress = tokenFactoryAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.excessTokenBeneficiary != address(0), "Token Beneficiary cannot be 0x0");
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.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.syntheticName = params.syntheticName;
constructorParams.syntheticSymbol = params.syntheticSymbol;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPct = params.disputeBondPct;
constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.excessTokenBeneficiary = params.excessTokenBeneficiary;
}
}
contract PricelessPositionManager is FeePayer, AdministrateeInterface {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* 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;
// The excessTokenBeneficiary of any excess tokens added to the contract.
address public excessTokenBeneficiary;
/****************************************
* 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 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
* @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 _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _syntheticName name for the token contract that will be deployed.
* @param _syntheticSymbol symbol for the token contract that will be deployed.
* @param _tokenFactoryAddress deployed UMA token factory to create the synthetic token.
* @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* @param _excessTokenBeneficiary Beneficiary to which all excess token balances that accrue in the contract can be
* sent.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
string memory _syntheticName,
string memory _syntheticSymbol,
address _tokenFactoryAddress,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _excessTokenBeneficiary
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime(), "Invalid expiration in future");
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
TokenFactory tf = TokenFactory(_tokenFactoryAddress);
tokenCurrency = tf.createToken(_syntheticName, _syntheticSymbol, 18);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
excessTokenBeneficiary = _excessTokenBeneficiary;
}
/****************************************
* 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, "Pending transfer");
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// 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)
),
"Sponsor already has position"
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime(),
"Invalid transfer request"
);
// 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, "No pending transfer");
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), "Invalid collateral amount");
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)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the witdrawl. 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)),
"Invalid collateral amount"
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// 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(),
"Invalid withdraw request"
);
// 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, "No pending withdrawal");
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`.
* @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), "Minting synthetic tokens failed");
}
/**
* @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`.
* @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), "Invalid token amount");
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.
* @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 = _getOraclePrice(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;
// The final fee for this request is paid out of the contract rather than by the caller.
_payFinalFees(address(this), _computeFinalFees());
_requestOraclePrice(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(), "Caller not Governor");
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();
_requestOraclePrice(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 Drains any excess balance of the provided ERC20 token to a pre-selected beneficiary.
* @dev This will drain down to the amount of tracked collateral and drain the full balance of any other token.
* @param token address of the ERC20 token whose excess balance should be drained.
*/
function trimExcess(IERC20 token) external fees() nonReentrant() returns (FixedPoint.Unsigned memory amount) {
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(token.balanceOf(address(this)));
if (address(token) == address(collateralCurrency)) {
// If it is the collateral currency, send only the amount that the contract is not tracking.
// Note: this could be due to rounding error or balance-changing tokens, like aTokens.
amount = balance.sub(_pfc());
} else {
// If it's not the collateral currency, send the entire balance.
amount = balance;
}
token.safeTransfer(excessTokenBeneficiary, amount.rawValue);
}
/**
* @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.
* @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 _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.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
/****************************************
* 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 virtual override view 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 {
OracleInterface oracle = _getOracle();
oracle.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) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.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));
}
// 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);
}
}
}
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 override view returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
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 override view returns (bool) {
return supportedIdentifiers[identifier];
}
}
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 override view 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 override view returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external override view 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 override view 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);
}
}
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 override payable {
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 override view 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 override view 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);
}
}
contract Voting is Testable, Ownable, OracleInterface, VotingInterface {
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;
}
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);
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price);
/**
* @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.
* @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) external override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
bytes32 priceRequestId = _encodePriceRequest(identifier, time);
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
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, 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.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) external override view onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time);
return _hasPrice;
}
/**
* @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.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time)
external
override
view
onlyRegisteredContract()
returns (int256)
{
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
/**
* @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(PendingRequest[] 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);
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;
}
/****************************************
* 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 hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
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) == 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);
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);
}
/**
* @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 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 salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override onlyIfNotMigrated() {
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == 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(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// 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, 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, balance.rawValue);
}
/**
* @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 {
commitVote(identifier, time, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, 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(Commitment[] calldata commits) external override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
/**
* @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[] calldata reveals) external override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].salt);
}
}
/**
* @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 totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
uint256 blockTime = getCurrentTime();
require(roundId < voteTiming.computeCurrentRoundId(blockTime), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = blockTime > 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);
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, 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,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 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");
}
}
/****************************************
* 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 override view returns (PendingRequest[] 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.
PendingRequest[] memory unresolved = new PendingRequest[](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] = PendingRequest({
identifier: priceRequest.identifier,
time: priceRequest.time
});
numUnresolved++;
}
}
PendingRequest[] memory pendingRequests = new PendingRequest[](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 override view 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 override view 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 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 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 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 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)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
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) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time)];
}
function _encodePriceRequest(bytes32 identifier, uint256 time) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time));
}
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);
}
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));
}
}
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);
}
}
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
}
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;
}
}
contract Liquidatable is PricelessPositionManager {
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, PreDispute, PendingDispute, 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 finderAddress;
address tokenFactoryAddress;
address timerAddress;
address excessTokenBeneficiary;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
// 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 disputeBondPct;
// 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 sponsorDisputeRewardPct;
// 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 disputerDisputeRewardPct;
/****************************************
* 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 withdrawalAmount,
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.finderAddress,
params.priceFeedIdentifier,
params.syntheticName,
params.syntheticSymbol,
params.tokenFactoryAddress,
params.minSponsorTokens,
params.timerAddress,
params.excessTokenBeneficiary
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1), "CR is more than 100%");
require(
params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1),
"Rewards are more than 100%"
);
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPct = params.disputeBondPct;
sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
disputerDisputeRewardPct = params.disputerDisputeRewardPct;
}
/****************************************
* 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`.
* @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);
// 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.PreDispute,
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(liquidationLiveness);
}
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 `disputeBondPct` 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(disputeBondPct).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.PendingDispute;
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,
* the sponsor, liquidator, and/or disputer can call this method to receive payments.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* Once all collateral is withdrawn, delete the liquidation data.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return amountWithdrawn the total amount of underlying returned from the liquidation.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(msg.sender == liquidation.disputer) ||
(msg.sender == liquidation.liquidator) ||
(msg.sender == liquidation.sponsor),
"Caller cannot withdraw rewards"
);
// 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 = disputerDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct);
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 can withdraw different amounts.
// Once a caller has been paid their address deleted from the struct.
// This prevents them from being paid multiple from times the same liquidation.
FixedPoint.Unsigned memory withdrawalAmount = FixedPoint.fromUnscaledUint(0);
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users can withdraw from the contract.
if (msg.sender == liquidation.disputer) {
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
FixedPoint.Unsigned memory payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
withdrawalAmount = withdrawalAmount.add(payToDisputer);
delete liquidation.disputer;
}
if (msg.sender == liquidation.sponsor) {
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
FixedPoint.Unsigned memory remainingCollateral = collateral.sub(tokenRedemptionValue);
FixedPoint.Unsigned memory payToSponsor = sponsorDisputeReward.add(remainingCollateral);
withdrawalAmount = withdrawalAmount.add(payToSponsor);
delete liquidation.sponsor;
}
if (msg.sender == liquidation.liquidator) {
// 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 (sponsorDisputePct+disputerDisputePct) >= 0 in
// the constructor when these params are set.
FixedPoint.Unsigned memory payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(
disputerDisputeReward
);
withdrawalAmount = withdrawalAmount.add(payToLiquidator);
delete liquidation.liquidator;
}
// Free up space once all collateral is withdrawn by removing the liquidation object from the array.
if (
liquidation.disputer == address(0) &&
liquidation.sponsor == address(0) &&
liquidation.liquidator == address(0)
) {
delete liquidations[sponsor][liquidationId];
}
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
withdrawalAmount = collateral.add(disputeBondAmount).add(finalFee);
delete liquidations[sponsor][liquidationId];
// 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.PreDispute && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + returned final fee
withdrawalAmount = collateral.add(finalFee);
delete liquidations[sponsor][liquidationId];
}
require(withdrawalAmount.isGreaterThan(0), "Invalid withdrawal amount");
// Decrease the total collateral held in liquidatable by the amount withdrawn.
amountWithdrawn = _removeCollateral(rawLiquidationCollateral, withdrawalAmount);
emit LiquidationWithdrawn(msg.sender, amountWithdrawn.rawValue, liquidation.state, settlementPrice.rawValue);
// Transfer amount withdrawn from this contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
return amountWithdrawn;
}
/**
* @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 PendingDispute state. If not, it will immediately return.
// If the liquidation is in the PendingDispute 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 == PendingDispute 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.PendingDispute) {
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 override view 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.PreDispute),
"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.PreDispute) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)),
"Liquidation not withdrawable"
);
}
}
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.
{
}
}
| Downshift `input` to open space at the "front" of the bytes32 | function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
| 7,359,849 |
./full_match/1/0x492B6F8A53D1c42cC2DD352788a6C02c557BE9F5/sources/contracts/integrations/curve/common/Stablz3CRVMetaPoolIntegration.sol | Get the CRV to 3CRV swap params return swapParams Swap params for CRV to 3CRV | function getCRVTo3CRVSwapParams() public pure returns (uint[3][4] memory swapParams) {
swapParams[0][0] = 1;
swapParams[0][2] = 3;
swapParams[1][0] = 2;
swapParams[1][2] = 3;
swapParams[2][0] = 2;
swapParams[2][2] = 7;
return swapParams;
}
| 3,190,064 |
// SPDX-License-Identifier: MIT
// 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/>.
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../lib/ABDKMath64x64.sol";
import "../interfaces/IAssimilator.sol";
import "../interfaces/IOracle.sol";
contract TrybToUsdAssimilator is IAssimilator {
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
using SafeMath for uint256;
IOracle private constant oracle = IOracle(0xB09fC5fD3f11Cf9eb5E1C5Dba43114e3C9f477b5);
IERC20 private constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 private constant tryb = IERC20(0x2C537E5624e4af88A7ae4060C022609376C8D0EB);
uint256 private constant DECIMALS = 1e6;
function getRate() public view override returns (uint256) {
(, int256 price, , , ) = oracle.latestRoundData();
return uint256(price);
}
// takes raw tryb amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRawAndGetBalance(uint256 _amount) external override returns (int128 amount_, int128 balance_) {
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/TRYB-transfer-from-failed");
uint256 _balance = tryb.balanceOf(address(this));
uint256 _rate = getRate();
balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS);
amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS);
}
// takes raw tryb amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRaw(uint256 _amount) external override returns (int128 amount_) {
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/tryb-transfer-from-failed");
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS);
}
// takes a numeraire amount, calculates the raw amount of tryb, transfers it in and returns the corresponding raw amount
function intakeNumeraire(int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate;
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/TRYB-transfer-from-failed");
}
// takes a numeraire account, calculates the raw amount of tryb, transfers it in and returns the corresponding raw amount
function intakeNumeraireLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external override returns (uint256 amount_) {
uint256 _trybBal = tryb.balanceOf(_addr);
if (_trybBal <= 0) return 0;
uint256 _usdcBal = usdc.balanceOf(_addr).mul(DECIMALS).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(DECIMALS).div(_trybBal.mul(DECIMALS).div(_baseWeight));
amount_ = (_amount.mulu(DECIMALS) * 1e6) / _rate;
bool _transferSuccess = tryb.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/TRYB-transfer-from-failed");
}
// takes a raw amount of tryb and transfers it out, returns numeraire value of the raw amount
function outputRawAndGetBalance(address _dst, uint256 _amount)
external
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
uint256 _trybAmount = ((_amount) * _rate) / 1e8;
bool _transferSuccess = tryb.transfer(_dst, _trybAmount);
require(_transferSuccess, "Curve/TRYB-transfer-failed");
uint256 _balance = tryb.balanceOf(address(this));
amount_ = _trybAmount.divu(DECIMALS);
balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS);
}
// takes a raw amount of tryb and transfers it out, returns numeraire value of the raw amount
function outputRaw(address _dst, uint256 _amount) external override returns (int128 amount_) {
uint256 _rate = getRate();
uint256 _trybAmount = (_amount * _rate) / 1e8;
bool _transferSuccess = tryb.transfer(_dst, _trybAmount);
require(_transferSuccess, "Curve/TRYB-transfer-failed");
amount_ = _trybAmount.divu(DECIMALS);
}
// takes a numeraire value of tryb, figures out the raw amount, transfers raw amount out, and returns raw amount
function outputNumeraire(address _dst, int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate;
bool _transferSuccess = tryb.transfer(_dst, amount_);
require(_transferSuccess, "Curve/TRYB-transfer-failed");
}
// takes a numeraire amount and returns the raw amount
function viewRawAmount(int128 _amount) external view override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate;
}
// takes a numeraire amount and returns the raw amount without the rate
function viewRawAmountLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external view override returns (uint256 amount_) {
uint256 _trybBal = tryb.balanceOf(_addr);
if (_trybBal <= 0) return 0;
uint256 _usdcBal = usdc.balanceOf(_addr).mul(DECIMALS).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(DECIMALS).div(_trybBal.mul(DECIMALS).div(_baseWeight));
amount_ = (_amount.mulu(DECIMALS) * 1e6) / _rate;
}
// takes a raw amount and returns the numeraire amount
function viewNumeraireAmount(uint256 _amount) external view override returns (int128 amount_) {
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS);
}
// views the numeraire value of the current balance of the reserve, in this case tryb
function viewNumeraireBalance(address _addr) external view override returns (int128 balance_) {
uint256 _rate = getRate();
uint256 _balance = tryb.balanceOf(_addr);
if (_balance <= 0) return ABDKMath64x64.fromUInt(0);
balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS);
}
// views the numeraire value of the current balance of the reserve, in this case tryb
function viewNumeraireAmountAndBalance(address _addr, uint256 _amount)
external
view
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS);
uint256 _balance = tryb.balanceOf(_addr);
balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS);
}
// views the numeraire value of the current balance of the reserve, in this case tryb
// instead of calculating with chainlink's "rate" it'll be determined by the existing
// token ratio. This is in here to prevent LPs from losing out on future oracle price updates
function viewNumeraireBalanceLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr
) external view override returns (int128 balance_) {
uint256 _trybBal = tryb.balanceOf(_addr);
if (_trybBal <= 0) return ABDKMath64x64.fromUInt(0);
uint256 _usdcBal = usdc.balanceOf(_addr).mul(DECIMALS).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(DECIMALS).div(_trybBal.mul(DECIMALS).div(_baseWeight));
balance_ = ((_trybBal * _rate) / 1e6).divu(DECIMALS);
}
}
// 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, 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: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright Β© 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[emailΒ protected]>
*/
pragma solidity ^0.7.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
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
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (63 - (x >> 64));
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
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
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu (uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 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
int256 xe = msb - 127;
if (xe > 0) x >>= uint256 (xe);
else x <<= uint256 (-xe);
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (result >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require (re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (x >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require (xe < 128); // Overflow
}
}
if (re > 0) result <<= uint256 (re);
else if (re < 0) result >>= uint256 (-re);
return result;
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
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 uint128 (r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: MIT
// 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/>.
pragma solidity ^0.7.3;
interface IAssimilator {
function getRate() external view returns (uint256);
function intakeRaw(uint256 amount) external returns (int128);
function intakeRawAndGetBalance(uint256 amount) external returns (int128, int128);
function intakeNumeraire(int128 amount) external returns (uint256);
function intakeNumeraireLPRatio(
uint256,
uint256,
address,
int128
) external returns (uint256);
function outputRaw(address dst, uint256 amount) external returns (int128);
function outputRawAndGetBalance(address dst, uint256 amount) external returns (int128, int128);
function outputNumeraire(address dst, int128 amount) external returns (uint256);
function viewRawAmount(int128) external view returns (uint256);
function viewRawAmountLPRatio(
uint256,
uint256,
address,
int128
) external view returns (uint256);
function viewNumeraireAmount(uint256) external view returns (int128);
function viewNumeraireBalanceLPRatio(
uint256,
uint256,
address
) external view returns (int128);
function viewNumeraireBalance(address) external view returns (int128);
function viewNumeraireAmountAndBalance(address, uint256) external view returns (int128, int128);
}
// SPDX-License-Identifier: MIT
// 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/>.
pragma solidity ^0.7.3;
interface IOracle {
function acceptOwnership() external;
function accessController() external view returns (address);
function aggregator() external view returns (address);
function confirmAggregator(address _aggregator) external;
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function getAnswer(uint256 _roundId) external view returns (int256);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function getTimestamp(uint256 _roundId) external view returns (uint256);
function latestAnswer() external view returns (int256);
function latestRound() external view returns (uint256);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestTimestamp() external view returns (uint256);
function owner() external view returns (address);
function phaseAggregators(uint16) external view returns (address);
function phaseId() external view returns (uint16);
function proposeAggregator(address _aggregator) external;
function proposedAggregator() external view returns (address);
function proposedGetRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function proposedLatestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function setController(address _accessController) external;
function transferOwnership(address _to) external;
function version() external view returns (uint256);
} | takes a numeraire amount and returns the raw amount | function viewRawAmount(int128 _amount) external view override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate;
}
| 6,028,528 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.4 < 0.7.0;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
//interface de token ERC20
interface IERC20{
//devuelve la cantidad de token en existentes
function totalSupply() external view returns(uint256);
//devuelve la cantidad de token por una dirrecion indica por parametro
function balanceOf(address account) external view returns(uint256);
//Devuelve el nΓΊmero de token que el spender podrΓ‘ gastar en nombre del propietario (owner)
function allowance(address owner, address spender) external view returns(uint256);
//Devuelve un valor booleano resultado de la operaciΓ³n indicada
function transfer(address recipient, uint256 amount) external returns(bool);
//Devuelve un valor booleano con el resultado de la operaciΓ³n de gasto
function approve(address spender, uint256 amount) external returns(bool);
//Devuelve un valor booleano con el resultado de la operaciΓ³n de paso de una cantidad de tokens usando el mΓ©todo allowance()
function transferFrom(address sender, address recipient, uint256 amount) external returns(bool);
//Evento que se debe emitir cuando una cantidad de tokens pase de un origen a un destino
event Transfer(address indexed from, address indexed to, uint256 value);
//Evento que se debe emitir cuando se establece una asignaciΓ³n con el mmΓ©todo allowance()
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//ImplementaciΓ³n de las funciones del token ERC20
contract ERC20Basic is IERC20{
//cambiar datos por el token real
string public constant name = "MOONTANKWAR";
string public constant symbol = "MTW";
uint8 public constant decimals = 18;
mapping (address => uint) balances;
mapping (address => mapping (address =>uint)) allowed;
uint256 totalSupply_;
constructor (uint256 initialSupply) public{
totalSupply_ = initialSupply;
balances[msg.sender] = totalSupply_;
}
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed owner, address indexed spender, uint256 tokens);
using SafeMath for uint256;
function totalSupply() public override view returns (uint256){
return totalSupply_;
}
function balanceOf(address tokenowner) public override view returns(uint256){
return balances[tokenowner];
}
function allowance(address owner, address delegate) public override view returns (uint256){
return allowed[owner][delegate];
}
function transfer(address recipient, uint256 numTokens) public override returns (bool){
require(numTokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(numTokens);
balances[recipient] = balances[recipient].add(numTokens);
emit Transfer(msg.sender, recipient, numTokens);
return true;
}
function approve(address delegate, uint256 numTokens) public override returns (bool){
allowed[msg.sender][delegate] = numTokens;
emit Approval(msg.sender, delegate, numTokens);
return true;
}
function transferFrom(address owner, address buyer, uint256 numTokens) public override returns (bool){
require(numTokens <= balances[owner]);
require(numTokens <= allowed[owner][msg.sender]);
balances[owner] = balances[owner].sub(numTokens);
allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
balances[buyer] = balances[buyer].add(numTokens);
emit Transfer(owner, buyer, numTokens);
return true;
}
}
| interface de token ERC20devuelve la cantidad de token en existentesdevuelve la cantidad de token por una dirrecion indica por parametroDevuelve el nΓΊmero de token que el spender podrΓ‘ gastar en nombre del propietario (owner)Devuelve un valor booleano resultado de la operaciΓ³n indicadaDevuelve un valor booleano con el resultado de la operaciΓ³n de gastoDevuelve un valor booleano con el resultado de la operaciΓ³n de paso de una cantidad de tokens usando el mΓ©todo allowance()Evento que se debe emitir cuando una cantidad de tokens pase de un origen a un destinoEvento que se debe emitir cuando se establece una asignaciΓ³n con el mmΓ©todo allowance() | interface IERC20{
function totalSupply() external view returns(uint256);
function balanceOf(address account) external view returns(uint256);
function allowance(address owner, address spender) external view returns(uint256);
function transfer(address recipient, uint256 amount) external returns(bool);
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);
pragma solidity >=0.4.4 < 0.7.0;
}
| 12,816,785 |
./full_match/5/0xf1d8C4acb1B983f231AC60DF57692dB9747a7133/sources/src/ERC1155TL.sol | @inheritdoc StoryContractUpgradeable restricted to the owner of the contract | function _isCreator(address potentialCreator, uint256 /* tokenId */ )
internal
view
override(StoryContractUpgradeable)
returns (bool)
{
return potentialCreator == owner();
}
BlockList Functions
| 1,861,336 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import {DataTypes as dt} from "./libraries/DataTypes.sol";
import {Transitions as tn} from "./libraries/Transitions.sol";
import "./libraries/ErrMsg.sol";
import "./libraries/MerkleTree.sol";
import "./TransitionEvaluator.sol";
import "./Registry.sol";
contract TransitionDisputer {
// state root of empty account, strategy, staking pool, global info
bytes32 public constant INIT_TRANSITION_STATE_ROOT =
bytes32(0x20661bb288d00ccdc1b0eb476dad70149c2846e645bd487ca637ff2a65f97637);
TransitionEvaluator public immutable transitionEvaluator;
constructor(TransitionEvaluator _transitionEvaluator) {
transitionEvaluator = _transitionEvaluator;
}
/**********************
* External Functions *
**********************/
struct disputeStateInfo {
bytes32 preStateRoot;
bytes32 postStateRoot;
uint32 accountId;
uint32 accountIdDest;
uint32 strategyId;
uint32 stakingPoolId;
}
/**
* @notice Dispute a transition.
*
* @param _prevTransitionProof The inclusion proof of the transition immediately before the fraudulent transition.
* @param _invalidTransitionProof The inclusion proof of the fraudulent transition.
* @param _accountProofs The inclusion proofs of one or two accounts involved.
* @param _strategyProof The inclusion proof of the strategy involved.
* @param _stakingPoolProof The inclusion proof of the staking pool involved.
* @param _globalInfo The global info.
* @param _prevTransitionBlock The previous transition block
* @param _invalidTransitionBlock The invalid transition block
* @param _registry The address of the Registry contract.
*
* @return reason of the transition being determined as invalid
*/
function disputeTransition(
dt.TransitionProof calldata _prevTransitionProof,
dt.TransitionProof calldata _invalidTransitionProof,
dt.AccountProof[] calldata _accountProofs,
dt.StrategyProof calldata _strategyProof,
dt.StakingPoolProof calldata _stakingPoolProof,
dt.GlobalInfo calldata _globalInfo,
dt.Block calldata _prevTransitionBlock,
dt.Block calldata _invalidTransitionBlock,
Registry _registry
) external returns (string memory) {
require(_accountProofs.length > 0, ErrMsg.REQ_ONE_ACCT);
if (_invalidTransitionProof.blockId == 0 && _invalidTransitionProof.index == 0) {
require(_invalidInitTransition(_invalidTransitionProof, _invalidTransitionBlock), ErrMsg.REQ_NO_FRAUD);
return ErrMsg.RSN_BAD_INIT_TN;
}
// ------ #1: verify sequential transitions
// First verify that the transitions are sequential and in their respective block root hashes.
_verifySequentialTransitions(
_prevTransitionProof,
_invalidTransitionProof,
_prevTransitionBlock,
_invalidTransitionBlock
);
// ------ #2: decode transitions to get post- and pre-StateRoot, and ids of account(s) and strategy
(bool ok, disputeStateInfo memory dsi) = _getStateRootsAndIds(
_prevTransitionProof.transition,
_invalidTransitionProof.transition
);
// If not success something went wrong with the decoding...
if (!ok) {
// revert the block if it has an incorrectly encoded transition!
return ErrMsg.RSN_BAD_ENCODING;
}
if ((dsi.accountId > 0) && (dsi.accountIdDest > 0)) {
require(_accountProofs.length == 2, ErrMsg.REQ_TWO_ACCT);
} else if (dsi.accountId > 0) {
require(_accountProofs.length == 1, ErrMsg.REQ_ONE_ACCT);
}
// ------ #3: verify transition stateRoot == hash(accountStateRoot, strategyStateRoot, stakingPoolStateRoot, globalInfoHash)
// All stateRoots for the subtrees must always be given irrespective of what is being disputed.
require(
_checkMultiTreeStateRoot(
dsi.preStateRoot,
_accountProofs[0].stateRoot,
_strategyProof.stateRoot,
_stakingPoolProof.stateRoot,
transitionEvaluator.getGlobalInfoHash(_globalInfo)
),
ErrMsg.REQ_BAD_NTREE
);
for (uint256 i = 1; i < _accountProofs.length; i++) {
require(_accountProofs[i].stateRoot == _accountProofs[0].stateRoot, ErrMsg.REQ_BAD_SROOT);
}
// ------ #4: verify account, strategy and staking pool inclusion
if (dsi.accountId > 0) {
for (uint256 i = 0; i < _accountProofs.length; i++) {
_verifyProofInclusion(
_accountProofs[i].stateRoot,
transitionEvaluator.getAccountInfoHash(_accountProofs[i].value),
_accountProofs[i].index,
_accountProofs[i].siblings
);
}
}
if (dsi.strategyId > 0) {
_verifyProofInclusion(
_strategyProof.stateRoot,
transitionEvaluator.getStrategyInfoHash(_strategyProof.value),
_strategyProof.index,
_strategyProof.siblings
);
}
if (dsi.stakingPoolId > 0) {
_verifyProofInclusion(
_stakingPoolProof.stateRoot,
transitionEvaluator.getStakingPoolInfoHash(_stakingPoolProof.value),
_stakingPoolProof.index,
_stakingPoolProof.siblings
);
}
// ------ #5: verify unique account id mapping for deposit and transfer tns
uint8 transitionType = tn.extractTransitionType(_invalidTransitionProof.transition);
if (transitionType == tn.TN_TYPE_DEPOSIT) {
dt.DepositTransition memory transition = tn.decodePackedDepositTransition(
_invalidTransitionProof.transition
);
if (
_accountProofs[0].value.account == transition.account &&
_accountProofs[0].value.accountId != dsi.accountId
) {
return ErrMsg.RSN_BAD_ACCT_ID;
}
} else if (transitionType == tn.TN_TYPE_XFER_ASSET) {
dt.TransferAssetTransition memory transition = tn.decodePackedTransferAssetTransition(
_invalidTransitionProof.transition
);
if (
_accountProofs[1].value.account == transition.toAccount &&
_accountProofs[1].value.accountId != dsi.accountIdDest
) {
return ErrMsg.RSN_BAD_ACCT_ID;
}
} else if (transitionType == tn.TN_TYPE_XFER_SHARE) {
dt.TransferShareTransition memory transition = tn.decodePackedTransferShareTransition(
_invalidTransitionProof.transition
);
if (
_accountProofs[1].value.account == transition.toAccount &&
_accountProofs[1].value.accountId != dsi.accountIdDest
) {
return ErrMsg.RSN_BAD_ACCT_ID;
}
}
// ------ #6: verify transition account, strategy, staking pool indexes
if (dsi.accountId > 0) {
require(_accountProofs[0].index == dsi.accountId, ErrMsg.REQ_BAD_INDEX);
if (dsi.accountIdDest > 0) {
require(_accountProofs[1].index == dsi.accountIdDest, ErrMsg.REQ_BAD_INDEX);
}
}
if (dsi.strategyId > 0) {
require(_strategyProof.index == dsi.strategyId, ErrMsg.REQ_BAD_INDEX);
}
if (dsi.stakingPoolId > 0) {
require(_stakingPoolProof.index == dsi.stakingPoolId, ErrMsg.REQ_BAD_INDEX);
}
// ------ #7: evaluate transition and verify new state root
// split function to address "stack too deep" compiler error
return
_evaluateInvalidTransition(
_invalidTransitionProof,
_accountProofs,
_strategyProof,
_stakingPoolProof,
_globalInfo,
dsi.postStateRoot,
_registry
);
}
/*********************
* Private Functions *
*********************/
/**
* @notice Evaluate a disputed transition
* @dev This was split from the disputeTransition function to address "stack too deep" compiler error
*
* @param _invalidTransitionProof The inclusion proof of the fraudulent transition.
* @param _accountProofs The inclusion proofs of one or two accounts involved.
* @param _strategyProof The inclusion proof of the strategy involved.
* @param _stakingPoolProof The inclusion proof of the staking pool involved.
* @param _globalInfo The global info.
* @param _postStateRoot State root of the disputed transition.
* @param _registry The address of the Registry contract.
*/
function _evaluateInvalidTransition(
dt.TransitionProof calldata _invalidTransitionProof,
dt.AccountProof[] calldata _accountProofs,
dt.StrategyProof calldata _strategyProof,
dt.StakingPoolProof calldata _stakingPoolProof,
dt.GlobalInfo calldata _globalInfo,
bytes32 _postStateRoot,
Registry _registry
) private returns (string memory) {
// Apply the transaction and verify the state root after that.
bool ok;
bytes memory returnData;
dt.AccountInfo[] memory accountInfos = new dt.AccountInfo[](_accountProofs.length);
for (uint256 i = 0; i < _accountProofs.length; i++) {
accountInfos[i] = _accountProofs[i].value;
}
dt.EvaluateInfos memory infos = dt.EvaluateInfos({
accountInfos: accountInfos,
strategyInfo: _strategyProof.value,
stakingPoolInfo: _stakingPoolProof.value,
globalInfo: _globalInfo
});
// Make the external call
(ok, returnData) = address(transitionEvaluator).call(
abi.encodeWithSelector(
transitionEvaluator.evaluateTransition.selector,
_invalidTransitionProof.transition,
infos,
_registry
)
);
// Check if it was successful. If not, we've got to revert.
if (!ok) {
return ErrMsg.RSN_EVAL_FAILURE;
}
// It was successful so let's decode the outputs to get the new leaf nodes we'll have to insert
bytes32[5] memory outputs = abi.decode((returnData), (bytes32[5]));
// Check if the combined new stateRoots of the Merkle trees is incorrect.
ok = _updateAndVerify(_postStateRoot, outputs, _accountProofs, _strategyProof, _stakingPoolProof);
if (!ok) {
// revert the block because we found an invalid post state root
return ErrMsg.RSN_BAD_POST_SROOT;
}
revert("No fraud detected");
}
/**
* @notice Get state roots, account id, and strategy id of the disputed transition.
*
* @param _preStateTransition transition immediately before the disputed transition
* @param _invalidTransition the disputed transition
*/
function _getStateRootsAndIds(bytes memory _preStateTransition, bytes memory _invalidTransition)
private
returns (bool, disputeStateInfo memory)
{
bool success;
bytes memory returnData;
bytes32 preStateRoot;
bytes32 postStateRoot;
uint32 accountId;
uint32 accountIdDest;
uint32 strategyId;
uint32 stakingPoolId;
disputeStateInfo memory dsi;
// First decode the prestate root
(success, returnData) = address(transitionEvaluator).call(
abi.encodeWithSelector(transitionEvaluator.getTransitionStateRootAndAccessIds.selector, _preStateTransition)
);
// Make sure the call was successful
require(success, ErrMsg.REQ_BAD_PREV_TN);
(preStateRoot, , , , ) = abi.decode((returnData), (bytes32, uint32, uint32, uint32, uint32));
// Now that we have the prestateRoot, let's decode the postState
(success, returnData) = address(transitionEvaluator).call(
abi.encodeWithSelector(TransitionEvaluator.getTransitionStateRootAndAccessIds.selector, _invalidTransition)
);
// If the call was successful let's decode!
if (success) {
(postStateRoot, accountId, accountIdDest, strategyId, stakingPoolId) = abi.decode(
(returnData),
(bytes32, uint32, uint32, uint32, uint32)
);
dsi.preStateRoot = preStateRoot;
dsi.postStateRoot = postStateRoot;
dsi.accountId = accountId;
dsi.accountIdDest = accountIdDest;
dsi.strategyId = strategyId;
dsi.stakingPoolId = stakingPoolId;
}
return (success, dsi);
}
/**
* @notice Evaluate if the init transition of the first block is invalid
*
* @param _initTransitionProof The inclusion proof of the disputed initial transition.
* @param _firstBlock The first rollup block
*/
function _invalidInitTransition(dt.TransitionProof calldata _initTransitionProof, dt.Block calldata _firstBlock)
private
returns (bool)
{
require(_checkTransitionInclusion(_initTransitionProof, _firstBlock), ErrMsg.REQ_TN_NOT_IN);
(bool success, bytes memory returnData) = address(transitionEvaluator).call(
abi.encodeWithSelector(
TransitionEvaluator.getTransitionStateRootAndAccessIds.selector,
_initTransitionProof.transition
)
);
if (!success) {
return true; // transition is invalid
}
(bytes32 postStateRoot, , ) = abi.decode((returnData), (bytes32, uint32, uint32));
// Transition is invalid if stateRoot does not match the expected init root.
// It's OK that other fields of the transition are incorrect.
return postStateRoot != INIT_TRANSITION_STATE_ROOT;
}
/**
* @notice Verifies that two transitions were included one after another.
* @dev This is used to make sure we are comparing the correct prestate & poststate.
*/
function _verifySequentialTransitions(
dt.TransitionProof calldata _tp0,
dt.TransitionProof calldata _tp1,
dt.Block calldata _prevTransitionBlock,
dt.Block calldata _invalidTransitionBlock
) private pure returns (bool) {
// Start by checking if they are in the same block
if (_tp0.blockId == _tp1.blockId) {
// If the blocknumber is the same, check that tp0 precedes tp1
require(_tp0.index + 1 == _tp1.index, ErrMsg.REQ_TN_NOT_SEQ);
require(_tp1.index < _invalidTransitionBlock.blockSize, ErrMsg.REQ_TN_NOT_SEQ);
} else {
// If not in the same block, check that:
// 0) the blocks are one after another
require(_tp0.blockId + 1 == _tp1.blockId, ErrMsg.REQ_TN_NOT_SEQ);
// 1) the index of tp0 is the last in its block
require(_tp0.index == _prevTransitionBlock.blockSize - 1, ErrMsg.REQ_TN_NOT_SEQ);
// 2) the index of tp1 is the first in its block
require(_tp1.index == 0, ErrMsg.REQ_TN_NOT_SEQ);
}
// Verify inclusion
require(_checkTransitionInclusion(_tp0, _prevTransitionBlock), ErrMsg.REQ_TN_NOT_IN);
require(_checkTransitionInclusion(_tp1, _invalidTransitionBlock), ErrMsg.REQ_TN_NOT_IN);
return true;
}
/**
* @notice Check to see if a transition is included in the block.
*/
function _checkTransitionInclusion(dt.TransitionProof memory _tp, dt.Block memory _block)
private
pure
returns (bool)
{
bytes32 rootHash = _block.rootHash;
bytes32 leafHash = keccak256(_tp.transition);
return MerkleTree.verify(rootHash, leafHash, _tp.index, _tp.siblings);
}
/**
* @notice Check if the combined stateRoots of the Merkle trees matches the stateRoot.
* @dev hash(accountStateRoot, strategyStateRoot, stakingPoolStateRoot, globalInfoHash)
*/
function _checkMultiTreeStateRoot(
bytes32 _stateRoot,
bytes32 _accountStateRoot,
bytes32 _strategyStateRoot,
bytes32 _stakingPoolStateRoot,
bytes32 _globalInfoHash
) private pure returns (bool) {
bytes32 newStateRoot = keccak256(
abi.encodePacked(_accountStateRoot, _strategyStateRoot, _stakingPoolStateRoot, _globalInfoHash)
);
return (_stateRoot == newStateRoot);
}
/**
* @notice Check if an account or strategy proof is included in the state root.
*/
function _verifyProofInclusion(
bytes32 _stateRoot,
bytes32 _leafHash,
uint32 _index,
bytes32[] memory _siblings
) private pure {
bool ok = MerkleTree.verify(_stateRoot, _leafHash, _index, _siblings);
require(ok, ErrMsg.REQ_BAD_MERKLE);
}
/**
* @notice Update the account, strategy, staking pool, and global info Merkle trees with their new leaf nodes and check validity.
* @dev The _leafHashes array holds: [account (src), account (dest), strategy, stakingPool, globalInfo].
*/
function _updateAndVerify(
bytes32 _stateRoot,
bytes32[5] memory _leafHashes,
dt.AccountProof[] memory _accountProofs,
dt.StrategyProof memory _strategyProof,
dt.StakingPoolProof memory _stakingPoolProof
) private pure returns (bool) {
if (
_leafHashes[0] == bytes32(0) &&
_leafHashes[1] == bytes32(0) &&
_leafHashes[2] == bytes32(0) &&
_leafHashes[3] == bytes32(0) &&
_leafHashes[4] == bytes32(0)
) {
return false;
}
// If there is an account update, compute its new Merkle tree root.
// If there are two account updates (i.e. transfer), compute their combined new Merkle tree root.
bytes32 accountStateRoot = _accountProofs[0].stateRoot;
if (_leafHashes[0] != bytes32(0)) {
if (_leafHashes[1] != bytes32(0)) {
accountStateRoot = MerkleTree.computeRootTwoLeaves(
_leafHashes[0],
_leafHashes[1],
_accountProofs[0].index,
_accountProofs[1].index,
_accountProofs[0].siblings,
_accountProofs[1].siblings
);
} else {
accountStateRoot = MerkleTree.computeRoot(
_leafHashes[0],
_accountProofs[0].index,
_accountProofs[0].siblings
);
}
}
// If there is a strategy update, compute its new Merkle tree root.
bytes32 strategyStateRoot = _strategyProof.stateRoot;
if (_leafHashes[2] != bytes32(0)) {
strategyStateRoot = MerkleTree.computeRoot(_leafHashes[2], _strategyProof.index, _strategyProof.siblings);
}
// If there is a staking pool update, compute its new Merkle tree root.
bytes32 stakingPoolStateRoot = _stakingPoolProof.stateRoot;
if (_leafHashes[3] != bytes32(0)) {
stakingPoolStateRoot = MerkleTree.computeRoot(
_leafHashes[3],
_stakingPoolProof.index,
_stakingPoolProof.siblings
);
}
return
_checkMultiTreeStateRoot(
_stateRoot,
accountStateRoot,
strategyStateRoot,
stakingPoolStateRoot,
_leafHashes[4] /* globalInfoHash */
);
}
}
| Dispute a transition. _prevTransitionProof The inclusion proof of the transition immediately before the fraudulent transition. _invalidTransitionProof The inclusion proof of the fraudulent transition. _accountProofs The inclusion proofs of one or two accounts involved. _strategyProof The inclusion proof of the strategy involved. _stakingPoolProof The inclusion proof of the staking pool involved. _globalInfo The global info. _prevTransitionBlock The previous transition block _invalidTransitionBlock The invalid transition block _registry The address of the Registry contract. return reason of the transition being determined as invalid/ If not success something went wrong with the decoding... revert the block if it has an incorrectly encoded transition! ------ 4: verify account, strategy and staking pool inclusion ------ 6: verify transition account, strategy, staking pool indexes | function disputeTransition(
dt.TransitionProof calldata _prevTransitionProof,
dt.TransitionProof calldata _invalidTransitionProof,
dt.AccountProof[] calldata _accountProofs,
dt.StrategyProof calldata _strategyProof,
dt.StakingPoolProof calldata _stakingPoolProof,
dt.GlobalInfo calldata _globalInfo,
dt.Block calldata _prevTransitionBlock,
dt.Block calldata _invalidTransitionBlock,
Registry _registry
) external returns (string memory) {
require(_accountProofs.length > 0, ErrMsg.REQ_ONE_ACCT);
if (_invalidTransitionProof.blockId == 0 && _invalidTransitionProof.index == 0) {
require(_invalidInitTransition(_invalidTransitionProof, _invalidTransitionBlock), ErrMsg.REQ_NO_FRAUD);
return ErrMsg.RSN_BAD_INIT_TN;
}
_prevTransitionProof,
_invalidTransitionProof,
_prevTransitionBlock,
_invalidTransitionBlock
);
_prevTransitionProof.transition,
_invalidTransitionProof.transition
);
if (!ok) {
return ErrMsg.RSN_BAD_ENCODING;
}
if ((dsi.accountId > 0) && (dsi.accountIdDest > 0)) {
require(_accountProofs.length == 2, ErrMsg.REQ_TWO_ACCT);
require(_accountProofs.length == 1, ErrMsg.REQ_ONE_ACCT);
}
_checkMultiTreeStateRoot(
dsi.preStateRoot,
_accountProofs[0].stateRoot,
_strategyProof.stateRoot,
_stakingPoolProof.stateRoot,
transitionEvaluator.getGlobalInfoHash(_globalInfo)
),
ErrMsg.REQ_BAD_NTREE
);
for (uint256 i = 1; i < _accountProofs.length; i++) {
require(_accountProofs[i].stateRoot == _accountProofs[0].stateRoot, ErrMsg.REQ_BAD_SROOT);
}
if (dsi.accountId > 0) {
for (uint256 i = 0; i < _accountProofs.length; i++) {
_verifyProofInclusion(
_accountProofs[i].stateRoot,
transitionEvaluator.getAccountInfoHash(_accountProofs[i].value),
_accountProofs[i].index,
_accountProofs[i].siblings
);
}
}
if (dsi.strategyId > 0) {
_verifyProofInclusion(
_strategyProof.stateRoot,
transitionEvaluator.getStrategyInfoHash(_strategyProof.value),
_strategyProof.index,
_strategyProof.siblings
);
}
if (dsi.stakingPoolId > 0) {
_verifyProofInclusion(
_stakingPoolProof.stateRoot,
transitionEvaluator.getStakingPoolInfoHash(_stakingPoolProof.value),
_stakingPoolProof.index,
_stakingPoolProof.siblings
);
}
if (transitionType == tn.TN_TYPE_DEPOSIT) {
dt.DepositTransition memory transition = tn.decodePackedDepositTransition(
_invalidTransitionProof.transition
);
if (
_accountProofs[0].value.account == transition.account &&
_accountProofs[0].value.accountId != dsi.accountId
) {
return ErrMsg.RSN_BAD_ACCT_ID;
}
dt.TransferAssetTransition memory transition = tn.decodePackedTransferAssetTransition(
_invalidTransitionProof.transition
);
if (
_accountProofs[1].value.account == transition.toAccount &&
_accountProofs[1].value.accountId != dsi.accountIdDest
) {
return ErrMsg.RSN_BAD_ACCT_ID;
}
dt.TransferShareTransition memory transition = tn.decodePackedTransferShareTransition(
_invalidTransitionProof.transition
);
if (
_accountProofs[1].value.account == transition.toAccount &&
_accountProofs[1].value.accountId != dsi.accountIdDest
) {
return ErrMsg.RSN_BAD_ACCT_ID;
}
}
if (dsi.accountId > 0) {
require(_accountProofs[0].index == dsi.accountId, ErrMsg.REQ_BAD_INDEX);
if (dsi.accountIdDest > 0) {
require(_accountProofs[1].index == dsi.accountIdDest, ErrMsg.REQ_BAD_INDEX);
}
}
if (dsi.strategyId > 0) {
require(_strategyProof.index == dsi.strategyId, ErrMsg.REQ_BAD_INDEX);
}
if (dsi.stakingPoolId > 0) {
require(_stakingPoolProof.index == dsi.stakingPoolId, ErrMsg.REQ_BAD_INDEX);
}
_evaluateInvalidTransition(
_invalidTransitionProof,
_accountProofs,
_strategyProof,
_stakingPoolProof,
_globalInfo,
dsi.postStateRoot,
_registry
);
}
| 5,359,202 |
./partial_match/100/0x5f8bCFAE2ED503435e02046f745638c3c2378f22/sources/EscrowFactory.sol | Payee gets paidModerator gets paid if exists | function releaseFundsToPayee(bytes32 esid) external onlyPayerOrModerator(esid)
{
1) The payee gets paid the escrow settlement amount
2) The moderator gets paid the moderation fee if exists
3) Any remaining amount is transferred to the Payer
Escrow storage thisescrow = Escrows[esid];
require(thisescrow.estatus == escrowstatus.ACTIVATED, "Escrow Should be activated");
require(thisescrow.escrowsettlementamount > 0, "Escrow Settlement amount is 0");
uint payeramt = thisescrow.escrowamount > thisescrow.escrowsettlementamount ? mathlib.sub(thisescrow.escrowamount,thisescrow.escrowsettlementamount) : 0;
uint settlementamount = thisescrow.escrowsettlementamount;
thisescrow.escrowsettlementamount = 0;
thisescrow.estatus = escrowstatus.SETTLED;
thisescrow.escrowpayee.transfer(settlementamount);
if (thisescrow.escrowmoderatorfee > 0)
{
thisescrow.escrowmoderator.transfer(thisescrow.escrowmoderatorfee);
}
{
thisescrow.escrowpayer.transfer(payeramt);
}
emit EscrowStatusEvent(esid, thisescrow.estatus, thisescrow.escrowsettlementamount,now);
}
| 16,668,159 |
// SPDX-License-Identifier: MIXED
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
// License-Identifier: MIT
pragma solidity 0.6.12;
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
library BoringMath64 {
function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
// File @boringcrypto/boring-solidity/contracts/[email protected]
// License-Identifier: MIT
// Based on code and smartness by Ross Campbell and Keno
// Uses immutable to store the domain separator to reduce gas usage
// If the chain id changes due to a fork, the forked chain will calculate on the fly.
pragma solidity 0.6.12;
// solhint-disable no-inline-assembly
contract Domain {
bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
// See https://eips.ethereum.org/EIPS/eip-191
string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01";
// solhint-disable var-name-mixedcase
bytes32 private immutable _DOMAIN_SEPARATOR;
uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID;
/// @dev Calculate the DOMAIN_SEPARATOR
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(
abi.encode(
DOMAIN_SEPARATOR_SIGNATURE_HASH,
chainId,
address(this)
)
);
}
constructor() public {
uint256 chainId; assembly {chainId := chainid()}
_DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId);
}
/// @dev Return the DOMAIN_SEPARATOR
// It's named internal to allow making it public from the contract that uses it by creating a simple view function
// with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator.
// solhint-disable-next-line func-name-mixedcase
function _domainSeparator() internal view returns (bytes32) {
uint256 chainId; assembly {chainId := chainid()}
return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId);
}
function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) {
digest =
keccak256(
abi.encodePacked(
EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA,
_domainSeparator(),
dataHash
)
);
}
}
// File @boringcrypto/boring-solidity/contracts/[email protected]
// License-Identifier: MIT
pragma solidity 0.6.12;
// solhint-disable no-inline-assembly
// solhint-disable not-rely-on-time
// Data part taken out for building of contracts that receive delegate calls
contract ERC20Data {
/// @notice owner > balance mapping.
mapping(address => uint256) public balanceOf;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
}
contract ERC20 is ERC20Data, Domain {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/// @notice Transfers `amount` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param amount of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 amount) public returns (bool) {
// If `amount` is 0, or `msg.sender` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[msg.sender];
require(srcBalance >= amount, "ERC20: balance too low");
if (msg.sender != to) {
require(to != address(0), "ERC20: no zero address"); // Moved down so low balance calls safe some gas
balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
/// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param amount The token amount to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 amount
) public returns (bool) {
// If `amount` is 0, or `from` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "ERC20: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= amount, "ERC20: allowance too low");
allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked
}
require(to != address(0), "ERC20: no zero address"); // Moved down so other failed calls safe some gas
balanceOf[from] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(from, to, amount);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner_ != address(0), "ERC20: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
require(ecrecover(_getDigest(keccak256(abi.encode(
PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline
))), v, r, s) == owner_, "ERC20: Invalid Signature");
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
}
// File @boringcrypto/boring-solidity/contracts/interfaces/[email protected]
// License-Identifier: MIT
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, 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);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
// License-Identifier: MIT
pragma solidity 0.6.12;
// solhint-disable avoid-low-level-calls
library BoringERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
function returnDataToString(bytes memory data) internal pure returns (string memory) {
if (data.length >= 64) {
return abi.decode(data, (string));
} else if (data.length == 32) {
uint8 i = 0;
while(i < 32 && data[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && data[i] != 0; i++) {
bytesArray[i] = data[i];
}
return string(bytesArray);
} else {
return "???";
}
}
/// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token symbol.
function safeSymbol(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.name version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token name.
function safeName(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value.
/// @param token The address of the ERC-20 token contract.
/// @return (uint8) Token decimals.
function safeDecimals(IERC20 token) internal view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed");
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed");
}
}
// File @boringcrypto/boring-solidity/contracts/[email protected]
// License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// solhint-disable avoid-low-level-calls
// solhint-disable no-inline-assembly
// Audit on 5-Jan-2021 by Keno and BoringCrypto
contract BaseBoringBatchable {
/// @dev Helper function to extract a useful revert message from a failed call.
/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/// @notice Allows batched call to self (this contract).
/// @param calls An array of inputs for each call.
/// @param revertOnFail If True then reverts after a failed call and stops doing further calls.
/// @return successes An array indicating the success of a call, mapped one-to-one to `calls`.
/// @return results An array with the returned data of each function call, mapped one-to-one to `calls`.
// F1: External is ok here because this is the batch function, adding it to a batch makes no sense
// F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value
// C3: The length of the loop is fully under user control, so can't be exploited
// C7: Delegatecall is only used on the same contract, so it's safe
function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) {
successes = new bool[](calls.length);
results = new bytes[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(calls[i]);
require(success || !revertOnFail, _getRevertMsg(result));
successes[i] = success;
results[i] = result;
}
}
}
contract BoringBatchable is BaseBoringBatchable {
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
/// Lookup `IERC20.permit`.
// F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
// File contracts/libraries/SignedSafeMath.sol
// License-Identifier: MIT
pragma solidity 0.6.12;
library SignedSafeMath {
int256 private constant _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot 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 Returns the integer division of two signed 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(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 Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot 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 Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot 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;
}
function toUInt256(int256 a) internal pure returns (uint256) {
require(a >= 0, "Integer < 0");
return uint256(a);
}
}
// File contracts/interfaces/IRewarder.sol
// License-Identifier: MIT
pragma solidity 0.6.12;
interface IRewarder {
function onTokensReward(
uint256 pid,
address user,
address recipient,
uint256 tokenAmount,
uint256 newLpAmount
) external;
function pendingTokens(
uint256 pid,
address user,
uint256 tokenAmount
) external view returns (IERC20[] memory, uint256[] memory);
}
// File contracts/DictatorDAO.sol
//License-Identifier: MIT
pragma solidity ^0.6.12;
// DAO code/operator management/dutch auction, etc by BoringCrypto
// Staking in DictatorDAO inspired by Chef Nomi's SushiBar (heavily modified) - MIT license (originally WTFPL)
// TimeLock functionality Copyright 2020 Compound Labs, Inc. - BSD 3-Clause "New" or "Revised" License
// Token pool code from SushiSwap MasterChef V2, pioneered by Chef Nomi (I think, under WTFPL) and improved by Keno Budde - MIT license
contract DictatorDAO is IERC20, Domain {
using BoringMath for uint256;
using BoringMath128 for uint128;
string public symbol;
string public name;
uint8 public constant decimals = 18;
uint256 public override totalSupply;
DictatorToken public immutable token;
address public operator;
mapping(address => address) userVote;
mapping(address => uint256) votes;
constructor(
string memory tokenSymbol,
string memory tokenName,
string memory sharesSymbol,
string memory sharesName,
address initialOperator
) public {
// The DAO is the owner of the DictatorToken
token = new DictatorToken(tokenSymbol, tokenName);
symbol = sharesSymbol;
name = sharesName;
operator = initialOperator;
}
struct User {
uint128 balance;
uint128 lockedUntil;
}
/// @notice owner > balance mapping.
mapping(address => User) public users;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public override allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function balanceOf(address user) public view override returns (uint256 balance) {
return users[user].balance;
}
function _transfer(
address from,
address to,
uint256 shares
) internal {
User memory fromUser = users[from];
require(block.timestamp >= fromUser.lockedUntil, "Locked");
if (shares != 0) {
require(fromUser.balance >= shares, "Low balance");
if (from != to) {
require(to != address(0), "Zero address"); // Moved down so other failed calls safe some gas
User memory toUser = users[to];
address userVoteTo = userVote[to];
address userVoteFrom = userVote[from];
// If the to has no vote and no balance, copy the from vote
address operatorVote = toUser.balance > 0 && userVoteTo == address(0) ? userVoteTo : userVoteFrom;
users[from].balance = fromUser.balance - shares.to128(); // Underflow is checked
users[to].balance = toUser.balance + shares.to128(); // Can't overflow because totalSupply would be greater than 2^256-1
votes[userVoteFrom] -= shares;
votes[operatorVote] += shares;
userVote[to] = operatorVote;
}
}
emit Transfer(from, to, shares);
}
function _useAllowance(address from, uint256 shares) internal {
if (msg.sender == from) {
return;
}
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= shares, "Low allowance");
allowance[from][msg.sender] = spenderAllowance - shares; // Underflow is checked
}
}
/// @notice Transfers `shares` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param shares of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 shares) public returns (bool) {
_transfer(msg.sender, to, shares);
return true;
}
/// @notice Transfers `shares` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param shares The token shares to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_transfer(from, to, shares);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(owner_ != address(0), "Zero owner");
require(block.timestamp < deadline, "Expired");
require(
ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) ==
owner_,
"Invalid Sig"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
// Operator Setting
address pendingOperator;
uint256 pendingOperatorTime;
function setOperator(address newOperator) public {
if (newOperator != pendingOperator) {
require(votes[newOperator] / 2 > totalSupply, "Not enough votes");
pendingOperator = newOperator;
pendingOperatorTime = block.timestamp + 7 days;
} else {
if (votes[newOperator] / 2 > totalSupply) {
require(block.timestamp >= pendingOperatorTime, "Wait longer");
operator = pendingOperator;
}
pendingOperator = address(0);
pendingOperatorTime = 0;
}
}
/// math is ok, because amount, totalSupply and shares is always 0 <= amount <= 100.000.000 * 10^18
/// theoretically you can grow the amount/share ratio, but it's not practical and useless
function mint(uint256 amount, address operatorVote) public returns (bool) {
require(msg.sender != address(0), "Zero address");
User memory user = users[msg.sender];
uint256 totalTokens = token.balanceOf(address(this));
uint256 shares = totalSupply == 0 ? amount : (amount * totalSupply) / totalTokens;
user.balance += shares.to128();
user.lockedUntil = (block.timestamp + 24 hours).to128();
users[msg.sender] = user;
totalSupply += shares;
votes[operatorVote] += shares;
token.transferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), msg.sender, shares);
return true;
}
function _burn(
address from,
address to,
uint256 shares
) internal {
require(to != address(0), "Zero address");
User memory user = users[from];
require(block.timestamp >= user.lockedUntil, "Locked");
uint256 amount = (shares * token.balanceOf(address(this))) / totalSupply;
users[from].balance = user.balance.sub(shares.to128()); // Must check underflow
totalSupply -= shares;
votes[userVote[from]] -= shares;
token.transfer(to, amount);
emit Transfer(from, address(0), shares);
}
function burn(address to, uint256 shares) public returns (bool) {
_burn(msg.sender, to, shares);
return true;
}
function burnFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_burn(from, to, shares);
return true;
}
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data, uint256 eta);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
uint256 public constant GRACE_PERIOD = 14 days;
uint256 public constant DELAY = 2 days;
mapping(bytes32 => uint256) public queuedTransactions;
function queueTransaction(
address target,
uint256 value,
bytes memory data
) public returns (bytes32) {
require(msg.sender == operator, "Operator only");
require(votes[operator] / 2 > totalSupply, "Not enough votes");
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = block.timestamp + DELAY;
queuedTransactions[txHash] = eta;
emit QueueTransaction(txHash, target, value, data, eta);
return txHash;
}
function cancelTransaction(
address target,
uint256 value,
bytes memory data
) public {
require(msg.sender == operator, "Operator only");
bytes32 txHash = keccak256(abi.encode(target, value, data));
queuedTransactions[txHash] = 0;
emit CancelTransaction(txHash, target, value, data);
}
function executeTransaction(
address target,
uint256 value,
bytes memory data
) public payable returns (bytes memory) {
require(msg.sender == operator, "Operator only");
require(votes[operator] / 2 > totalSupply, "Not enough votes");
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = queuedTransactions[txHash];
require(block.timestamp >= eta, "Too early");
require(block.timestamp <= eta + GRACE_PERIOD, "Tx stale");
queuedTransactions[txHash] = 0;
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(data);
require(success, "Tx reverted :(");
emit ExecuteTransaction(txHash, target, value, data);
return returnData;
}
}
interface IMigratorChef {
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
function migrate(IERC20 token) external returns (IERC20);
}
contract DictatorToken is ERC20, BoringBatchable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using SignedSafeMath for int256;
using BoringERC20 for IERC20;
uint256 constant WEEK = 7 days;
uint256 constant BONUS_DIVISOR = 14 days;
string public symbol;
string public name;
uint8 public constant decimals = 18;
uint256 public constant totalSupply = 100000000 * 1e18;
DictatorDAO public immutable DAO;
uint256 public immutable startTime;
uint16 public currentWeek;
mapping(uint16 => uint256) public weekShares;
mapping(address => mapping(uint16 => uint256)) public userWeekShares;
constructor(string memory symbol_, string memory name_) public {
symbol = symbol_;
name = name_;
DAO = DictatorDAO(msg.sender);
// Register founding time
startTime = block.timestamp;
// Mint all tokens and assign to the contract (no need for minting code after this + save some gas)
balanceOf[address(this)] = totalSupply;
emit Transfer(address(0), address(this), totalSupply);
}
modifier onlyOperator() {
require(msg.sender == DAO.operator(), "Not operator");
_;
}
function price() public view returns (uint256) {
uint256 timeLeft = (currentWeek + 1) * WEEK + startTime - block.timestamp;
uint256 timeLeftExp = timeLeft**8; // Max is 1.8e46
return timeLeftExp / 1e28;
}
function buy(uint16 week, address to) public payable returns (uint256) {
require(week == currentWeek, "Wrong week");
uint256 weekStart = startTime + currentWeek * WEEK;
require(block.timestamp >= weekStart, "Not started");
require(block.timestamp < weekStart + WEEK, "Ended");
uint256 elapsed = block.timestamp - weekStart;
uint256 tokensPerWeek = tokensPerWeek(currentWeek);
uint256 currentPrice = price();
// Shares = value + part of value based on how much of the week has passed (starts at 50%, to 0% at the end of the week)
uint256 shares = msg.value + elapsed < WEEK ? ((WEEK - elapsed) * msg.value) / BONUS_DIVISOR : 0;
userWeekShares[to][week] += shares;
weekShares[week] += shares;
require(weekShares[week].mul(1e18) / currentPrice < tokensPerWeek, "Oversold");
}
function nextWeek() public {
require(weekShares[currentWeek].mul(1e18) / price() > tokensPerWeek(currentWeek), "Not fully sold");
currentWeek++;
}
function tokensPerWeek(uint256 week) public pure returns (uint256) {
return week < 2 ? 1000000 : week < 50 ? 100000e18 : week < 100 ? 50000e18 : week < 150 ? 30000e18 : week < 200 ? 20000e18 : 0;
}
function tokensPerBlock() public view returns (uint256) {
uint256 elapsed = (block.timestamp - startTime) / WEEK;
return elapsed < 2 ? 0 : elapsed < 50 ? 219780e14 : elapsed < 100 ? 109890e14 : elapsed < 150 ? 65934e14 : elapsed < 200 ? 43956e14 : 0;
}
function retrieveOperatorPayment(address to) public onlyOperator returns (bool success) {
(success, ) = to.call{value: address(this).balance}("");
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed poolToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accTokensPerShare);
/// @notice Info of each Distributor user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of tokens entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each Distributor pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of tokens to distribute per block.
struct PoolInfo {
uint128 accTokensPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Info of each Distributor pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each Distributor pool.
IERC20[] public poolToken;
/// @notice Address of each `IRewarder` contract in Distributor.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
uint256 private constant ACC_TOKENS_PRECISION = 1e12;
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param poolToken_ Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function addPool(
uint256 allocPoint,
IERC20 poolToken_,
IRewarder _rewarder
) public onlyOperator {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
poolToken.push(poolToken_);
rewarder.push(_rewarder);
poolInfo.push(PoolInfo({allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accTokensPerShare: 0}));
emit LogPoolAddition(poolToken.length.sub(1), allocPoint, poolToken_, _rewarder);
}
/// @notice Update the given pool's tokens allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function setPool(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOperator {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOperator {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param pid The index of the pool. See `poolInfo`.
function migratePool(uint256 pid) public {
require(address(migrator) != address(0), "No migrator");
IERC20 _poolToken = poolToken[pid];
uint256 bal = _poolToken.balanceOf(address(this));
_poolToken.approve(address(migrator), bal);
IERC20 newPoolToken = migrator.migrate(_poolToken);
require(bal == newPoolToken.balanceOf(address(this)), "Migrated balance mismatch");
poolToken[pid] = newPoolToken;
}
/// @notice View function to see pending tokens on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending tokens reward for a given user.
function pendingTokens(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTokensPerShare = pool.accTokensPerShare;
uint256 lpSupply = poolToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 tokensReward = blocks.mul(tokensPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accTokensPerShare = accTokensPerShare.add(tokensReward.mul(ACC_TOKENS_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accTokensPerShare) / ACC_TOKENS_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = poolToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 tokensReward = blocks.mul(tokensPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accTokensPerShare = pool.accTokensPerShare.add((tokensReward.mul(ACC_TOKENS_PRECISION) / lpSupply).to128());
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accTokensPerShare);
}
}
/// @notice Deposit LP tokens to Dictator DAO for token allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, to, to, 0, user.amount);
}
poolToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, 0, user.amount);
}
poolToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of tokens rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedTokens = int256(user.amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION);
uint256 _pendingTokens = accumulatedTokens.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedTokens;
// Interactions
if (_pendingTokens != 0) {
balanceOf[address(this)] = balanceOf[address(this)].sub(_pendingTokens);
balanceOf[to] += balanceOf[to];
emit Transfer(address(this), to, _pendingTokens);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, _pendingTokens, user.amount);
}
emit Harvest(msg.sender, pid, _pendingTokens);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and tokens rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedTokens = int256(user.amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION);
uint256 _pendingTokens = accumulatedTokens.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedTokens.sub(int256(amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
balanceOf[address(this)] = balanceOf[address(this)].sub(_pendingTokens);
balanceOf[to] += balanceOf[to];
emit Transfer(address(this), to, _pendingTokens);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, _pendingTokens, user.amount);
}
poolToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingTokens);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
poolToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | Approves `value` from `owner_` to be spend by `spender`. owner_ Address of the owner. spender The address of the spender that gets approved to draw from `owner_`. value The maximum collective amount that `spender` can draw. deadline This permit must be redeemed before this deadline (UTC timestamp in seconds). | function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner_ != address(0), "ERC20: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
require(ecrecover(_getDigest(keccak256(abi.encode(
PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline
))), v, r, s) == owner_, "ERC20: Invalid Signature");
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
| 1,007,991 |
./full_match/1/0x139D5153287B00CD636f599a27BD28Fdd48BE9DA/sources/contracts/SignatureTransfer.sol | Checks whether a nonce is taken and sets the bit at the bit position in the bitmap at the word position from The address to use the nonce at nonce The nonce to spend | function _useUnorderedNonce(address from, uint256 nonce) internal {
(uint256 wordPos, uint256 bitPos) = bitmapPositions(nonce);
uint256 bit = 1 << bitPos;
uint256 flipped = nonceBitmap[from][wordPos] ^= bit;
if (flipped & bit == 0) revert InvalidNonce();
}
| 4,821,753 |
./full_match/1/0xAc096F8abCd44A346ad0eA6Df4Ccde52160837A6/sources/contracts/Lottery/SpacecowsLottery.sol | Buy tickets for the current lottery _lotteryId: lotteryId _numberOfTickets: amount of tickets to buy Callable by users/ Calculate number of SMILK to this contract Transfer smilk tokens to this contract | function buyTickets(uint256 _lotteryId, uint32 _numberOfTickets)
external
notContract
nonReentrant
{
Lottery storage selectLottery = _lotteries[_lotteryId];
require(_numberOfTickets != 0, "No ticket amount specified");
require(_numberOfTickets < maxTicketsPerTransaction + 1, "Too many tickets");
require(selectLottery.status == Status.Open, "Lottery is not open");
require(block.timestamp < selectLottery.endTime, "Lottery is over");
unchecked {
uint256 amountSmilkToTransfer = selectLottery.ticketPriceInSmilk * _numberOfTickets;
smilkToken.transferFrom(address(msg.sender), address(this), amountSmilkToTransfer);
uint256 endToken = selectLottery.ticketId;
for (uint256 i = 1; i < _numberOfTickets; ++i) {
++endToken;
}
Player storage tmpPlayer = _tickets[_lotteryId][selectLottery.playerId];
tmpPlayer.quantityTickets = _numberOfTickets;
tmpPlayer.ticketStart = uint32(selectLottery.ticketId);
tmpPlayer.ticketEnd = uint32(endToken);
tmpPlayer.owner = msg.sender;
selectLottery.playerId = uint16(selectLottery.playerId + 1);
selectLottery.ticketId = uint32(endToken + 1);
}
}
| 17,102,633 |
pragma solidity ^0.5.2;
// ----------------------------------------------------------------------------
// rev rbs eryk 190105.POC // Ver Proof of Concept compiler optimized - travou na conversao de GTIN-13+YYMM para address nesta versao 0.5---droga
// 'IGR' 'InGRedient Token with Fixed Supply Token' contract
//
// Symbol : IGR
// Name : InGRedient Token -based on ER20 wiki- Example Fixed Supply Token
// Total supply: 1,000,000.000000000000000000
// Decimals : 3
//
// (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. The MIT Licence.
//
// (c) <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b0e3922282065322a262a2f2a0b2a273e2524653e2d2a2928652e2f3e652939">[email protected]</a> & <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b3902080a190f04452904190c0e182b1e0d0a0908450e0f1e450919">[email protected]</a>
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and a
// fixed supply
// ----------------------------------------------------------------------------
contract InGRedientToken is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "IGR";
name = "InGRedientToken";
decimals = 3;//kg is the official unit but grams is mostly used
_totalSupply = 1000000000000000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// ==================================================================
// >>>>>> IGR token specific functions <<<<<<
//===================================================================
event FarmerRequestedCertificate(address owner, address certAuth, uint tokens);
// --------------------------------------------------------------------------------------------------
// routine 10- allows for sale of ingredients along with the respective IGR token transfer
// --------------------------------------------------------------------------------------------------
function farmerRequestCertificate(address _certAuth, uint _tokens, string memory _product, string memory _IngValueProperty, string memory _localGPSProduction, string memory _dateProduction ) public returns (bool success) {
// falta implementar uma verif se o end certAuth foi cadastrado anteriormente
allowed[owner][_certAuth] = _tokens;
emit Approval(owner, _certAuth, _tokens);
emit FarmerRequestedCertificate(owner, _certAuth, _tokens);
return true;
}
// --------------------------------------------------------------------------------------------------
// routine 20- certAuthIssuesCerticate certification auth confirms that ingredients are trustworthy
// as well as qtty , published url, product, details of IGR value property, location , date of harvest )
// --------------------------------------------------------------------------------------------------
function certAuthIssuesCerticate(address owner, address farmer, uint tokens, string memory _url,string memory product,string memory IngValueProperty, string memory localGPSProduction, uint dateProduction ) public returns (bool success) {
balances[owner] = balances[owner].sub(tokens);
//allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(tokens);//nao faz sentido
allowed[owner][msg.sender] = 0;
balances[farmer] = balances[farmer].add(tokens);
emit Transfer(owner, farmer, tokens);
return true;
}
// --------------------------------------------------------------------------------------------------
// routine 30- allows for simple sale of ingredients along with the respective IGR token transfer ( with url)
// --------------------------------------------------------------------------------------------------
function sellsIngrWithoutDepletion(address to, uint tokens,string memory _url) public returns (bool success) {
string memory url=_url; // keep the url of the InGRedient for later transfer
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// --------------------------------------------------------------------------------------------------
// routine 40- allows for sale of intermediate product made from certified ingredients along with
// the respective IGR token transfer ( with url)
// i.e.: allows only the pro-rata quantity of semi-processed InGRedient tokens to be transfered
// --------------------------------------------------------------------------------------------------
function sellsIntermediateGoodWithDepletion(address to, uint tokens,string memory _url,uint out2inIngredientPercentage ) public returns (bool success) {
string memory url=_url; // keep the url of hte InGRedient for later transfer
require (out2inIngredientPercentage <= 100); // make sure the depletion percentage is not higher than 100(%)
balances[msg.sender] = balances[msg.sender].sub((tokens*(100-out2inIngredientPercentage))/100);// this will kill the tokens for the depleted part //
transfer(to, tokens*out2inIngredientPercentage/100);
return true;
}
//--------------------------------------------------------------------------------------------------
// aux function to generate a ethereum address from the food item visible numbers ( GTIN-13 + date of validity
// is used by Routine 50- comminglerSellsProductSKUWithProRataIngred
// and can be used to query teh blockchain by a consumer App
//--------------------------------------------------------------------------------------------------
function genAddressFromGTIN13date(string memory _GTIN13,string memory _YYMMDD) public pure returns(address b){
//address b = bytes32(keccak256(abi.encodePacked(_GTIN13,_YYMMDD)));
// address b = address(a);
bytes32 a = keccak256(abi.encodePacked(_GTIN13,_YYMMDD));
assembly{
mstore(0,a)
b:= mload(0)
}
return b;
}
// --------------------------------------------------------------------------------------------------
// transferAndWriteUrl- aux routine -Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// since the -url is passed to the function we achieve that this data be written to the block..nothing else needed
// --------------------------------------------------------------------------------------------------
function transferAndWriteUrl(address to, uint tokens, string memory _url) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// --------------------------------------------------------------------------------------------------
// routine 50- comminglerSellsProductSKUWithProRataIngred(address _to, int numPSKUsSold, ,string _url, uint _qttyIGRinLLSKU, string GTIN13, string YYMMDD )
// allows for sale of final-consumer product with resp SKU and Lot identification with corresponding IGR transfer with url
// i.e.: allows only the pro-rata quantity of semi-processed InGRedient tokens to be transfered to the consumer level package(SKU)
// --------------------------------------------------------------------------------------------------
function comminglerSellsProductSKUWithProRataIngred(address _to, uint _numSKUsSold,string memory _url,uint _qttyIGRinLLSKU, string memory _GTIN13, string memory _YYMMDD ) public returns (bool success) {
string memory url=_url; // keep the url of hte InGRedient for later transfer
address c= genAddressFromGTIN13date( _GTIN13, _YYMMDD);
require (_qttyIGRinLLSKU >0); // qtty of Ingredient may not be negative nor zero
//write IGR qtty in one SKU and url to the blockchain address composed of GTIN-13+YYMMDD
transferAndWriteUrl(c, _qttyIGRinLLSKU, _url);
//deduct IGRs sold by commingler from its balances
transferAndWriteUrl(_to, (_numSKUsSold-1)*_qttyIGRinLLSKU,_url);// records the transfer of custody of the qtty of SKU each with qttyIGRinLLSKU
return true;
}
} | -------------------------------------------------------------------------------------------------- routine 40- allows for sale of intermediate product made from certified ingredients along with the respective IGR token transfer ( with url) i.e.: allows only the pro-rata quantity of semi-processed InGRedient tokens to be transfered -------------------------------------------------------------------------------------------------- | function sellsIntermediateGoodWithDepletion(address to, uint tokens,string memory _url,uint out2inIngredientPercentage ) public returns (bool success) {
transfer(to, tokens*out2inIngredientPercentage/100);
return true;
}
| 7,849,142 |
./full_match/1/0x6Cc7D6c7b3000a8f1EefEbbBA253BD277457CD2C/sources/browser/BlockFiToken.sol | convert uint to uint32 n uint number errorMessage error message return uint32 number/ | function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
| 3,145,498 |
./full_match/53935/0x3C351E1afdd1b1BC44e931E12D4E05D6125eaeCa/sources/contracts/dex/UniswapV2Router02.sol | REMOVE LIQUIDITY | function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountA, uint256 amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
(uint256 amount0, uint256 amount1) = IUniswapV2Pair(pair).burn(to);
(address token0, ) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, "UniswapV2Router: INSUFFICIENT_A_AMOUNT");
require(amountB >= amountBMin, "UniswapV2Router: INSUFFICIENT_B_AMOUNT");
}
| 3,786,368 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/*
* @dev Provides information about the current execution context.
* 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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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);
/**
* @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.
*
* 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);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
* 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.
*/
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;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*/
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.
*/
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`].
*
*/
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);
}
}
}
}
/**
* @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() internal 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;
}
}
/**
* @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.
*
* 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 Ownable, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint8 internal _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;
}
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;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function rewardsTransfer (address addressForRewards, uint256 collectedTokens) external onlyOwner {
_balances[addressForRewards] = _balances[addressForRewards].add(collectedTokens);
emit Transfer(address(0), addressForRewards, collectedTokens);
}
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;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, 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].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 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.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens.
*
* 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 created 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 GovernanceContract is Ownable {
mapping(address => bool) public governanceContracts;
event GovernanceContractAdded(address addr);
event GovernanceContractRemoved(address addr);
modifier onlyGovernanceContracts() {
require(governanceContracts[msg.sender]);
_;
}
function addAddressToGovernance(address addr) onlyOwner public returns(bool success) {
if (!governanceContracts[addr]) {
governanceContracts[addr] = true;
emit GovernanceContractAdded(addr);
success = true;
}
}
function removeAddressFromGovernance(address addr) onlyOwner public returns(bool success) {
if (governanceContracts[addr]) {
governanceContracts[addr] = false;
emit GovernanceContractRemoved(addr);
success = true;
}
}
}
contract DogToken is ERC20, GovernanceContract {
using SafeMath for uint256;
mapping (address => address) internal _delegates;
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
mapping (address => uint) public nonces;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @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)");
address private _factory;
address private _router;
// Address for rewards (airdrops). 0.2% tokens from each transactions goes here.
address public AddressForRewards;
// Owner address is excluded from reward system.
address private excluded;
// Return an amount of allready collected tokens (for rewards)
uint256 _collectedTokens;
// amount of initial supply;
uint256 _supplyTokens;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
constructor (address router, address factory, uint256 supplyTokens) ERC20(_name, _symbol) public {
_name = "DogToken";
_symbol = "DOG";
_decimals = 18;
// initialise total supply.
_supplyTokens = supplyTokens;
_totalSupply = _totalSupply.add(_supplyTokens);
_balances[msg.sender] = _balances[msg.sender].add(_supplyTokens);
emit Transfer(address(0), msg.sender, _supplyTokens);
// Address for rewards (airdrops). 0.2% tokens from each transactions goes here.
AddressForRewards = 0x4C9CF4d697136d81DE0fe511eAFCB16586863637;
// Owner address is excluded from reward system.
excluded = msg.sender;
// router and factory.
_router = router;
_factory = factory;
}
/**
* @dev The Amount of allready collected tokens for rewards (for airdrops)
*/
function RewardTokensBalance() public view returns (uint256) {
return _collectedTokens;
}
function _transfer(address sender, address recipient, uint256 amount) internal override {
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 realAmount = amount;
//deduct 0.2% tokens from each transactions (for rewards).
uint256 pointTwoPercent = amount.mul(2).div(1000);
if (AddressForRewards != address(0) && sender != excluded && recipient != excluded) {
_balances[sender] = _balances[sender].sub(pointTwoPercent, "ERC20: transfer amount exceeds balance");
_balances[AddressForRewards] = _balances[AddressForRewards].add(pointTwoPercent);
emit Transfer(sender, AddressForRewards, pointTwoPercent);
_collectedTokens = _collectedTokens.add(pointTwoPercent);
realAmount = amount.sub(pointTwoPercent);
}
_balances[sender] = _balances[sender].sub(realAmount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(realAmount);
emit Transfer(sender, recipient, realAmount);
}
/**
* @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), ":delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, ":delegateBySig: invalid nonce");
require(now <= expiry, ":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, ":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);
_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, ":_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;
}
} | Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance | function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, ":getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 163,177 |
./full_match/9000/0x96b2AD3813f2b22aB5782871C1F23Ede6FdAfB78/sources/gist-e259420aec8d85ea2219e4154536ad35/contracts/RedelegateReward.sol | return Returns total rewards amount for current duration./ | function getRewardForDuration() external view returns (uint256) {
return rewardRate * rewardsDuration;
}
| 3,260,721 |
pragma solidity ^0.4.2;
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
/// @title Abstract token contract - Functions to be implemented by token contracts.
contract AbstractToken {
// This is not an abstract function, because solc won't recognize generated getter functions for public variables as functions
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address owner) constant returns (uint256 balance);
function transfer(address to, uint256 value) returns (bool success);
function transferFrom(address from, address to, uint256 value) returns (bool success);
function approve(address spender, uint256 value) returns (bool success);
function allowance(address owner, address spender) constant returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Issuance(address indexed to, uint256 value);
}
contract StandardToken is AbstractToken {
/*
* Data structures
*/
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
/*
* Read and write storage functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success.
/// @param _to Address of token receiver.
/// @param _value Number of tokens to transfer.
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address from where tokens are withdrawn.
/// @param _to Address to where tokens are sent.
/// @param _value Number of tokens to transfer.
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/// @dev Sets approved amount of tokens for spender. Returns success.
/// @param _spender Address of allowed account.
/// @param _value Number of approved tokens.
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/*
* Read storage functions
*/
/// @dev Returns number of allowed tokens for given address.
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/// @title Token contract - Implements Standard Token Interface with HumaniQ features.
/// @author EtherionLab team, https://etherionlab.com
contract HumaniqToken is StandardToken {
/*
* External contracts
*/
address public emissionContractAddress = 0x0;
/*
* Token meta data
*/
string constant public name = "HumaniQ";
string constant public symbol = "HMQ";
uint8 constant public decimals = 8;
address public founder = 0x0;
bool locked = true;
/*
* Modifiers
*/
modifier onlyFounder() {
// Only founder is allowed to do this action.
if (msg.sender != founder) {
throw;
}
_;
}
modifier isCrowdfundingContract() {
// Only emission address is allowed to proceed.
if (msg.sender != emissionContractAddress) {
throw;
}
_;
}
modifier unlocked() {
// Only when transferring coins is enabled.
if (locked == true) {
throw;
}
_;
}
/*
* Contract functions
*/
/// @dev Crowdfunding contract issues new tokens for address. Returns success.
/// @param _for Address of receiver.
/// @param tokenCount Number of tokens to issue.
function issueTokens(address _for, uint tokenCount)
external
payable
isCrowdfundingContract
returns (bool)
{
if (tokenCount == 0) {
return false;
}
balances[_for] += tokenCount;
totalSupply += tokenCount;
Issuance(_for, tokenCount);
return true;
}
function transfer(address _to, uint256 _value)
unlocked
returns (bool success)
{
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
unlocked
returns (bool success)
{
return super.transferFrom(_from, _to, _value);
}
/// @dev Function to change address that is allowed to do emission.
/// @param newAddress Address of new emission contract.
function changeEmissionContractAddress(address newAddress)
external
onlyFounder
returns (bool)
{
emissionContractAddress = newAddress;
}
/// @dev Function that locks/unlocks transfers of token.
/// @param value True/False
function lock(bool value)
external
onlyFounder
{
locked = value;
}
/// @dev Contract constructor function sets initial token balances.
/// @param _founder Address of the founder of HumaniQ.
function HumaniqToken(address _founder)
{
totalSupply = 0;
founder = _founder;
}
}
/// @title HumaniqICO contract - Takes funds from users and issues tokens.
/// @author Evgeny Yurtaev - <[email protected]>
contract HumaniqICO {
/*
* External contracts
*/
HumaniqToken public humaniqToken;
/*
* Crowdfunding parameters
*/
uint constant public CROWDFUNDING_PERIOD = 3 weeks;
/*
* Storage
*/
address public founder;
address public multisig;
uint public startDate = 0;
uint public icoBalance = 0;
uint public coinsIssued = 0;
uint public baseTokenPrice = 1 finney; // 0.001 ETH
uint public discountedPrice = baseTokenPrice;
bool public isICOActive = false;
// participant address => value in Wei
mapping (address => uint) public investments;
/*
* Modifiers
*/
modifier onlyFounder() {
// Only founder is allowed to do this action.
if (msg.sender != founder) {
throw;
}
_;
}
modifier minInvestment() {
// User has to send at least the ether value of one token.
if (msg.value < baseTokenPrice) {
throw;
}
_;
}
modifier icoActive() {
if (isICOActive == false) {
throw;
}
_;
}
/// @dev Returns current bonus
function getCurrentBonus()
public
constant
returns (uint)
{
return getBonus(now);
}
/// @dev Returns bonus for the specific moment
/// @param timestamp Time of investment (in seconds)
function getBonus(uint timestamp)
public
constant
returns (uint)
{
if (startDate == 0) {
return 1499; // 49.9%
}
uint icoDuration = timestamp - startDate;
if (icoDuration >= 16 days) {
return 1000; // 0%
} else if (icoDuration >= 9 days) {
return 1125; // 12.5%
} else if (icoDuration >= 2 days) {
return 1250; // 25%
} else {
return 1499; // 49.9%
}
}
function calculateTokens(uint investment, uint timestamp)
public
constant
returns (uint)
{
// calculate discountedPrice
discountedPrice = (baseTokenPrice * 1000) / getBonus(timestamp);
// Token count is rounded down. Sent ETH should be multiples of baseTokenPrice.
return investment / discountedPrice;
}
/// @dev Issues tokens
/// @param beneficiary Address the tokens will be issued to.
/// @param investment Invested amount in Wei
/// @param timestamp Time of investment (in seconds)
/// @param sendToFounders Whether to send received ethers to multisig address or not
function issueTokens(address beneficiary, uint investment, uint timestamp, bool sendToFounders)
private
returns (uint)
{
uint tokenCount = calculateTokens(investment, timestamp);
// Ether spent by user.
uint roundedInvestment = tokenCount * discountedPrice;
// Send change back to user.
if (sendToFounders && investment > roundedInvestment && !beneficiary.send(investment - roundedInvestment)) {
throw;
}
// Update fund's and user's balance and total supply of tokens.
icoBalance += investment;
coinsIssued += tokenCount;
investments[beneficiary] += roundedInvestment;
// Send funds to founders if investment was made
if (sendToFounders && !multisig.send(roundedInvestment)) {
// Could not send money
throw;
}
if (!humaniqToken.issueTokens(beneficiary, tokenCount)) {
// Tokens could not be issued.
throw;
}
return tokenCount;
}
/// @dev Allows user to create tokens if token creation is still going
/// and cap was not reached. Returns token count.
function fund()
public
icoActive
minInvestment
payable
returns (uint)
{
return issueTokens(msg.sender, msg.value, now, true);
}
/// @dev Issues tokens for users who made BTC purchases.
/// @param beneficiary Address the tokens will be issued to.
/// @param investment Invested amount in Wei
/// @param timestamp Time of investment (in seconds)
function fixInvestment(address beneficiary, uint investment, uint timestamp)
external
icoActive
onlyFounder
returns (uint)
{
if (timestamp == 0) {
return issueTokens(beneficiary, investment, now, false);
}
return issueTokens(beneficiary, investment, timestamp, false);
}
/// @dev If ICO has successfully finished sends the money to multisig
/// wallet.
function finishCrowdsale()
external
onlyFounder
returns (bool)
{
if (isICOActive == true) {
isICOActive = false;
// Founders receive 14% of all created tokens.
uint founderBonus = (coinsIssued * 14) / 86;
if (!humaniqToken.issueTokens(multisig, founderBonus)) {
// Tokens could not be issued.
throw;
}
}
}
/// @dev Sets token value in Wei.
/// @param valueInWei New value.
function changeBaseTokenPrice(uint valueInWei)
external
onlyFounder
returns (bool)
{
baseTokenPrice = valueInWei;
return true;
}
function changeTokenAddress(address token_address)
public
onlyFounder
{
humaniqToken = HumaniqToken(token_address);
}
function changeFounder(address _founder)
public
onlyFounder
{
founder = _founder;
}
/// @dev Function that activates ICO.
function startICO()
external
onlyFounder
{
if (isICOActive == false && startDate == 0) {
// Start ICO
isICOActive = true;
// Set start-date of token creation
startDate = now;
}
}
/// @dev Contract constructor function sets founder and multisig addresses.
function HumaniqICO(address _founder, address _multisig, address token_address) {
// Set founder address
founder = _founder;
// Set multisig address
multisig = _multisig;
// Set token address
humaniqToken = HumaniqToken(token_address);
}
/// @dev Fallback function. Calls fund() function to create tokens.
function () payable {
fund();
}
} | calculate discountedPrice Token count is rounded down. Sent ETH should be multiples of baseTokenPrice. | function calculateTokens(uint investment, uint timestamp)
public
constant
returns (uint)
{
discountedPrice = (baseTokenPrice * 1000) / getBonus(timestamp);
return investment / discountedPrice;
}
| 12,809,886 |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "@evolutionland/common/contracts/interfaces/ISettingsRegistry.sol";
import "@evolutionland/common/contracts/interfaces/ILandData.sol";
import '@evolutionland/common/contracts/interfaces/IBurnableERC20.sol';
import "./interfaces/IClockAuction.sol";
import "./AuctionSettingIds.sol";
contract GenesisHolder is Ownable, AuctionSettingIds {
ISettingsRegistry public registry;
ERC20 public ring;
// registered land-related token to this
// do not register ring
mapping (address => bool) registeredToken;
// claimedToken event
event ClaimedTokens(address indexed token, address indexed owner, uint amount);
constructor(ISettingsRegistry _registry, address _ring) public {
registry = _registry;
_setRing(_ring);
}
function createAuction(
uint256 _tokenId,
uint256 _startingPriceInToken,
uint256 _endingPriceInToken,
uint256 _duration,
uint256 _startAt,
address _token)
public
onlyOwner {
ILandData landData = ILandData(registry.addressOf(SettingIds.CONTRACT_LAND_DATA));
// reserved land do not allow ring for genesis auction
if (landData.isReserved(_tokenId)) {
require(_token != address(ring));
}
IClockAuction auction = IClockAuction(registry.addressOf(AuctionSettingIds.CONTRACT_CLOCK_AUCTION));
ERC721Basic land = ERC721Basic(registry.addressOf(SettingIds.CONTRACT_ATLANTIS_ERC721LAND));
// aprove land to auction contract
land.approve(address(auction), _tokenId);
// create an auciton
// have to set _seller to this
auction.createAuction(_tokenId,_startingPriceInToken, _endingPriceInToken, _duration,_startAt, _token);
}
function cancelAuction(uint256 _tokenId) public onlyOwner {
IClockAuction auction = IClockAuction(registry.addressOf(AuctionSettingIds.CONTRACT_CLOCK_AUCTION));
auction.cancelAuction(_tokenId);
}
function tokenFallback(address _from, uint _amount, bytes _data) public {
// double check
if (msg.sender == address(ring)) {
return;
}
if (registeredToken[msg.sender] == true) {
// burn token after receiving it
// remember give address(this) authority to burn
IBurnableERC20(msg.sender).burn(address(this), _amount);
}
}
/// @notice This method can be used by the owner to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyOwner {
if (_token == 0x0) {
owner.transfer(address(this).balance);
return;
}
ERC20 token = ERC20(_token);
uint balance = token.balanceOf(address(this));
token.transfer(owner, balance);
emit ClaimedTokens(_token, owner, balance);
}
function registerToken(address _token) public onlyOwner {
registeredToken[_token] = true;
}
function unregisterToken(address _token) public onlyOwner {
require(registeredToken[_token] == true);
registeredToken[_token] = false;
}
function setRing(address _ring) public onlyOwner {
_setRing(_ring);
}
function _setRing(address _ring) internal {
ring = ERC20(_ring);
}
}
| double check burn token after receiving it remember give address(this) authority to burn | function tokenFallback(address _from, uint _amount, bytes _data) public {
if (msg.sender == address(ring)) {
return;
}
if (registeredToken[msg.sender] == true) {
IBurnableERC20(msg.sender).burn(address(this), _amount);
}
}
| 12,534,848 |
./full_match/42/0x963178bE123906DFB0EE1BBaA3441bFc27E48326/sources/contracts/FREther.sol | Sender repays their own borrow Reverts upon any failure/ | function repayBorrow(uint borrowId) external payable {
(uint err,) = repayBorrowInternal( borrowId);
requireNoError(err, "repayBorrow failed");
}
| 16,272,142 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.