file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** *Submitted for verification at Etherscan.io on 2020-02-11 */ pragma solidity ^0.5.16; 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]; } } 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 Nordic Energy smart contract. * @notice Renouncing to ownership will leave the smart contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the smart 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 smart contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title 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) { if (a == 0) { return 0; } uint256 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 c; } /** * @dev Substracts 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) { uint256 c = a + b; //assert(c >= a); return c; } } 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); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of Nordic Energy 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 Nordic Energy 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 Nordic Energy tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer Nordic Energy token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of Nordic Energy 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 Nordic Energy tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer Nordic Energy tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of Nordic Energy tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); //injected INTEGER OVERFLOW OR UNDERFLOW _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of Nordic Energy tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of Nordic Energy 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); //injected INTEGER OVERFLOW OR UNDERFLOW emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of Nordic Energy tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of Nordic Energy 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); //injected INTEGER OVERFLOW OR UNDERFLOW emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer Nordic Energy token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the Nordic Energy 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 Nordic Energy tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the Nordic Energy token of a given * account. * @param account The account whose Nordic Energy tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the Nordic Energy token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose Nordic Energy tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of Nordic Energy tokens. * @param value The amount of Nordic Energy token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of Nordic Energy 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 Nordic Energy token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, 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); _; } /** * @dev Modifier to make a function callable only when the smart contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } contract ERC20Pausable is ERC20, 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 increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } contract MintableAndPausableToken is ERC20Pausable, Ownable { uint8 public constant decimals = 18; uint256 public maxTokenSupply = 185000000 * 10 ** uint256(decimals); bool public mintingFinished = false; event Mint(address indexed to, uint256 amount); event MintFinished(); event MintStarted(); modifier canMint() { require(!mintingFinished); _; } modifier checkMaxSupply(uint256 _amount) { require(maxTokenSupply >= totalSupply().add(_amount)); _; } modifier cannotMint() { require(mintingFinished); _; } function mint(address _to, uint256 _amount) external onlyOwner canMint checkMaxSupply (_amount) whenNotPaused returns (bool) { super._mint(_to, _amount); return true; } function _mint(address _to, uint256 _amount) internal canMint checkMaxSupply (_amount) { super._mint(_to, _amount); } function finishMinting() external onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } function startMinting() external onlyOwner cannotMint returns (bool) { mintingFinished = false; emit MintStarted(); return true; } } /** * Token upgrader interface inspired by Lunyr. * * Token upgrader transfers previous version Nordic Energy tokens to a newer version. * Token upgrader itself can be the Nordic Energy token smart contract, or just a middle man contract doing the heavy lifting. */ contract TokenUpgrader { uint public originalSupply; /** Interface marker */ function isTokenUpgrader() external pure returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } contract UpgradeableToken is MintableAndPausableToken { // Contract or person who can set the upgrade path. address public upgradeMaster; // Bollean value needs to be true to start upgrades bool private upgradesAllowed; // The next smart contract where the Nordic Energy tokens will be migrated. TokenUpgrader public tokenUpgrader; // How many Nordic Energy tokens we have upgraded by now. uint public totalUpgraded; /** * Upgrade states. * - NotAllowed: The child contract has not reached a condition where the upgrade can begin * - Waiting: Nordic Energy allows upgrade, but we don't have a new Nordic Energy token version * - ReadyToUpgrade: The Nordic Energy token version is set, but not a single Nordic Energy token has been upgraded yet * - Upgrading: Nordic Energy token upgrader is set and the balance holders can upgrade Nordic Energy tokens */ enum UpgradeState { NotAllowed, Waiting, ReadyToUpgrade, Upgrading } // Somebody has upgraded some of his Nordic Energy tokens. event Upgrade(address indexed _from, address indexed _to, uint256 _value); // New token version available. event TokenUpgraderIsSet(address _newToken); modifier onlyUpgradeMaster { // Only a master can designate the next token require(msg.sender == upgradeMaster); _; } modifier notInUpgradingState { // Upgrade has already begun for Nordic Energy token require(getUpgradeState() != UpgradeState.Upgrading); _; } // Do not allow construction without upgrade master set. constructor(address _upgradeMaster) public { upgradeMaster = _upgradeMaster; } // set a Nordic Energy token upgrader function setTokenUpgrader(address _newToken) external onlyUpgradeMaster notInUpgradingState { require(canUpgrade()); require(_newToken != address(0)); tokenUpgrader = TokenUpgrader(_newToken); // Handle bad interface require(tokenUpgrader.isTokenUpgrader()); // Make sure that Nordic Energy token supplies match in source and target require(tokenUpgrader.originalSupply() == totalSupply()); emit TokenUpgraderIsSet(address(tokenUpgrader)); } // Allow the Nordic Energy token holder to upgrade some of our tokens to a new smart contract. function upgrade(uint _value) external { UpgradeState state = getUpgradeState(); // Check upgrate state require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading); // Validate input value require(_value != 0); //balances[msg.sender] = balances[msg.sender].sub(_value); // Take Nordic Energy tokens out from circulation //totalSupply_ = totalSupply_.sub(_value); //the _burn method emits the Transfer event _burn(msg.sender, _value); totalUpgraded = totalUpgraded.add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW // Token Upgrader reissues the Nordic Energy tokens tokenUpgrader.upgradeFrom(msg.sender, _value); emit Upgrade(msg.sender, address(tokenUpgrader), _value); } /** * Change the upgrade master. * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address _newMaster) external onlyUpgradeMaster { require(_newMaster != address(0)); upgradeMaster = _newMaster; } // To be overriden to add functionality function allowUpgrades() external onlyUpgradeMaster () { upgradesAllowed = true; } // To be overriden to add functionality function rejectUpgrades() external onlyUpgradeMaster () { require(!(totalUpgraded > 0)); upgradesAllowed = false; } // Get the state of the Nordic Energy token upgrade. function getUpgradeState() public view returns(UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if (address(tokenUpgrader) == address(0)) return UpgradeState.Waiting; else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } // To be overriden to add functionality function canUpgrade() public view returns(bool) { return upgradesAllowed; } } contract Token is UpgradeableToken, ERC20Burnable { string public name; string public symbol; // For patient incentive programs uint256 public INITIAL_SUPPLY; uint256 public holdPremiumCap; uint256 public holdPremiumMinted; // After 180 days you get a constant maximum bonus of 25% of Nordic Energy tokens transferred // Before that it is spread out linearly(from 0% to 25%) starting from the // contribution time till 180 days after that uint256 constant maxBonusDuration = 180 days; struct Bonus { uint256 holdTokens; uint256 contributionTime; uint256 buybackTokens; } mapping( address => Bonus ) public holdPremium; IERC20 stablecoin; address stablecoinPayer; uint256 public signupWindowStart; uint256 public signupWindowEnd; uint256 public refundWindowStart; uint256 public refundWindowEnd; event UpdatedTokenInformation(string newName, string newSymbol); event holdPremiumSet(address beneficiary, uint256 tokens, uint256 contributionTime); event holdPremiumCapSet(uint256 newholdPremiumCap); event RegisteredForRefund( address holder, uint256 tokens ); constructor (address _litWallet, address _upgradeMaster, uint256 _INITIAL_SUPPLY, uint256 _holdPremiumCap) public UpgradeableToken(_upgradeMaster) Ownable() { require(maxTokenSupply >= _INITIAL_SUPPLY.mul(10 ** uint256(decimals))); INITIAL_SUPPLY = _INITIAL_SUPPLY.mul(10 ** uint256(decimals)); setholdPremiumCap(_holdPremiumCap) ; _mint(_litWallet, INITIAL_SUPPLY); } /** * Owner can update Nordic Energy token/stablecoin information here */ function setTokenInformation(string calldata _name, string calldata _symbol) external onlyOwner { name = _name; symbol = _symbol; emit UpdatedTokenInformation(name, symbol); } function setRefundSignupDetails( uint256 _startTime, uint256 _endTime, ERC20 _stablecoin, address _payer ) public onlyOwner { require( _startTime < _endTime ); stablecoin = _stablecoin; stablecoinPayer = _payer; signupWindowStart = _startTime; signupWindowEnd = _endTime; refundWindowStart = signupWindowStart + 182 days; refundWindowEnd = signupWindowEnd + 182 days; require( refundWindowStart > signupWindowEnd); } function signUpForRefund( uint256 _value ) public { require( holdPremium[msg.sender].holdTokens != 0 || holdPremium[msg.sender].buybackTokens != 0, "You must be ICO/STOs user to sign up" ); //the user was registered in ICO/STOs require( block.timestamp >= signupWindowStart&& block.timestamp <= signupWindowEnd, "Cannot sign up at this time" ); uint256 value = _value; value = value.add(holdPremium[msg.sender].buybackTokens); if( value > balanceOf(msg.sender)) //cannot register more than he or she has; since refund has to happen while Nordic Energy token is paused, we don't need to check anything else value = balanceOf(msg.sender); holdPremium[ msg.sender].buybackTokens = value; //buyback cancels hold highway if( holdPremium[msg.sender].holdTokens > 0 ){ holdPremium[msg.sender].holdTokens = 0; emit holdPremiumSet( msg.sender, 0, holdPremium[msg.sender].contributionTime ); } emit RegisteredForRefund(msg.sender, value); } function refund( uint256 _value ) public { require( block.timestamp >= refundWindowStart && block.timestamp <= refundWindowEnd, "cannot refund now" ); require( holdPremium[msg.sender].buybackTokens >= _value, "not enough tokens in refund program" ); require( balanceOf(msg.sender) >= _value, "not enough tokens" ); //this check is probably redundant to those in _burn, but better check twice holdPremium[msg.sender].buybackTokens = holdPremium[msg.sender].buybackTokens.sub(_value); _burn( msg.sender, _value ); require( stablecoin.transferFrom( stablecoinPayer, msg.sender, _value.div(20) ), "transfer failed" ); //we pay 1/20 = 0.05 DAI for 1 LIT } function setholdPremiumCap(uint256 newholdPremiumCap) public onlyOwner { require(newholdPremiumCap > 0); holdPremiumCap = newholdPremiumCap; emit holdPremiumCapSet(holdPremiumCap); } /** * Owner can burn Nordic Energy tokens here */ function burn(uint256 _value) public onlyOwner { super.burn(_value); } function setholdPremium( address beneficiary, uint256 value, uint256 contributionTime ) public onlyOwner returns (bool) { require(beneficiary != address(0) && value > 0 && contributionTime > 0, "Not eligible for hold Premium"); if (holdPremium[beneficiary].holdTokens != 0) { holdPremium[beneficiary].holdTokens = holdPremium[beneficiary].holdTokens.add(value); //injected INTEGER OVERFLOW OR UNDERFLOW emit holdPremiumSet(beneficiary, holdPremium[beneficiary].holdTokens, holdPremium[beneficiary].contributionTime); } else { holdPremium[beneficiary] = Bonus(value, contributionTime, 0); emit holdPremiumSet(beneficiary, value, contributionTime); } return true; } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); require(_value <= balanceOf(msg.sender)); if (holdPremiumMinted < holdPremiumCap && holdPremium[msg.sender].holdTokens > 0) { uint256 amountForBonusCalculation = calculateAmountForBonus(msg.sender, _value); uint256 bonus = calculateBonus(msg.sender, amountForBonusCalculation); //subtract the tokens token into account here to avoid the above calculations in the future, e.g. in case I withdraw everything in 0 days (bonus 0), and then refund, I shall not be eligible for any bonuses holdPremium[msg.sender].holdTokens = holdPremium[msg.sender].holdTokens.sub(amountForBonusCalculation); if ( bonus > 0) { //balances[msg.sender] = balances[msg.sender].add(bonus); _mint( msg.sender, bonus ); //emit Transfer(address(0), msg.sender, bonus); } } ERC20Pausable.transfer( _to, _value ); // balances[msg.sender] = balances[msg.sender].sub(_value); // balances[_to] = balances[_to].add(_value); // emit Transfer(msg.sender, _to, _value); //TODO: optimize to avoid setting values outside of buyback window if( balanceOf(msg.sender) < holdPremium[msg.sender].buybackTokens ) holdPremium[msg.sender].buybackTokens = balanceOf(msg.sender); return true; } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { require(_to != address(0)); if (holdPremiumMinted < holdPremiumCap && holdPremium[_from].holdTokens > 0) { uint256 amountForBonusCalculation = calculateAmountForBonus(_from, _value); uint256 bonus = calculateBonus(_from, amountForBonusCalculation); //subtract the tokens token into account here to avoid the above calculations in the future, e.g. in case I withdraw everything in 0 days (bonus 0), and then refund, I shall not be eligible for any bonuses holdPremium[_from].holdTokens = holdPremium[_from].holdTokens.sub(amountForBonusCalculation); if ( bonus > 0) { //balances[_from] = balances[_from].add(bonus); _mint( _from, bonus ); //emit Transfer(address(0), _from, bonus); } } ERC20Pausable.transferFrom( _from, _to, _value); if( balanceOf(_from) < holdPremium[_from].buybackTokens ) holdPremium[_from].buybackTokens = balanceOf(_from); return true; } function calculateBonus(address beneficiary, uint256 amount) internal returns (uint256) { uint256 bonusAmount; uint256 contributionTime = holdPremium[beneficiary].contributionTime; uint256 bonusPeriod; if (now <= contributionTime) { bonusPeriod = 0; } else if (now.sub(contributionTime) >= maxBonusDuration) { bonusPeriod = maxBonusDuration; } else { bonusPeriod = now.sub(contributionTime); } if (bonusPeriod != 0) { bonusAmount = (((bonusPeriod.mul(amount)).div(maxBonusDuration)).mul(25)).div(100); if (holdPremiumMinted.add(bonusAmount) > holdPremiumCap) { bonusAmount = holdPremiumCap.sub(holdPremiumMinted); holdPremiumMinted = holdPremiumCap; } else { holdPremiumMinted = holdPremiumMinted.add(bonusAmount); } if( totalSupply().add(bonusAmount) > maxTokenSupply ) bonusAmount = maxTokenSupply.sub(totalSupply()); } return bonusAmount; } function calculateAmountForBonus(address beneficiary, uint256 _value) internal view returns (uint256) { uint256 amountForBonusCalculation; if(_value >= holdPremium[beneficiary].holdTokens) { amountForBonusCalculation = holdPremium[beneficiary].holdTokens; } else { amountForBonusCalculation = _value; } return amountForBonusCalculation; } } contract TestToken is ERC20{ constructor ( uint256 _balance)public { _mint(msg.sender, _balance); } }
Transfer Nordic Energy tokens from one address to another. Note that while this function emits an Approval event, this is not required as per the specification, and other compliant implementations may not emit the event. from address The address which you want to send tokens from to address The address which you want to transfer to value uint256 the amount of Nordic Energy tokens to be transferred/
function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; }
1,800,604
./full_match/3/0x3ab27ECCA95d100053802bABafD6497B8A31EFc8/sources/contracts/NFTDomain.sol
Get if an account can delete the subdomain with a given name It is highly suggested to return `false` if `getDomain(name).canDeleteSubdomain(msg.sender, name, this)` is `false` updater The account that may or may not be able to delete a subdomain name The subdomain to delete return Whether an account can delete the subdomain
function canDeleteDomain(address updater, string memory name) public view returns (bool) { return ownerOf(1) == updater || subdomains[name].canDeleteSubdomain(updater, name, this); }
8,237,629
// Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol'; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SM1Admin } from '../v1_1/impl/SM1Admin.sol'; import { SM1Getters } from '../v1_1/impl/SM1Getters.sol'; import { SM1Operators } from '../v1_1/impl/SM1Operators.sol'; import { SM1Slashing } from '../v1_1/impl/SM1Slashing.sol'; import { SM1Staking } from '../v1_1/impl/SM1Staking.sol'; /** * @title SafetyModuleV2 * @author dYdX * * @notice Contract for staking tokens, which may be slashed by the permissioned slasher. * * NOTE: Most functions will revert if epoch zero has not started. */ contract SafetyModuleV2 is SM1Slashing, SM1Operators, SM1Admin, SM1Getters { using SafeERC20 for IERC20; // ============ Constants ============ string public constant EIP712_DOMAIN_NAME = 'dYdX Safety Module'; string public constant EIP712_DOMAIN_VERSION = '1'; bytes32 public constant EIP712_DOMAIN_SCHEMA_HASH = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Initializer for v2, intended to fix the deployment bug that affected v1. * * Responsible for the following: * * 1. Funds recovery and staker compensation: * - Transfer all Safety Module DYDX to the recovery contract. * - Transfer compensation amount from the rewards treasury to the recovery contract. * * 2. Storage recovery and cleanup: * - Set the _EXCHANGE_RATE_ to EXCHANGE_RATE_BASE. * - Clean up invalid storage values at slots 115 and 125. * * @param recoveryContract The address of the contract which will distribute * recovered funds to stakers. * @param recoveryCompensationAmount Amount to transfer out of the rewards treasury, for staker * compensation, on top of the return of staked funds. */ function initialize( address recoveryContract, uint256 recoveryCompensationAmount ) external initializer { // Funds recovery and staker compensation. uint256 balance = STAKED_TOKEN.balanceOf(address(this)); STAKED_TOKEN.safeTransfer(recoveryContract, balance); REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recoveryContract, recoveryCompensationAmount); // Storage recovery and cleanup. __SM1ExchangeRate_init(); // solhint-disable-next-line no-inline-assembly assembly { sstore(115, 0) sstore(125, 0) } } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 2; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * 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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { 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 callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; /** * @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: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract SM1Admin is SM1StakedBalances, SM1Roles { using SafeMath for uint256; // ============ External Functions ============ /** * @notice Set the parameters defining the function from timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Reverts if epoch zero already started, and the new parameters would change the current epoch. * Reverts if epoch zero has not started, but would have had started under the new parameters. * * @param interval The length `a` of an epoch, in seconds. * @param offset The offset `b`, i.e. the start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { if (!hasEpochZeroStarted()) { require( block.timestamp < offset, 'SM1Admin: Started epoch zero' ); _setEpochParameters(interval, offset); return; } // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the epoch formula. _settleTotalActiveBalance(); // Update the epoch parameters. Require that the current epoch number is unchanged. uint256 originalCurrentEpoch = getCurrentEpoch(); _setEpochParameters(interval, offset); uint256 newCurrentEpoch = getCurrentEpoch(); require( originalCurrentEpoch == newCurrentEpoch, 'SM1Admin: Changed epochs' ); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { _setBlackoutWindow(blackoutWindow); } /** * @notice Set the emission rate of rewards. * * @param emissionPerSecond The new number of rewards tokens given out per second. */ function setRewardsPerSecond( uint256 emissionPerSecond ) external onlyRole(REWARDS_RATE_ROLE) nonReentrant { uint256 totalStaked = 0; if (hasEpochZeroStarted()) { // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the emission rate. totalStaked = _settleTotalActiveBalance(); } _setRewardsPerSecond(emissionPerSecond, totalStaked); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract SM1Getters is SM1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice The parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (SM1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * @return The blackout window duration, in seconds. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get the domain separator used for EIP-712 signatures. * * @return The EIP-712 domain separator. */ function getDomainSeparator() external view returns (bytes32) { return _DOMAIN_SEPARATOR_; } /** * @notice The value of one underlying token, in the units used for staked balances, denominated * as a mutiple of EXCHANGE_RATE_BASE for additional precision. * * To convert from an underlying amount to a staked amount, multiply by the exchange rate. * * @return The exchange rate. */ function getExchangeRate() external view returns (uint256) { return _EXCHANGE_RATE_; } /** * @notice Get an exchange rate snapshot. * * @param index The index number of the exchange rate snapshot. * * @return The snapshot struct with `blockNumber` and `value` fields. */ function getExchangeRateSnapshot( uint256 index ) external view returns (SM1Types.Snapshot memory) { return _EXCHANGE_RATE_SNAPSHOTS_[index]; } /** * @notice Get the number of exchange rate snapshots. * * @return The number of snapshots that have been taken of the exchange rate. */ function getExchangeRateSnapshotCount() external view returns (uint256) { return _EXCHANGE_RATE_SNAPSHOT_COUNT_; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are two types of operators. These should be smart contracts, which can be used to * provide additional functionality to users: * * STAKE_OPERATOR_ROLE: * * This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This * role could be used by a smart contract to provide a staking interface with additional * features, for example, optional lock-up periods that pay out additional rewards (from a * separate rewards pool). * * CLAIM_OPERATOR_ROLE: * * This operator is allowed to claim rewards on behalf of stakers. This role could be used by a * smart contract to provide an interface for claiming rewards from multiple incentive programs * at once. */ abstract contract SM1Operators is SM1Staking, SM1Roles { using SafeMath for uint256; // ============ Events ============ event OperatorStakedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrawalRequestedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrewStakeFor( address indexed staker, address recipient, uint256 amount, address operator ); event OperatorClaimedRewardsFor( address indexed staker, address recipient, uint256 claimedRewards, address operator ); // ============ External Functions ============ /** * @notice Request a withdrawal on behalf of a staker. * * Reverts if we are currently in the blackout window. * * @param staker The staker whose stake to request a withdrawal for. * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, stakeAmount); emit OperatorWithdrawalRequestedFor(staker, stakeAmount, msg.sender); } /** * @notice Withdraw a staker's stake, and send to the specified recipient. * * @param staker The staker whose stake to withdraw. * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, stakeAmount); emit OperatorWithdrewStakeFor(staker, recipient, stakeAmount, msg.sender); } /** * @notice Claim rewards on behalf of a staker, and send them to the specified recipient. * * @param staker The staker whose rewards to claim. * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address staker, address recipient ) external onlyRole(CLAIM_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally. emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender); return rewards; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Slashing * @author dYdX * * @dev Provides the slashing function for removing funds from the contract. * * SLASHING: * * All funds in the contract, active or inactive, are slashable. Slashes are recorded by updating * the exchange rate, and to simplify the technical implementation, we disallow full slashes. * To reduce the possibility of overflow in the exchange rate, we place an upper bound on the * fraction of funds that may be slashed in a single slash. * * Warning: Slashing is not possible if the slash would cause the exchange rate to overflow. * * REWARDS AND GOVERNANCE POWER ACCOUNTING: * * Since all slashes are accounted for by a global exchange rate, slashes do not require any * update to staked balances. The earning of rewards is unaffected by slashes. * * Governance power takes slashes into account by using snapshots of the exchange rate inside * the getPowerAtBlock() function. Note that getPowerAtBlock() returns the governance power as of * the end of the specified block. */ abstract contract SM1Slashing is SM1Staking, SM1Roles { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The maximum fraction of funds that may be slashed in a single slash (numerator). uint256 public constant MAX_SLASH_NUMERATOR = 95; /// @notice The maximum fraction of funds that may be slashed in a single slash (denominator). uint256 public constant MAX_SLASH_DENOMINATOR = 100; // ============ Events ============ event Slashed( uint256 amount, address recipient, uint256 newExchangeRate ); // ============ External Functions ============ /** * @notice Slash staked token balances and withdraw those funds to the specified address. * * @param requestedSlashAmount The request slash amount, denominated in the underlying token. * @param recipient The address to receive the slashed tokens. * * @return The amount slashed, denominated in the underlying token. */ function slash( uint256 requestedSlashAmount, address recipient ) external onlyRole(SLASHER_ROLE) nonReentrant returns (uint256) { uint256 underlyingBalance = STAKED_TOKEN.balanceOf(address(this)); if (underlyingBalance == 0) { return 0; } // Get the slash amount and remaining amount. Note that remainingAfterSlash is nonzero. uint256 maxSlashAmount = underlyingBalance.mul(MAX_SLASH_NUMERATOR).div(MAX_SLASH_DENOMINATOR); uint256 slashAmount = Math.min(requestedSlashAmount, maxSlashAmount); uint256 remainingAfterSlash = underlyingBalance.sub(slashAmount); if (slashAmount == 0) { return 0; } // Update the exchange rate. // // Warning: Can revert if the max exchange rate is exceeded. uint256 newExchangeRate = updateExchangeRate(underlyingBalance, remainingAfterSlash); // Transfer the slashed token. STAKED_TOKEN.safeTransfer(recipient, slashAmount); emit Slashed(slashAmount, recipient, newExchangeRate); return slashAmount; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ERC20 } from './SM1ERC20.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Staking * @author dYdX * * @dev External functions for stakers. See SM1StakedBalances for details on staker accounting. * * UNDERLYING AND STAKED AMOUNTS: * * We distinguish between underlying amounts and stake amounts. An underlying amount is denoted * in the original units of the token being staked. A stake amount is adjusted by the exchange * rate, which can increase due to slashing. Before any slashes have occurred, the exchange rate * is equal to one. */ abstract contract SM1Staking is SM1StakedBalances, SM1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 underlyingAmount, uint256 stakeAmount ); event WithdrawalRequested( address indexed staker, uint256 stakeAmount ); event WithdrewStake( address indexed staker, address recipient, uint256 underlyingAmount, uint256 stakeAmount ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param underlyingAmount The amount of underlying token to stake. */ function stake( uint256 underlyingAmount ) external nonReentrant { _stake(msg.sender, underlyingAmount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param underlyingAmount The amount of underlying token to stake. */ function stakeFor( address staker, uint256 underlyingAmount ) external nonReentrant { _stake(staker, underlyingAmount); } /** * @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive” * and available for withdrawal. Inactive funds do not earn rewards. * * Reverts if we are currently in the blackout window. * * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawal( uint256 stakeAmount ) external nonReentrant { _requestWithdrawal(msg.sender, stakeAmount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 stakeAmount ) external nonReentrant { _withdrawStake(msg.sender, recipient, stakeAmount); } /** * @notice Withdraw the max available inactive funds, and send to the specified recipient. * * This is less gas-efficient than querying the max via eth_call and calling withdrawStake(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxStake( address recipient ) external nonReentrant returns (uint256) { uint256 stakeAmount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, stakeAmount); return stakeAmount; } /** * @notice Settle and claim all rewards, and send them to the specified recipient. * * Call this function with eth_call to query the claimable rewards balance. * * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewards( address recipient ) external nonReentrant returns (uint256) { return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally. } // ============ Public Functions ============ /** * @notice Get the amount of stake available for a given staker to withdraw. * * @param staker The address whose balance to check. * * @return The staker's stake amount that is inactive and available to withdraw. */ function getStakeAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that the next epoch inactive balance is always at least that of the current epoch. return getInactiveBalanceCurrentEpoch(staker); } // ============ Internal Functions ============ function _stake( address staker, uint256 underlyingAmount ) internal { // Convert using the exchange rate. uint256 stakeAmount = stakeAmountFromUnderlyingAmount(underlyingAmount); // Update staked balances and delegate snapshots. _increaseCurrentAndNextActiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(address(0), staker, stakeAmount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), underlyingAmount); emit Staked(staker, msg.sender, underlyingAmount, stakeAmount); emit Transfer(address(0), msg.sender, stakeAmount); } function _requestWithdrawal( address staker, uint256 stakeAmount ) internal { require( !inBlackoutWindow(), 'SM1Staking: Withdraw requests restricted in the blackout window' ); // Get the staker's requestable amount and revert if there is not enough to request withdrawal. uint256 requestableBalance = getActiveBalanceNextEpoch(staker); require( stakeAmount <= requestableBalance, 'SM1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, stakeAmount); emit WithdrawalRequested(staker, stakeAmount); } function _withdrawStake( address staker, address recipient, uint256 stakeAmount ) internal { // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( stakeAmount <= withdrawableBalance, 'SM1Staking: Withdraw amount exceeds staker inactive balance' ); // Update staked balances and delegate snapshots. _decreaseCurrentAndNextInactiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(staker, address(0), stakeAmount); // Convert using the exchange rate. uint256 underlyingAmount = underlyingAmountFromStakeAmount(stakeAmount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, underlyingAmount); emit Transfer(msg.sender, address(0), stakeAmount); emit WithdrewStake(staker, recipient, underlyingAmount, stakeAmount); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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: MIT pragma solidity 0.7.5; /** * @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'); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; library SM1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev Snapshot of a value at a specific block, used to track historical governance power. */ struct Snapshot { uint256 blockNumber; uint256 value; } /** * @dev A balance, possibly with a change scheduled for the next epoch. * * @param currentEpoch The epoch in which the balance was last updated. * @param currentEpochBalance The balance at epoch `currentEpoch`. * @param nextEpochBalance The balance at epoch `currentEpoch + 1`. */ struct StoredBalance { uint16 currentEpoch; uint240 currentEpochBalance; uint240 nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Roles * @author dYdX * * @dev Defines roles used in the SafetyModuleV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove addresses from any of the roles below. * | * +-- SLASHER_ROLE * | -> Can slash staked token balances and withdraw those funds. * | * +-- EPOCH_PARAMETERS_ROLE * | -> May set epoch parameters such as the interval, offset, and blackout window. * | * +-- REWARDS_RATE_ROLE * | -> May set the emission rate of rewards. * | * +-- CLAIM_OPERATOR_ROLE * | -> May claim rewards on behalf of a user. * | * +-- STAKE_OPERATOR_ROLE * -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user). */ abstract contract SM1Roles is SM1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant SLASHER_ROLE = keccak256('SLASHER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); function __SM1Roles_init() internal { // Assign roles to the sender. // // The STAKE_OPERATOR_ROLE and CLAIM_OPERATOR_ROLE roles are not initially assigned. // These can be assigned to other smart contracts to provide additional functionality for users. _setupRole(OWNER_ROLE, msg.sender); _setupRole(SLASHER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(SLASHER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Rewards } from './SM1Rewards.sol'; /** * @title SM1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Functions may revert if epoch zero has not started. * * NOTE: All amounts dealt with in this file are denominated in staked units, which because of the * exchange rate, may not correspond one-to-one with the underlying token. See SM1Staking.sol. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Earning staking rewards; cannot be withdrawn by staker; may be slashed. * - inactive: Not earning rewards; can be withdrawn by the staker; may be slashed. * * A staker may have a combination of active and inactive balances. The following operations * affect staked balances as follows: * - deposit: Increase active balance. * - request withdrawal: At the end of the current epoch, move some active funds to inactive. * - withdraw: Decrease inactive balance. * - transfer: Move some active funds to another staker. * * To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we * store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and * nextEpochBalance. * * REWARDS ACCOUNTING: * * Active funds earn rewards for the period of time that they remain active. This means, after * requesting a withdrawal of some funds, those funds will continue to earn rewards until the end * of the epoch. For example: * * epoch: n n + 1 n + 2 n + 3 * | | | | * +----------+----------+----------+-----... * ^ t_0: User makes a deposit. * ^ t_1: User requests a withdrawal of all funds. * ^ t_2: The funds change state from active to inactive. * * In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying * with the total staked balance in that period. If the user only request a withdrawal for a part * of their balance, then the remaining balance would continue earning rewards beyond t_2. * * User rewards must be settled via SM1Rewards any time a user's active balance changes. Special * attention is paid to the the epoch boundaries, where funds may have transitioned from active * to inactive. * * SETTLEMENT DETAILS: * * Internally, this module uses the following types of operations on stored balances: * - Load: Loads a balance, while applying settlement logic internally to get the * up-to-date result. Returns settlement results without updating state. * - Store: Stores a balance. * - Load-for-update: Performs a load and applies updates as needed to rewards accounting. * Since this is state-changing, it must be followed by a store operation. * - Settle: Performs load-for-update and store operations. * * This module is responsible for maintaining the following invariants to ensure rewards are * calculated correctly: * - When an active balance is loaded for update, if a rollover occurs from one epoch to the * next, the rewards index must be settled up to the boundary at which the rollover occurs. * - Because the global rewards index is needed to update the user rewards index, the total * active balance must be settled before any staker balances are settled or loaded for update. * - A staker's balance must be settled before their rewards are settled. */ abstract contract SM1StakedBalances is SM1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ Public Functions ============ /** * @notice Get the current active balance of a staker. */ function getActiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch active balance of a staker. */ function getActiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total active balance. */ function getTotalActiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total active balance. */ function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total inactive balance. */ function getTotalInactiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get the current transferable balance for a user. The user can * only transfer their balance that is not currently inactive or going to be * inactive in the next epoch. Note that this means the user's transferable funds * are their active balance of the next epoch. * * @param account The account to get the transferable balance of. * * @return The user's transferable balance. */ function getTransferableBalance( address account ) public view returns (uint256) { return getActiveBalanceNextEpoch(account); } // ============ Internal Functions ============ function _increaseCurrentAndNextActiveBalance( address staker, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount); uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance); } function _moveNextBalanceActiveToInactive( address staker, uint256 amount ) internal { // Decrease the active balance for the next epoch. // Always settle total active balance before settling a staker active balance. _decreaseNextBalance(address(0), true, amount); _decreaseNextBalance(staker, true, amount); // Increase the inactive balance for the next epoch. _increaseNextBalance(address(0), false, amount); _increaseNextBalance(staker, false, amount); // Note that we don't need to settle rewards since the current active balance did not change. } function _transferCurrentAndNextActiveBalance( address sender, address recipient, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Move current and next active balances from sender to recipient. uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount); uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance); _settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance); } function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { // Decrease the inactive balance for the next epoch. _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); // Note that we don't settle rewards since active balances are not affected. } function _settleTotalActiveBalance() internal returns (uint256) { return _settleBalance(address(0), true); } function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Always settle staker active balance before settling staker rewards. uint256 userBalance = _settleBalance(staker, true); // Settle rewards balance since we want to claim the full accrued amount. _settleUserRewardsUpToNow(staker, userBalance, totalBalance); // Claim rewards balance. return _claimRewards(staker, recipient); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 currentBalance = uint256(balance.currentEpochBalance); _storeBalance(balancePtr, balance); return currentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (SM1Types.StoredBalance storage) { // Active. if (isActiveBalance) { if (maybeStaker != address(0)) { return _ACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_ACTIVE_BALANCE_; } // Inactive. if (maybeStaker != address(0)) { return _INACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_INACTIVE_BALANCE_; } /** * @dev Load a balance for updating. * * IMPORTANT: This function may modify state, and so the balance MUST be stored afterwards. * - For active balances: * - If a rollover occurs, rewards are settled up to the epoch boundary. * * @param balancePtr A storage pointer to the balance. * @param maybeStaker The user address, or address(0) to update total balance. * @param isActiveBalance Whether the balance is an active balance. */ function _loadBalanceForUpdate( SM1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (SM1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( SM1Types.StoredBalance memory balance, uint256 beforeRolloverEpoch, uint256 beforeRolloverBalance, bool didRolloverOccur ) = _loadActiveBalance(balancePtr); if (didRolloverOccur) { // Handle the effect of the balance rollover on rewards. We must partially settle the index // up to the epoch boundary where the change in balance occurred. We pass in the balance // from before the boundary. if (maybeStaker == address(0)) { // If it's the total active balance... _settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch); } else { // If it's a user active balance... _settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch); } } return balance; } // Inactive balance. return _loadInactiveBalance(balancePtr); } function _loadActiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns ( SM1Types.StoredBalance memory, uint256, uint256, bool ) { SM1Types.StoredBalance memory balance = balancePtr; // Return these as they may be needed for rewards settlement. uint256 beforeRolloverEpoch = uint256(balance.currentEpoch); uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance); bool didRolloverOccur = false; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance; balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur); } function _loadInactiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns (SM1Types.StoredBalance memory) { SM1Types.StoredBalance memory balance = balancePtr; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; } /** * @dev Store a balance. */ function _storeBalance( SM1Types.StoredBalance storage balancePtr, SM1Types.StoredBalance memory balance ) private { // Note: This should use a single `sstore` when compiler optimizations are enabled. balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { SM1Types } from '../lib/SM1Types.sol'; /** * @title SM1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract SM1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. SM1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ /// @dev Allowances for ERC-20 transfers. mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Governance Power Delegation ============ /// @dev Domain separator for EIP-712 signatures. bytes32 internal _DOMAIN_SEPARATOR_; /// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures. mapping(address => uint256) internal _NONCES_; /// @dev Snapshots and delegates for governance voting power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _VOTING_SNAPSHOTS_; mapping(address => uint256) internal _VOTING_SNAPSHOT_COUNTS_; mapping(address => address) internal _VOTING_DELEGATES_; /// @dev Snapshots and delegates for governance proposition power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _PROPOSITION_SNAPSHOTS_; mapping(address => uint256) internal _PROPOSITION_SNAPSHOT_COUNTS_; mapping(address => address) internal _PROPOSITION_DELEGATES_; // ============ Rewards Accounting ============ /// @dev The emission rate of rewards. uint256 internal _REWARDS_PER_SECOND_; /// @dev The cumulative rewards earned per staked token. (Shared storage slot.) uint224 internal _GLOBAL_INDEX_; /// @dev The timestamp at which the global index was last updated. (Shared storage slot.) uint32 internal _GLOBAL_INDEX_TIMESTAMP_; /// @dev The value of the global index when the user's staked balance was last updated. mapping(address => uint256) internal _USER_INDEXES_; /// @dev The user's accrued, unclaimed rewards (as of the last update to the user index). mapping(address => uint256) internal _USER_REWARDS_BALANCES_; /// @dev The value of the global index at the end of a given epoch. mapping(uint256 => uint256) internal _EPOCH_INDEXES_; // ============ Staker Accounting ============ /// @dev The active balance by staker. mapping(address => SM1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. SM1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => SM1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. SM1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; // ============ Exchange Rate ============ /// @dev The value of one underlying token, in the units used for staked balances, denominated /// as a mutiple of EXCHANGE_RATE_BASE for additional precision. uint256 internal _EXCHANGE_RATE_; /// @dev Historical snapshots of the exchange rate, in each block that it has changed. mapping(uint256 => SM1Types.Snapshot) internal _EXCHANGE_RATE_SNAPSHOTS_; /// @dev Number of snapshots of the exchange rate. uint256 internal _EXCHANGE_RATE_SNAPSHOT_COUNT_; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @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 AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev 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]{20}) is missing role (0x[0-9a-f]{32})$/ * * _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(IAccessControlUpgradeable).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]{20}) is missing role (0x[0-9a-f]{32})$/ */ 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 granted `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}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @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. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @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.7.5; /** * @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.7.5; 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.7.5; /** * @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: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint16, reverting on overflow. */ function toUint16( uint256 a ) internal pure returns (uint16) { uint16 b = uint16(a); require( uint256(b) == a, 'SafeCast: toUint16 overflow' ); return b; } /** * @dev Downcast to a uint32, reverting on overflow. */ function toUint32( uint256 a ) internal pure returns (uint32) { uint32 b = uint32(a); require( uint256(b) == a, 'SafeCast: toUint32 overflow' ); return b; } /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128( uint256 a ) internal pure returns (uint128) { uint128 b = uint128(a); require( uint256(b) == a, 'SafeCast: toUint128 overflow' ); return b; } /** * @dev Downcast to a uint224, reverting on overflow. */ function toUint224( uint256 a ) internal pure returns (uint224) { uint224 b = uint224(a); require( uint256(b) == a, 'SafeCast: toUint224 overflow' ); return b; } /** * @dev Downcast to a uint240, reverting on overflow. */ function toUint240( uint256 a ) internal pure returns (uint240) { uint240 b = uint240(a); require( uint256(b) == a, 'SafeCast: toUint240 overflow' ); return b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1EpochSchedule } from './SM1EpochSchedule.sol'; /** * @title SM1Rewards * @author dYdX * * @dev Manages the distribution of token rewards. * * Rewards are distributed continuously. After each second, an account earns rewards `r` according * to the following formula: * * r = R * s / S * * Where: * - `R` is the rewards distributed globally each second, also called the “emission rate.” * - `s` is the account's staked balance in that second (technically, it is measured at the * end of the second) * - `S` is the sum total of all staked balances in that second (again, measured at the end of * the second) * * The parameter `R` can be configured by the contract owner. For every second that elapses, * exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that * while the total staked balance is zero, no tokens will accrue to anyone. * * The accounting works as follows: A global index is stored which represents the cumulative * number of rewards tokens earned per staked token since the start of the distribution. * The value of this index increases over time, and there are two factors affecting the rate of * increase: * 1) The emission rate (in the numerator) * 2) The total number of staked tokens (in the denominator) * * Whenever either factor changes, in some timestamp T, we settle the global index up to T by * calculating the increase in the index since the last update using the OLD values of the factors: * * indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked * * Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index. * * For each user we store an accrued rewards balance, as well as a user index, which is a cache of * the global index at the time that the user's accrued rewards balance was last updated. Then at * any point in time, a user's claimable rewards are represented by the following: * * rewards = _USER_REWARDS_BALANCES_[user] + userStaked * ( * settledGlobalIndex - _USER_INDEXES_[user] * ) / INDEX_BASE */ abstract contract SM1Rewards is SM1EpochSchedule { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @dev Additional precision used to represent the global and user index values. uint256 private constant INDEX_BASE = 10**18; /// @notice The rewards token. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; /// @notice Start timestamp (inclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_START; /// @notice End timestamp (exclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_END; // ============ Events ============ event RewardsPerSecondUpdated( uint256 emissionPerSecond ); event GlobalIndexUpdated( uint256 index ); event UserIndexUpdated( address indexed user, uint256 index, uint256 unclaimedRewards ); event ClaimedRewards( address indexed user, address recipient, uint256 claimedRewards ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) { require( distributionEnd >= distributionStart, 'SM1Rewards: Invalid parameters' ); REWARDS_TOKEN = rewardsToken; REWARDS_TREASURY = rewardsTreasury; DISTRIBUTION_START = distributionStart; DISTRIBUTION_END = distributionEnd; } // ============ External Functions ============ /** * @notice The current emission rate of rewards. * * @return The number of rewards tokens issued globally each second. */ function getRewardsPerSecond() external view returns (uint256) { return _REWARDS_PER_SECOND_; } // ============ Internal Functions ============ /** * @dev Initialize the contract. */ function __SM1Rewards_init() internal { _GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32(); } /** * @dev Set the emission rate of rewards. * * IMPORTANT: Do not call this function without settling the total staked balance first, to * ensure that the index is settled up to the epoch boundaries. * * @param emissionPerSecond The new number of rewards tokens to give out each second. * @param totalStaked The total staked balance. */ function _setRewardsPerSecond( uint256 emissionPerSecond, uint256 totalStaked ) internal { _settleGlobalIndexUpToNow(totalStaked); _REWARDS_PER_SECOND_ = emissionPerSecond; emit RewardsPerSecondUpdated(emissionPerSecond); } /** * @dev Claim tokens, sending them to the specified recipient. * * Note: In order to claim all accrued rewards, the total and user staked balances must first be * settled before calling this function. * * @param user The user's address. * @param recipient The address to send rewards to. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, address recipient ) internal returns (uint256) { uint256 accruedRewards = _USER_REWARDS_BALANCES_[user]; _USER_REWARDS_BALANCES_[user] = 0; REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards); emit ClaimedRewards(user, recipient, accruedRewards); return accruedRewards; } /** * @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a * settlement of the global index up to `block.timestamp`. Should be called with the OLD user * and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param totalStaked Total tokens staked by all users during the period since the last global * index update. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToNow( address user, uint256 userStaked, uint256 totalStaked ) internal returns (uint256) { uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked); return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a * user's rewards if their balance was known to have changed on that epoch boundary. * * @param user The user's address. * @param userStaked Tokens staked by the user. Should be accurate for the time period * since the last update to this user and up to the end of the * specified epoch. * @param epochNumber Settle the user's rewards up to the end of this epoch. * * @return The user's accrued rewards, including past unclaimed rewards, up to the end of the * specified epoch. */ function _settleUserRewardsUpToEpoch( address user, uint256 userStaked, uint256 epochNumber ) internal returns (uint256) { uint256 globalIndex = _EPOCH_INDEXES_[epochNumber]; return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle the global index up to the end of the given epoch. * * IMPORTANT: This function should only be called under conditions which ensure the following: * - `epochNumber` < the current epoch number * - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp` * - `_EPOCH_INDEXES_[epochNumber] = 0` */ function _settleGlobalIndexUpToEpoch( uint256 totalStaked, uint256 epochNumber ) internal returns (uint256) { uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1)); uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp); _EPOCH_INDEXES_[epochNumber] = globalIndex; return globalIndex; } // ============ Private Functions ============ /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * since the last update to the global index. * * @return The new global index. */ function _settleGlobalIndexUpToNow( uint256 totalStaked ) private returns (uint256) { return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp); } /** * @dev Helper function which settles a user's rewards up to a global index. Should be called * any time a user's staked balance changes, with the OLD user and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param newGlobalIndex The new index value to bring the user index up to. MUST NOT be less * than the user's index. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToIndex( address user, uint256 userStaked, uint256 newGlobalIndex ) private returns (uint256) { uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user]; uint256 oldUserIndex = _USER_INDEXES_[user]; if (oldUserIndex == newGlobalIndex) { return oldAccruedRewards; } uint256 newAccruedRewards; if (userStaked == 0) { // Note: Even if the user's staked balance is zero, we still need to update the user index. newAccruedRewards = oldAccruedRewards; } else { // Calculate newly accrued rewards since the last update to the user's index. uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); // Update the user's rewards. _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } // Update the user's index. _USER_INDEXES_[user] = newGlobalIndex; emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; } /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp). * @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy * `settleUpToTimestamp <= block.timestamp`. * * @return The new global index. */ function _settleGlobalIndexUpToTimestamp( uint256 totalStaked, uint256 settleUpToTimestamp ) private returns (uint256) { uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_); // The goal of this function is to calculate rewards earned since the last global index update. // These rewards are earned over the time interval which is the intersection of the intervals // [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END]. // // We can simplify a bit based on the assumption: // `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START` // // Get the start and end of the time interval under consideration. uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_); uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END); // Return early if the interval has length zero (incl. case where intervalEnd < intervalStart). if (intervalEnd <= intervalStart) { return oldGlobalIndex; } // Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_. uint256 emissionPerSecond = _REWARDS_PER_SECOND_; if (emissionPerSecond == 0 || totalStaked == 0) { // Ensure a log is emitted if the timestamp changed, even if the index does not change. _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); emit GlobalIndexUpdated(oldGlobalIndex); return oldGlobalIndex; } // Calculate the change in index over the interval. uint256 timeDelta = intervalEnd.sub(intervalStart); uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked); // Calculate, update, and return the new global index. uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta); // Update storage. (Shared storage slot.) _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch * zero starts at a non-negative timestamp. * * The recommended epoch length and blackout window are 28 and 7 days respectively; however, these * are modifiable by the admin, within the specified bounds. */ abstract contract SM1EpochSchedule is SM1Storage { using SafeCast for uint256; using SafeMath for uint256; // ============ Events ============ event EpochParametersChanged( SM1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __SM1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'SM1EpochSchedule: Epoch zero must start after initialization' ); _setBlackoutWindow(blackoutWindow); _setEpochParameters(interval, offset); } // ============ Public Functions ============ /** * @notice Get the epoch at the current block timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); return offsetTimestamp.div(interval); } /** * @notice Get the time remaining in the current epoch. * * NOTE: Reverts if epoch zero has not started. * * @return The number of seconds until the next epoch. */ function getTimeRemainingInCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval); return interval.sub(timeElapsedInEpoch); } /** * @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`. * * @return The timestamp in seconds representing the start of that epoch. */ function getStartOfEpoch( uint256 epochNumber ) public view returns (uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); return epochNumber.mul(interval).add(offset); } /** * @notice Check whether we are at or past the start of epoch zero. * * @return Boolean `true` if the current timestamp is at least the start of epoch zero, * otherwise `false`. */ function hasEpochZeroStarted() public view returns (bool) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 offset = uint256(epochParameters.offset); return block.timestamp >= offset; } /** * @notice Check whether we are in a blackout window, where withdrawal requests are restricted. * Note that before epoch zero has started, there are no blackout windows. * * @return Boolean `true` if we are in a blackout window, otherwise `false`. */ function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; } // ============ Internal Functions ============ function _setEpochParameters( uint256 interval, uint256 offset ) internal { SM1Types.EpochParameters memory epochParameters = SM1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * Recall that the formula for epoch number is `n = (t - b) / a`. * * NOTE: Reverts if epoch zero has not started. * * @return The values `a` and `(t - b)`. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require( block.timestamp >= offset, 'SM1EpochSchedule: Epoch zero has not started' ); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1GovernancePowerDelegation } from './SM1GovernancePowerDelegation.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Implements governance functionality for the tokens. * * Also allows a user with an active stake to transfer their staked tokens to another user, * even if they would otherwise be restricted from withdrawing. */ abstract contract SM1ERC20 is SM1StakedBalances, SM1GovernancePowerDelegation, IERC20Detailed { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for token approval via EIP-2612 permit. bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); // ============ External Functions ============ function name() external pure override returns (string memory) { return 'Staked DYDX'; } function symbol() external pure override returns (string memory) { return 'stkDYDX'; } function decimals() external pure override returns (uint8) { return 18; } /** * @notice Get the total supply of staked balances. * * Note that due to the exchange rate, this is different than querying the total balance of * underyling token staked to this contract. * * @return The sum of all staked balances. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get a user's staked balance. * * Note that due to the exchange rate, one unit of staked balance may not be equivalent to one * unit of the underlying token. Also note that a user's staked balance is different from a * user's transferable balance. * * @param account The account to get the balance of. * * @return The user's staked balance. */ function balanceOf( address account ) public view override(SM1GovernancePowerDelegation, IERC20) returns (uint256) { return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account); } function transfer( address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) external view override returns (uint256) { return _ALLOWANCES_[owner][spender]; } function approve( address spender, uint256 amount ) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _ALLOWANCES_[sender][msg.sender].sub(amount, 'SM1ERC20: transfer amount exceeds allowance') ); return true; } function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { _approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { _approve( msg.sender, spender, _ALLOWANCES_[msg.sender][spender].sub( subtractedValue, 'SM1ERC20: Decreased allowance below zero' ) ); return true; } /** * @notice Implements the permit function as specified in EIP-2612. * * @param owner Address of the token owner. * @param spender Address of the spender. * @param value Amount of allowance. * @param deadline Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require( owner != address(0), 'SM1ERC20: INVALID_OWNER' ); require( block.timestamp <= deadline, 'SM1ERC20: INVALID_EXPIRATION' ); uint256 currentValidNonce = _NONCES_[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', _DOMAIN_SEPARATOR_, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require( owner == ecrecover(digest, v, r, s), 'SM1ERC20: INVALID_SIGNATURE' ); _NONCES_[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require( sender != address(0), 'SM1ERC20: Transfer from address(0)' ); require( recipient != address(0), 'SM1ERC20: Transfer to address(0)' ); require( getTransferableBalance(sender) >= amount, 'SM1ERC20: Transfer exceeds next epoch active balance' ); // Update staked balances and delegate snapshots. _transferCurrentAndNextActiveBalance(sender, recipient, amount); _moveDelegatesForTransfer(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require( owner != address(0), 'SM1ERC20: Approve from address(0)' ); require( spender != address(0), 'SM1ERC20: Approve to address(0)' ); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import { IERC20 } from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IGovernancePowerDelegationERC20 } from '../../../interfaces/IGovernancePowerDelegationERC20.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ExchangeRate } from './SM1ExchangeRate.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1GovernancePowerDelegation * @author dYdX * * @dev Provides support for two types of governance powers which are separately delegatable. * Provides functions for delegation and for querying a user's power at a certain block number. * * Internally, makes use of staked balances denoted in staked units, but returns underlying token * units from the getPowerAtBlock() and getPowerCurrent() functions. * * This is based on, and is designed to match, Aave's implementation, which is used in their * governance token and staked token contracts. */ abstract contract SM1GovernancePowerDelegation is SM1ExchangeRate, IGovernancePowerDelegationERC20 { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for delegation by signature of a specific governance power type. bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256( 'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)' ); /// @notice EIP-712 typehash for delegation by signature of all governance powers. bytes32 public constant DELEGATE_TYPEHASH = keccak256( 'Delegate(address delegatee,uint256 nonce,uint256 expiry)' ); // ============ External Functions ============ /** * @notice Delegates a specific governance power of the sender to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType( address delegatee, DelegationType delegationType ) external override { _delegateByType(msg.sender, delegatee, delegationType); } /** * @notice Delegates all governance powers of the sender to a delegatee. * * @param delegatee The address to delegate power to. */ function delegate( address delegatee ) external override { _delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER); _delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER); } /** * @dev Delegates specific governance power from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateByTypeBySig( address delegatee, DelegationType delegationType, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256( abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry) ); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, delegationType); } /** * @dev Delegates both governance powers from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, DelegationType.VOTING_POWER); _delegateByType(signer, delegatee, DelegationType.PROPOSITION_POWER); } /** * @notice Returns the delegatee of a user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType( address delegator, DelegationType delegationType ) external override view returns (address) { (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); return _getDelegatee(delegator, delegates); } /** * @notice Returns the current power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent( address user, DelegationType delegationType ) external override view returns (uint256) { return getPowerAtBlock(user, block.number, delegationType); } /** * @notice Get the next valid nonce for EIP-712 signatures. * * This nonce should be used when signing for any of the following functions: * - permit() * - delegateByTypeBySig() * - delegateBySig() */ function nonces( address owner ) external view returns (uint256) { return _NONCES_[owner]; } // ============ Public Functions ============ function balanceOf( address account ) public view virtual returns (uint256); /** * @notice Returns the power of a user at a certain block, denominated in underlying token units. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The user's governance power of the specified type, in underlying token units. */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) public override view returns (uint256) { ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); uint256 stakeAmount = _findValueAtBlock( snapshots[user], snapshotCounts[user], blockNumber, 0 ); uint256 exchangeRate = _findValueAtBlock( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, blockNumber, EXCHANGE_RATE_BASE ); return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, exchangeRate); } // ============ Internal Functions ============ /** * @dev Delegates one specific power to a delegatee. * * @param delegator The user whose power to delegate. * @param delegatee The address to delegate power to. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _delegateByType( address delegator, address delegatee, DelegationType delegationType ) internal { require( delegatee != address(0), 'SM1GovernancePowerDelegation: INVALID_DELEGATEE' ); (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); uint256 delegatorBalance = balanceOf(delegator); address previousDelegatee = _getDelegatee(delegator, delegates); delegates[delegator] = delegatee; _moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType); emit DelegateChanged(delegator, delegatee, delegationType); } /** * @dev Update delegate snapshots whenever staked tokens are transfered, minted, or burned. * * @param from The sender. * @param to The recipient. * @param stakedAmount The amount being transfered, denominated in staked units. */ function _moveDelegatesForTransfer( address from, address to, uint256 stakedAmount ) internal { address votingPowerFromDelegatee = _getDelegatee(from, _VOTING_DELEGATES_); address votingPowerToDelegatee = _getDelegatee(to, _VOTING_DELEGATES_); _moveDelegatesByType( votingPowerFromDelegatee, votingPowerToDelegatee, stakedAmount, DelegationType.VOTING_POWER ); address propositionPowerFromDelegatee = _getDelegatee(from, _PROPOSITION_DELEGATES_); address propositionPowerToDelegatee = _getDelegatee(to, _PROPOSITION_DELEGATES_); _moveDelegatesByType( propositionPowerFromDelegatee, propositionPowerToDelegatee, stakedAmount, DelegationType.PROPOSITION_POWER ); } /** * @dev Moves power from one user to another. * * @param from The user from which delegated power is moved. * @param to The user that will receive the delegated power. * @param amount The amount of power to be moved. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _moveDelegatesByType( address from, address to, uint256 amount, DelegationType delegationType ) internal { if (from == to) { return; } ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); if (from != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage fromSnapshots = snapshots[from]; uint256 fromSnapshotCount = snapshotCounts[from]; uint256 previousBalance = 0; if (fromSnapshotCount != 0) { previousBalance = fromSnapshots[fromSnapshotCount - 1].value; } uint256 newBalance = previousBalance.sub(amount); snapshotCounts[from] = _writeSnapshot( fromSnapshots, fromSnapshotCount, newBalance ); emit DelegatedPowerChanged(from, newBalance, delegationType); } if (to != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage toSnapshots = snapshots[to]; uint256 toSnapshotCount = snapshotCounts[to]; uint256 previousBalance = 0; if (toSnapshotCount != 0) { previousBalance = toSnapshots[toSnapshotCount - 1].value; } uint256 newBalance = previousBalance.add(amount); snapshotCounts[to] = _writeSnapshot( toSnapshots, toSnapshotCount, newBalance ); emit DelegatedPowerChanged(to, newBalance, delegationType); } } /** * @dev Returns delegation data (snapshot, snapshotCount, delegates) by delegation type. * * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The mapping of each user to a mapping of snapshots. * @return The mapping of each user to the total number of snapshots for that user. * @return The mapping of each user to the user's delegate. */ function _getDelegationDataByType( DelegationType delegationType ) internal view returns ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage, mapping(address => uint256) storage, mapping(address => address) storage ) { if (delegationType == DelegationType.VOTING_POWER) { return ( _VOTING_SNAPSHOTS_, _VOTING_SNAPSHOT_COUNTS_, _VOTING_DELEGATES_ ); } else { return ( _PROPOSITION_SNAPSHOTS_, _PROPOSITION_SNAPSHOT_COUNTS_, _PROPOSITION_DELEGATES_ ); } } /** * @dev Returns the delegatee of a user. If a user never performed any delegation, their * delegated address will be 0x0, in which case we return the user's own address. * * @param delegator The address of the user for which return the delegatee. * @param delegates The mapping of delegates for a particular type of delegation. */ function _getDelegatee( address delegator, mapping(address => address) storage delegates ) internal view returns (address) { address previousDelegatee = delegates[delegator]; if (previousDelegatee == address(0)) { return delegator; } return previousDelegatee; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; interface IGovernancePowerDelegationERC20 { enum DelegationType { VOTING_POWER, PROPOSITION_POWER } /** * @dev Emitted when a user delegates governance power to another user. * * @param delegator The delegator. * @param delegatee The delegatee. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegateChanged( address indexed delegator, address indexed delegatee, DelegationType delegationType ); /** * @dev Emitted when an action changes the delegated power of a user. * * @param user The user whose delegated power has changed. * @param amount The new amount of delegated power for the user. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType); /** * @dev Delegates a specific governance power to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType(address delegatee, DelegationType delegationType) external virtual; /** * @dev Delegates all governance powers to a delegatee. * * @param delegatee The user to which the power will be delegated. */ function delegate(address delegatee) external virtual; /** * @dev Returns the delegatee of an user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType(address delegator, DelegationType delegationType) external view virtual returns (address); /** * @dev Returns the current delegated power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent(address user, DelegationType delegationType) external view virtual returns (uint256); /** * @dev Returns the delegated power of a user at a certain block. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Snapshots } from './SM1Snapshots.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1ExchangeRate * @author dYdX * * @dev Performs math using the exchange rate, which converts between underlying units of the token * that was staked (e.g. STAKED_TOKEN.balanceOf(account)), and staked units, used by this contract * for all staked balances (e.g. this.balanceOf(account)). * * OVERVIEW: * * The exchange rate is stored as a multiple of EXCHANGE_RATE_BASE, and represents the number of * staked balance units that each unit of underlying token is worth. Before any slashes have * occurred, the exchange rate is equal to one. The exchange rate can increase with each slash, * indicating that staked balances are becoming less and less valuable, per unit, relative to the * underlying token. * * AVOIDING OVERFLOW AND UNDERFLOW: * * Staked balances are represented internally as uint240, so the result of an operation returning * a staked balances must return a value less than 2^240. Intermediate values in calcuations are * represented as uint256, so all operations within a calculation must return values under 2^256. * * In the functions below operating on the exchange rate, we are strategic in our choice of the * order of multiplication and division operations, in order to avoid both overflow and underflow. * * We use the following assumptions and principles to implement this module: * - (ASSUMPTION) An amount denoted in underlying token units is never greater than 10^28. * - If the exchange rate is greater than 10^46, then we may perform division on the exchange * rate before performing multiplication, provided that the denominator is not greater * than 10^28 (to ensure a result with at least 18 decimals of precision). Specifically, * we use EXCHANGE_RATE_MAY_OVERFLOW as the cutoff, which is a number greater than 10^46. * - Since staked balances are stored as uint240, we cap the exchange rate to ensure that a * staked balance can never overflow (using the assumption above). */ abstract contract SM1ExchangeRate is SM1Snapshots, SM1Storage { using SafeMath for uint256; // ============ Constants ============ /// @notice The assumed upper bound on the total supply of the staked token. uint256 public constant MAX_UNDERLYING_BALANCE = 1e28; /// @notice Base unit used to represent the exchange rate, for additional precision. uint256 public constant EXCHANGE_RATE_BASE = 1e18; /// @notice Cutoff where an exchange rate may overflow after multiplying by an underlying balance. /// @dev Approximately 1.2e49 uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE; /// @notice Cutoff where a stake amount may overflow after multiplying by EXCHANGE_RATE_BASE. /// @dev Approximately 1.2e59 uint256 public constant STAKE_AMOUNT_MAY_OVERFLOW = (2 ** 256 - 1) / EXCHANGE_RATE_BASE; /// @notice Max exchange rate. /// @dev Approximately 1.8e62 uint256 public constant MAX_EXCHANGE_RATE = ( ((2 ** 240 - 1) / MAX_UNDERLYING_BALANCE) * EXCHANGE_RATE_BASE ); // ============ Initializer ============ function __SM1ExchangeRate_init() internal { _EXCHANGE_RATE_ = EXCHANGE_RATE_BASE; } function stakeAmountFromUnderlyingAmount( uint256 underlyingAmount ) internal view returns (uint256) { uint256 exchangeRate = _EXCHANGE_RATE_; if (exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return underlyingAmount.mul(exchangeRateUnbased); } else { return underlyingAmount.mul(exchangeRate).div(EXCHANGE_RATE_BASE); } } function underlyingAmountFromStakeAmount( uint256 stakeAmount ) internal view returns (uint256) { return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, _EXCHANGE_RATE_); } function underlyingAmountFromStakeAmountWithExchangeRate( uint256 stakeAmount, uint256 exchangeRate ) internal pure returns (uint256) { if (stakeAmount > STAKE_AMOUNT_MAY_OVERFLOW) { // Note that this case implies that exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW. uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return stakeAmount.div(exchangeRateUnbased); } else { return stakeAmount.mul(EXCHANGE_RATE_BASE).div(exchangeRate); } } function updateExchangeRate( uint256 numerator, uint256 denominator ) internal returns (uint256) { uint256 oldExchangeRate = _EXCHANGE_RATE_; // Avoid overflow. // Note that the numerator and denominator are both denominated in underlying token units. uint256 newExchangeRate; if (oldExchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { newExchangeRate = oldExchangeRate.div(denominator).mul(numerator); } else { newExchangeRate = oldExchangeRate.mul(numerator).div(denominator); } require( newExchangeRate <= MAX_EXCHANGE_RATE, 'SM1ExchangeRate: Max exchange rate exceeded' ); _EXCHANGE_RATE_SNAPSHOT_COUNT_ = _writeSnapshot( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, newExchangeRate ); _EXCHANGE_RATE_ = newExchangeRate; return newExchangeRate; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Snapshots * @author dYdX * * @dev Handles storage and retrieval of historical values by block number. * * Note that the snapshot stored at a given block number represents the value as of the end of * that block. */ abstract contract SM1Snapshots { /** * @dev Writes a snapshot of a value at the current block. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param newValue The new value to snapshot at the current block. * * @return The new snapshot count. */ function _writeSnapshot( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 newValue ) internal returns (uint256) { uint256 currentBlock = block.number; if ( snapshotCount != 0 && snapshots[snapshotCount - 1].blockNumber == currentBlock ) { // If there was a previous snapshot for this block, overwrite it. snapshots[snapshotCount - 1].value = newValue; return snapshotCount; } else { snapshots[snapshotCount] = SM1Types.Snapshot(currentBlock, newValue); return snapshotCount + 1; } } /** * @dev Search for the snapshot value at a given block. Uses binary search. * * Reverts if `blockNumber` is greater than the current block number. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param blockNumber The block number to search for. * @param initialValue The value to return if `blockNumber` is before the earliest snapshot. * * @return The snapshot value at the specified block number. */ function _findValueAtBlock( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 blockNumber, uint256 initialValue ) internal view returns (uint256) { require( blockNumber <= block.number, 'SM1Snapshots: INVALID_BLOCK_NUMBER' ); if (snapshotCount == 0) { return initialValue; } // Check earliest snapshot. if (blockNumber < snapshots[0].blockNumber) { return initialValue; } // Check latest snapshot. if (blockNumber >= snapshots[snapshotCount - 1].blockNumber) { return snapshots[snapshotCount - 1].value; } uint256 lower = 0; uint256 upper = snapshotCount - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // Ceil, avoiding overflow. SM1Types.Snapshot memory snapshot = snapshots[center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return snapshots[lower].value; } }
Always settle total active balance before settling a staker active balance. Always settle staker active balance before settling staker rewards. Settle rewards balance since we want to claim the full accrued amount. Claim rewards balance.
function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { uint256 totalBalance = _settleTotalActiveBalance(); uint256 userBalance = _settleBalance(staker, true); _settleUserRewardsUpToNow(staker, userBalance, totalBalance); return _claimRewards(staker, recipient); }
203,910
pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @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; } } /** * @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); } /** * @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); } /** * @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); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).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 {} } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } interface LootInterface { function ownerOf(uint256 tokenId) external view returns (address owner); } contract Loot is ERC721Enumerable, ReentrancyGuard, Ownable { uint256 public publicPrice = 10000000000000000; //0.01 ETH //Loot Contract address public lootAddress = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7; LootInterface public lootContract = LootInterface(lootAddress); string[] private adjectives = [ "Surprising", "Predictable", "Agreeable", "Mysterious", "Colossal", "Great", "Huge", "Lazy", "Miniature", "Microscopic", "Massive", "Puny", "Immense", "Large", "Little", "Scrawny", "Short", "Small", "Tiny", "Gigantic", "Mammoth", "Gentle", "Lively", "Ambitious", "Delightful", "Eager", "Happy", "Jolly", "Polite", "Victorious", "Witty", "Wonderful", "Zealous", "Attractive", "Dazzling", "Magnificent", "Plain", "Scruffy", "Unsightly", "Legendary", "Sneaky", "Fit", "Drab", "Elegant", "Glamorous", "Truthful", "Pitiful", "Angry", "Fierce", "Embarrassed", "Scary", "Terrifying", "Panicky", "Thoughtless", "Worried", "Foolish", "Frantic", "Perfect", "Timely", "Dashing", "Dangerous", "Icy", "Dull", "Cloudy", "Enchanting" ]; string[] private toots = [ "Butt ghost", "Fart", "Wind", "Air biscuit", "Bark", "Blast", "Bomber", "Boom-boom", "Bubbler", "Burner", "Butt Bazooka", "Butt Bongo", "Butt Sneeze", "Butt Trumpet", "Butt Tuba", "Butt Yodeling", "Cheek Squeak", "Cheeser", "Drifter", "Fizzler", "Flatus", "Floater", "Fluffy", "Frump", "Gas", "Grunt", "Gurgler", "Hisser", "Honker", "Hot wind", "Nasty cough", "One-man salute", "Bottom burp", "Peter", "Pewie", "Poof", "Pootsa", "Pop tart", "Power puff", "Puffer", "Putt-Putt", "Quack", "Quaker", "Raspberry", "Rattler", "Rump Ripper", "Rump Roar", "Slider", "Spitter", "Squeaker", "Steamer", "Stinker", "Stinky", "Tootsie", "Trouser Cough", "Trouser Trumpet", "Trunk Bunk", "Turtle Burp", "Tushy Tickler", "Under Thunder", "Wallop", "Whiff", "Whoopee", "Whopper", "Vapor Loaf" ]; string[] private suffixes = [ "of Might", "of Tang", "of Death", "of Life", "of Pollution", "of Power", "of Giants", "of Titans", "of Skill", "of Perfection", "of Brilliance", "of Enlightenment", "of Protection", "of Anger", "of Rage", "of Fury", "of Vitriol", "of the Fox", "of Detection", "of Reflection", "of the Twins", "of the Smog", "of the Dragon" ]; string[] private namePrefixes = [ "Agony", "Apocalypse", "Armageddon", "Beast", "Behemoth", "Blight", "Blood", "Bramble", "Brimstone", "Brood", "Carrion", "Cataclysm", "Chimeric", "Corpse", "Corruption", "Damnation", "Death", "Demon", "Dire", "Dragon", "Dread", "Doom", "Dusk", "Eagle", "Empyrean", "Fate", "Foe", "Gale", "Ghoul", "Gloom", "Glyph", "Golem", "Grim", "Hate", "Havoc", "Honour", "Horror", "Hypnotic", "Kraken", "Loath", "Maelstrom", "Mind", "Miracle", "Morbid", "Oblivion", "Onslaught", "Pain", "Pandemonium", "Phoenix", "Plague", "Rage", "Rapture", "Rune", "Skull", "Sol", "Soul", "Sorrow", "Spirit", "Storm", "Tempest", "Torment", "Vengeance", "Victory", "Viper", "Vortex", "Woe", "Wrath", "Light's", "Shimmering" ]; string[] private nameSuffixes = [ "Bane", "Root", "Bite", "Song", "Roar", "Grasp", "Instrument", "Glow", "Bender", "Shadow", "Whisper", "Shout", "Growl", "Tear", "Peak", "Form", "Sun", "Moon" ]; function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getToot(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "TOOT", toots); } function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; output = string(abi.encodePacked(adjectives[rand % adjectives.length], " ", output)); uint256 greatness = rand % 21; if (greatness > 14) { output = string(abi.encodePacked(output, " ", suffixes[rand % suffixes.length])); } if (greatness >= 18) { string[2] memory name; name[0] = namePrefixes[rand % namePrefixes.length]; name[1] = nameSuffixes[rand % nameSuffixes.length]; if (greatness == 18) { output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output)); } else { output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output, " +1")); } } return output; } function tokenURI(uint256 tokenId) override public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getToot(tokenId); parts[3] = '</text><text x="10" y="40" class="base">'; parts[4] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4])); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Toot #', toString(tokenId), '", "description": "Toots are randomized adventurer farts generated and stored on chain. Smells, Stats, images, and other functionality are intentionally omitted for others to interpret. Feel free to use Toots in any way you want. Compatible with Loot (for Adventurers)", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } function mint(uint256 tokenId) public payable{ require(tokenId > 8000 && tokenId < 16000, "Token ID invalid"); require(publicPrice <= msg.value, "Ether value sent is not correct"); _safeMint(_msgSender(), tokenId); } function multiMint(uint256[] memory tokenIds) public payable nonReentrant { require((publicPrice * tokenIds.length) <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < tokenIds.length; i++) { require(tokenIds[i] > 8000 && tokenIds[i] < 16000, "Token ID invalid"); _safeMint(msg.sender, tokenIds[i]); } } function mintWithLoot(uint256 lootId) public payable nonReentrant { require(lootId > 0 && lootId <= 8000, "Token ID invalid"); require(lootContract.ownerOf(lootId) == msg.sender, "Not the owner of this loot"); _safeMint(_msgSender(), lootId); } function multiMintWithLoot(uint256[] memory lootIds) public payable nonReentrant { for (uint256 i = 0; i < lootIds.length; i++) { require(lootContract.ownerOf(lootIds[i]) == msg.sender, "Not the owner of this loot"); _safeMint(_msgSender(), lootIds[i]); } } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } 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); } function withdrawAll() public payable onlyOwner { require(payable(_msgSender()).send(address(this).balance)); } constructor() ERC721("Toot", "TOOT") Ownable() {} } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } }
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"); }
1,635,090
/** *Submitted for verification at Etherscan.io on 2021-05-07 */ /* ___ _ ___ _ | .\ ___ _ _ <_> ___ | __><_>._ _ ___ ._ _ ___ ___ | _// ._>| '_>| ||___|| _> | || ' |<_> || ' |/ | '/ ._> |_| \___.|_| |_| |_| |_||_|_|<___||_|_|\_|_.\___. * PeriFinance: RewardEscrowV2.sol * * Latest source (may be newer): https://github.com/PeriFinance/periFinance/blob/master/contracts/RewardEscrowV2.sol * Docs: Will be added in the future. /contracts/RewardEscrowV2 * * Contract Dependencies: * - BaseRewardEscrowV2 * - IAddressResolver * - Owned * Libraries: * - SafeDecimalMath * - SafeMath * - VestingEntries * * MIT License * =========== * * Copyright (c) 2021 PeriFinance * * 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 */ pragma solidity ^0.5.16; // https://docs.peri.finance/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // https://docs.peri.finance/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getPynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // https://docs.peri.finance/contracts/source/interfaces/ipynth interface IPynth { // Views function currencyKey() external view returns (bytes32); function transferablePynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to PeriFinance function burn(address account, uint amount) external; function issue(address account, uint amount) external; } // https://docs.peri.finance/contracts/source/interfaces/iissuer interface IIssuer { // Views function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availablePynthCount() external view returns (uint); function availablePynths(uint index) external view returns (IPynth); function canBurnPynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function issuanceRatio() external view returns (uint); function lastIssueEvent(address account) external view returns (uint); function maxIssuablePynths(address issuer) external view returns (uint maxIssuable); function minimumStakeTime() external view returns (uint); function remainingIssuablePynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function pynths(bytes32 currencyKey) external view returns (IPynth); function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory); function pynthsByAddress(address pynthAddress) external view returns (bytes32); function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint); function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid); // Restricted: used internally to PeriFinance function issuePynths(address from, uint amount) external; function issuePynthsOnBehalf( address issueFor, address from, uint amount ) external; function issueMaxPynths(address from) external; function issueMaxPynthsOnBehalf(address issueFor, address from) external; function stakeUSDCAndIssuePynths( address from, uint usdcStakeAmount, uint issueAmount ) external; function stakeUSDCAndIssueMaxPynths(address from, uint usdcStakeAmount) external; function burnPynths(address from, uint amount) external; function burnPynthsOnBehalf( address burnForAddress, address from, uint amount ) external; function burnPynthsToTarget(address from) external; function burnPynthsToTargetOnBehalf(address burnForAddress, address from) external; function unstakeUSDCAndBurnPynths( address from, uint usdcUnstakeAmount, uint burnAmount ) external; function unstakeUSDCToMaxAndBurnPynths(address from, uint burnAmount) external; function liquidateDelinquentAccount( address account, uint pusdAmount, address liquidator ) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/addressresolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(MixinResolver[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getPynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.pynths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // solhint-disable payable-fallback // https://docs.peri.finance/contracts/source/contracts/readproxy contract ReadProxy is Owned { address public target; constructor(address _owner) public Owned(_owner) {} function setTarget(address _target) external onlyOwner { target = _target; emit TargetUpdated(target); } function() external { // The basics of a proxy read call // Note that msg.sender in the underlying will always be the address of this contract. assembly { calldatacopy(0, 0, calldatasize) // Use of staticcall - this will revert if the underlying function mutates state let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) if iszero(result) { revert(0, returndatasize) } return(0, returndatasize) } } event TargetUpdated(address newTarget); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/mixinresolver contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } // https://docs.peri.finance/contracts/source/contracts/limitedsetup contract LimitedSetup { uint public setupExpiryTime; /** * @dev LimitedSetup Constructor. * @param setupDuration The time the setup period will last for. */ constructor(uint setupDuration) internal { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime, "Can only perform this action during setup"); _; } } pragma experimental ABIEncoderV2; library VestingEntries { struct VestingEntry { uint64 endTime; uint256 escrowAmount; } struct VestingEntryWithID { uint64 endTime; uint256 escrowAmount; uint256 entryID; } } interface IRewardEscrowV2 { // Views function balanceOf(address account) external view returns (uint); function numVestingEntries(address account) external view returns (uint); function totalEscrowedAccountBalance(address account) external view returns (uint); function totalVestedAccountBalance(address account) external view returns (uint); function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint); function getVestingSchedules( address account, uint256 index, uint256 pageSize ) external view returns (VestingEntries.VestingEntryWithID[] memory); function getAccountVestingEntryIDs( address account, uint256 index, uint256 pageSize ) external view returns (uint256[] memory); function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint); function getVestingEntry(address account, uint256 entryID) external view returns (uint64, uint256); // Mutative functions function vest(uint256[] calldata entryIDs) external; function createEscrowEntry( address beneficiary, uint256 deposit, uint256 duration ) external; function appendVestingEntry( address account, uint256 quantity, uint256 duration ) external; function migrateVestingSchedule(address _addressToMigrate) external; function migrateAccountEscrowBalances( address[] calldata accounts, uint256[] calldata escrowBalances, uint256[] calldata vestedBalances ) external; // Account Merging function startMergingWindow() external; function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external; function nominateAccountToMerge(address account) external; function accountMergingIsOpen() external view returns (bool); // L2 Migration function importVestingEntries( address account, uint256 escrowedAmount, VestingEntries.VestingEntry[] calldata vestingEntries ) external; // Return amount of PERI transfered to PynthetixBridgeToOptimism deposit contract function burnForMigration(address account, uint256[] calldata entryIDs) external returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries); } /** * @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; } } // Libraries // https://docs.peri.finance/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // https://docs.peri.finance/contracts/source/interfaces/ierc20 interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // https://docs.peri.finance/contracts/source/interfaces/ifeepool interface IFeePool { // Views // solhint-disable-next-line func-name-mixedcase function FEE_ADDRESS() external view returns (address); function feesAvailable(address account) external view returns (uint, uint); function feePeriodDuration() external view returns (uint); function isFeesClaimable(address account) external view returns (bool); function targetThreshold() external view returns (uint); function totalFeesAvailable() external view returns (uint); function totalRewardsAvailable() external view returns (uint); // Mutative Functions function claimFees() external returns (bool); function claimOnBehalf(address claimingForAddress) external returns (bool); function closeCurrentFeePeriod() external; // Restricted: used internally to PeriFinance function appendAccountIssuanceRecord( address account, uint lockedAmount, uint debtEntryIndex, bytes32 currencyKey ) external; function recordFeePaid(uint pUSDAmount) external; function setRewardsToDistribute(uint amount) external; } interface IVirtualPynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function pynth() external view returns (IPynth); // Mutative functions function settle(address account) external; } // https://docs.peri.finance/contracts/source/interfaces/iperiFinance interface IPeriFinance { // Views function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availablePynthCount() external view returns (uint); function availablePynths(uint index) external view returns (IPynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuablePynths(address issuer) external view returns (uint maxIssuable); function remainingIssuablePynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function pynths(bytes32 currencyKey) external view returns (IPynth); function pynthsByAddress(address pynthAddress) external view returns (bytes32); function totalIssuedPynths(bytes32 currencyKey) external view returns (uint); function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferablePeriFinance(address account) external view returns (uint transferable); // Mutative Functions function burnPynths(uint amount) external; function burnPynthsOnBehalf(address burnForAddress, uint amount) external; function burnPynthsToTarget() external; function burnPynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualPynth vPynth); function issueMaxPynths() external; function issuePynths(uint amount) external; function issuePynthsOnBehalf(address issueForAddress, uint amount) external; function issueMaxPynthsOnBehalf(address issueForAddress) external; function stakeUSDCAndIssuePynths(uint usdcStakeAmount, uint issueAmount) external; function stakeUSDCAndIssueMaxPynths(uint usdcStakingAmount) external; function unstakeUSDCAndBurnPynths(uint usdcUnstakeAmount, uint burnAmount) external; function unstakeUSDCToMaxAndBurnPynths(uint burnAmount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint pusdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } // Inheritance // Libraries // Internal references // https://docs.peri.finance/contracts/RewardEscrow contract BaseRewardEscrowV2 is Owned, IRewardEscrowV2, LimitedSetup(8 weeks), MixinResolver { using SafeMath for uint; using SafeDecimalMath for uint; mapping(address => mapping(uint256 => VestingEntries.VestingEntry)) public vestingSchedules; mapping(address => uint256[]) public accountVestingEntryIDs; /*Counter for new vesting entry ids. */ uint256 public nextEntryId; /* An account's total escrowed periFinance balance to save recomputing this for fee extraction purposes. */ mapping(address => uint256) public totalEscrowedAccountBalance; /* An account's total vested reward periFinance. */ mapping(address => uint256) public totalVestedAccountBalance; /* Mapping of nominated address to recieve account merging */ mapping(address => address) public nominatedReceiver; /* The total remaining escrowed balance, for verifying the actual periFinance balance of this contract against. */ uint256 public totalEscrowedBalance; /* Max escrow duration */ uint public max_duration = 2 * 52 weeks; // Default max 2 years duration /* Max account merging duration */ uint public maxAccountMergingDuration = 4 weeks; // Default 4 weeks is max /* ========== ACCOUNT MERGING CONFIGURATION ========== */ uint public accountMergingDuration = 1 weeks; uint public accountMergingStartTime; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_PERIFINANCE = "PeriFinance"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, address _resolver) public Owned(_owner) MixinResolver(_resolver) { nextEntryId = 1; } /* ========== VIEWS ======================= */ function feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function periFinance() internal view returns (IPeriFinance) { return IPeriFinance(requireAndGetAddress(CONTRACT_PERIFINANCE)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function _notImplemented() internal pure { revert("Cannot be run on this layer"); } /* ========== VIEW FUNCTIONS ========== */ // Note: use public visibility so that it can be invoked in a subclass function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](3); addresses[0] = CONTRACT_PERIFINANCE; addresses[1] = CONTRACT_FEEPOOL; addresses[2] = CONTRACT_ISSUER; } /** * @notice A simple alias to totalEscrowedAccountBalance: provides ERC20 balance integration. */ function balanceOf(address account) public view returns (uint) { return totalEscrowedAccountBalance[account]; } /** * @notice The number of vesting dates in an account's schedule. */ function numVestingEntries(address account) external view returns (uint) { return accountVestingEntryIDs[account].length; } /** * @notice Get a particular schedule entry for an account. * @return The vesting entry object and rate per second emission. */ function getVestingEntry(address account, uint256 entryID) external view returns (uint64 endTime, uint256 escrowAmount) { endTime = vestingSchedules[account][entryID].endTime; escrowAmount = vestingSchedules[account][entryID].escrowAmount; } function getVestingSchedules( address account, uint256 index, uint256 pageSize ) external view returns (VestingEntries.VestingEntryWithID[] memory) { uint256 endIndex = index + pageSize; // If index starts after the endIndex return no results if (endIndex <= index) { return new VestingEntries.VestingEntryWithID[](0); } // If the page extends past the end of the accountVestingEntryIDs, truncate it. if (endIndex > accountVestingEntryIDs[account].length) { endIndex = accountVestingEntryIDs[account].length; } uint256 n = endIndex - index; VestingEntries.VestingEntryWithID[] memory vestingEntries = new VestingEntries.VestingEntryWithID[](n); for (uint256 i; i < n; i++) { uint256 entryID = accountVestingEntryIDs[account][i + index]; VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryID]; vestingEntries[i] = VestingEntries.VestingEntryWithID({ endTime: uint64(entry.endTime), escrowAmount: entry.escrowAmount, entryID: entryID }); } return vestingEntries; } function getAccountVestingEntryIDs( address account, uint256 index, uint256 pageSize ) external view returns (uint256[] memory) { uint256 endIndex = index + pageSize; // If the page extends past the end of the accountVestingEntryIDs, truncate it. if (endIndex > accountVestingEntryIDs[account].length) { endIndex = accountVestingEntryIDs[account].length; } if (endIndex <= index) { return new uint256[](0); } uint256 n = endIndex - index; uint256[] memory page = new uint256[](n); for (uint256 i; i < n; i++) { page[i] = accountVestingEntryIDs[account][i + index]; } return page; } function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint total) { for (uint i = 0; i < entryIDs.length; i++) { VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryIDs[i]]; /* Skip entry if escrowAmount == 0 */ if (entry.escrowAmount != 0) { uint256 quantity = _claimableAmount(entry); /* add quantity to total */ total = total.add(quantity); } } } function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint) { VestingEntries.VestingEntry memory entry = vestingSchedules[account][entryID]; return _claimableAmount(entry); } function _claimableAmount(VestingEntries.VestingEntry memory _entry) internal view returns (uint256) { uint256 quantity; if (_entry.escrowAmount != 0) { /* Escrow amounts claimable if block.timestamp equal to or after entry endTime */ quantity = block.timestamp >= _entry.endTime ? _entry.escrowAmount : 0; } return quantity; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * Vest escrowed amounts that are claimable * Allows users to vest their vesting entries based on msg.sender */ function vest(uint256[] calldata entryIDs) external { uint256 total; for (uint i = 0; i < entryIDs.length; i++) { VestingEntries.VestingEntry storage entry = vestingSchedules[msg.sender][entryIDs[i]]; /* Skip entry if escrowAmount == 0 already vested */ if (entry.escrowAmount != 0) { uint256 quantity = _claimableAmount(entry); /* update entry to remove escrowAmount */ if (quantity > 0) { entry.escrowAmount = 0; } /* add quantity to total */ total = total.add(quantity); } } /* Transfer vested tokens. Will revert if total > totalEscrowedAccountBalance */ if (total != 0) { _transferVestedTokens(msg.sender, total); } } /** * @notice Create an escrow entry to lock PERI for a given duration in seconds * @dev This call expects that the depositor (msg.sender) has already approved the Reward escrow contract to spend the the amount being escrowed. */ function createEscrowEntry( address beneficiary, uint256 deposit, uint256 duration ) external { require(beneficiary != address(0), "Cannot create escrow with address(0)"); /* Transfer PERI from msg.sender */ require(IERC20(address(periFinance())).transferFrom(msg.sender, address(this), deposit), "token transfer failed"); /* Append vesting entry for the beneficiary address */ _appendVestingEntry(beneficiary, deposit, duration); } /** * @notice Add a new vesting entry at a given time and quantity to an account's schedule. * @dev A call to this should accompany a previous successful call to periFinance.transfer(rewardEscrow, amount), * to ensure that when the funds are withdrawn, there is enough balance. * @param account The account to append a new vesting entry to. * @param quantity The quantity of PERI that will be escrowed. * @param duration The duration that PERI will be emitted. */ function appendVestingEntry( address account, uint256 quantity, uint256 duration ) external onlyFeePool { _appendVestingEntry(account, quantity, duration); } /* Transfer vested tokens and update totalEscrowedAccountBalance, totalVestedAccountBalance */ function _transferVestedTokens(address _account, uint256 _amount) internal { _reduceAccountEscrowBalances(_account, _amount); totalVestedAccountBalance[_account] = totalVestedAccountBalance[_account].add(_amount); IERC20(address(periFinance())).transfer(_account, _amount); emit Vested(_account, block.timestamp, _amount); } function _reduceAccountEscrowBalances(address _account, uint256 _amount) internal { // Reverts if amount being vested is greater than the account's existing totalEscrowedAccountBalance totalEscrowedBalance = totalEscrowedBalance.sub(_amount); totalEscrowedAccountBalance[_account] = totalEscrowedAccountBalance[_account].sub(_amount); } /* ========== ACCOUNT MERGING ========== */ function accountMergingIsOpen() public view returns (bool) { return accountMergingStartTime.add(accountMergingDuration) > block.timestamp; } function startMergingWindow() external onlyOwner { accountMergingStartTime = block.timestamp; emit AccountMergingStarted(accountMergingStartTime, accountMergingStartTime.add(accountMergingDuration)); } function setAccountMergingDuration(uint256 duration) external onlyOwner { require(duration <= maxAccountMergingDuration, "exceeds max merging duration"); accountMergingDuration = duration; emit AccountMergingDurationUpdated(duration); } function setMaxAccountMergingWindow(uint256 duration) external onlyOwner { maxAccountMergingDuration = duration; emit MaxAccountMergingDurationUpdated(duration); } function setMaxEscrowDuration(uint256 duration) external onlyOwner { max_duration = duration; emit MaxEscrowDurationUpdated(duration); } /* Nominate an account to merge escrow and vesting schedule */ function nominateAccountToMerge(address account) external { require(account != msg.sender, "Cannot nominate own account to merge"); require(accountMergingIsOpen(), "Account merging has ended"); require(issuer().debtBalanceOf(msg.sender, "pUSD") == 0, "Cannot merge accounts with debt"); nominatedReceiver[msg.sender] = account; emit NominateAccountToMerge(msg.sender, account); } function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external { require(accountMergingIsOpen(), "Account merging has ended"); require(issuer().debtBalanceOf(accountToMerge, "pUSD") == 0, "Cannot merge accounts with debt"); require(nominatedReceiver[accountToMerge] == msg.sender, "Address is not nominated to merge"); uint256 totalEscrowAmountMerged; for (uint i = 0; i < entryIDs.length; i++) { // retrieve entry VestingEntries.VestingEntry memory entry = vestingSchedules[accountToMerge][entryIDs[i]]; /* ignore vesting entries with zero escrowAmount */ if (entry.escrowAmount != 0) { /* copy entry to msg.sender (destination address) */ vestingSchedules[msg.sender][entryIDs[i]] = entry; /* Add the escrowAmount of entry to the totalEscrowAmountMerged */ totalEscrowAmountMerged = totalEscrowAmountMerged.add(entry.escrowAmount); /* append entryID to list of entries for account */ accountVestingEntryIDs[msg.sender].push(entryIDs[i]); /* Delete entry from accountToMerge */ delete vestingSchedules[accountToMerge][entryIDs[i]]; } } /* update totalEscrowedAccountBalance for merged account and accountToMerge */ totalEscrowedAccountBalance[accountToMerge] = totalEscrowedAccountBalance[accountToMerge].sub( totalEscrowAmountMerged ); totalEscrowedAccountBalance[msg.sender] = totalEscrowedAccountBalance[msg.sender].add(totalEscrowAmountMerged); emit AccountMerged(accountToMerge, msg.sender, totalEscrowAmountMerged, entryIDs, block.timestamp); } /* Internal function for importing vesting entry and creating new entry for escrow liquidations */ function _addVestingEntry(address account, VestingEntries.VestingEntry memory entry) internal returns (uint) { uint entryID = nextEntryId; vestingSchedules[account][entryID] = entry; /* append entryID to list of entries for account */ accountVestingEntryIDs[account].push(entryID); /* Increment the next entry id. */ nextEntryId = nextEntryId.add(1); return entryID; } /* ========== MIGRATION OLD ESCROW ========== */ function migrateVestingSchedule(address) external { _notImplemented(); } function migrateAccountEscrowBalances( address[] calldata, uint256[] calldata, uint256[] calldata ) external { _notImplemented(); } /* ========== L2 MIGRATION ========== */ function burnForMigration(address, uint[] calldata) external returns (uint256, VestingEntries.VestingEntry[] memory) { _notImplemented(); } function importVestingEntries( address, uint256, VestingEntries.VestingEntry[] calldata ) external { _notImplemented(); } /* ========== INTERNALS ========== */ function _appendVestingEntry( address account, uint256 quantity, uint256 duration ) internal { /* No empty or already-passed vesting entries allowed. */ require(quantity != 0, "Quantity cannot be zero"); require(duration > 0 && duration <= max_duration, "Cannot escrow with 0 duration OR above max_duration"); /* There must be enough balance in the contract to provide for the vesting entry. */ totalEscrowedBalance = totalEscrowedBalance.add(quantity); require( totalEscrowedBalance <= IERC20(address(periFinance())).balanceOf(address(this)), "Must be enough balance in the contract to provide for the vesting entry" ); /* Escrow the tokens for duration. */ uint endTime = block.timestamp + duration; /* Add quantity to account's escrowed balance */ totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(quantity); uint entryID = nextEntryId; vestingSchedules[account][entryID] = VestingEntries.VestingEntry({endTime: uint64(endTime), escrowAmount: quantity}); accountVestingEntryIDs[account].push(entryID); /* Increment the next entry id. */ nextEntryId = nextEntryId.add(1); emit VestingEntryCreated(account, block.timestamp, quantity, duration, entryID); } /* ========== MODIFIERS ========== */ modifier onlyFeePool() { require(msg.sender == address(feePool()), "Only the FeePool can perform this action"); _; } /* ========== EVENTS ========== */ event Vested(address indexed beneficiary, uint time, uint value); event VestingEntryCreated(address indexed beneficiary, uint time, uint value, uint duration, uint entryID); event MaxEscrowDurationUpdated(uint newDuration); event MaxAccountMergingDurationUpdated(uint newDuration); event AccountMergingDurationUpdated(uint newDuration); event AccountMergingStarted(uint time, uint endTime); event AccountMerged( address indexed accountToMerge, address destinationAddress, uint escrowAmountMerged, uint[] entryIDs, uint time ); event NominateAccountToMerge(address indexed account, address destination); } // https://docs.peri.finance/contracts/source/interfaces/irewardescrow interface IRewardEscrow { // Views function balanceOf(address account) external view returns (uint); function numVestingEntries(address account) external view returns (uint); function totalEscrowedAccountBalance(address account) external view returns (uint); function totalVestedAccountBalance(address account) external view returns (uint); function getVestingScheduleEntry(address account, uint index) external view returns (uint[2] memory); function getNextVestingIndex(address account) external view returns (uint); // Mutative functions function appendVestingEntry(address account, uint quantity) external; function vest() external; } // https://docs.peri.finance/contracts/source/interfaces/isystemstatus interface ISystemStatus { struct Status { bool canSuspend; bool canResume; } struct Suspension { bool suspended; // reason is an integer code, // 0 => no reason, 1 => upgrading, 2+ => defined by system usage uint248 reason; } // Views function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume); function requireSystemActive() external view; function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireExchangeBetweenPynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function requirePynthActive(bytes32 currencyKey) external view; function requirePynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function systemSuspension() external view returns (bool suspended, uint248 reason); function issuanceSuspension() external view returns (bool suspended, uint248 reason); function exchangeSuspension() external view returns (bool suspended, uint248 reason); function pynthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function pynthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function getPynthExchangeSuspensions(bytes32[] calldata pynths) external view returns (bool[] memory exchangeSuspensions, uint256[] memory reasons); function getPynthSuspensions(bytes32[] calldata pynths) external view returns (bool[] memory suspensions, uint256[] memory reasons); // Restricted functions function suspendPynth(bytes32 currencyKey, uint256 reason) external; function updateAccessControl( bytes32 section, address account, bool canSuspend, bool canResume ) external; } // Inheritance // Internal references // https://docs.peri.finance/contracts/RewardEscrow contract RewardEscrowV2 is BaseRewardEscrowV2 { mapping(address => uint256) public totalBalancePendingMigration; uint public migrateEntriesThresholdAmount = SafeDecimalMath.unit() * 1000; // Default 1000 PERI /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_PERIFINANCE_BRIDGE_OPTIMISM = "PeriFinanceBridgeToOptimism"; bytes32 private constant CONTRACT_REWARD_ESCROW = "RewardEscrow"; bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, address _resolver) public BaseRewardEscrowV2(_owner, _resolver) {} /* ========== VIEWS ======================= */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = BaseRewardEscrowV2.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](3); newAddresses[0] = CONTRACT_PERIFINANCE_BRIDGE_OPTIMISM; newAddresses[1] = CONTRACT_REWARD_ESCROW; newAddresses[2] = CONTRACT_SYSTEMSTATUS; return combineArrays(existingAddresses, newAddresses); } function periFinanceBridgeToOptimism() internal view returns (address) { return requireAndGetAddress(CONTRACT_PERIFINANCE_BRIDGE_OPTIMISM); } function oldRewardEscrow() internal view returns (IRewardEscrow) { return IRewardEscrow(requireAndGetAddress(CONTRACT_REWARD_ESCROW)); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } /* ========== OLD ESCROW LOOKUP ========== */ uint internal constant TIME_INDEX = 0; uint internal constant QUANTITY_INDEX = 1; /* ========== MIGRATION OLD ESCROW ========== */ /* Threshold amount for migrating escrow entries from old RewardEscrow */ function setMigrateEntriesThresholdAmount(uint amount) external onlyOwner { migrateEntriesThresholdAmount = amount; emit MigrateEntriesThresholdAmountUpdated(amount); } /* Function to allow any address to migrate vesting entries from previous reward escrow */ function migrateVestingSchedule(address addressToMigrate) external systemActive { /* Ensure account escrow balance pending migration is not zero */ /* Ensure account escrowed balance is not zero - should have been migrated */ require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending"); require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0"); /* Add a vestable entry for addresses with totalBalancePendingMigration <= migrateEntriesThreshold amount of PERI */ if (totalBalancePendingMigration[addressToMigrate] <= migrateEntriesThresholdAmount) { _importVestingEntry( addressToMigrate, VestingEntries.VestingEntry({ endTime: uint64(block.timestamp), escrowAmount: totalBalancePendingMigration[addressToMigrate] }) ); /* Remove totalBalancePendingMigration[addressToMigrate] */ delete totalBalancePendingMigration[addressToMigrate]; } else { uint numEntries = oldRewardEscrow().numVestingEntries(addressToMigrate); /* iterate and migrate old escrow schedules from rewardEscrow.vestingSchedules * starting from the last entry in each staker's vestingSchedules */ for (uint i = 1; i <= numEntries; i++) { uint[2] memory vestingSchedule = oldRewardEscrow().getVestingScheduleEntry(addressToMigrate, numEntries - i); uint time = vestingSchedule[TIME_INDEX]; uint amount = vestingSchedule[QUANTITY_INDEX]; /* The list is sorted, when we reach the first entry that can be vested stop */ if (time < block.timestamp) { break; } /* import vesting entry */ _importVestingEntry( addressToMigrate, VestingEntries.VestingEntry({endTime: uint64(time), escrowAmount: amount}) ); /* subtract amount from totalBalancePendingMigration - reverts if insufficient */ totalBalancePendingMigration[addressToMigrate] = totalBalancePendingMigration[addressToMigrate].sub(amount); } } } /** * Import function for owner to import vesting schedule * All entries imported should have past their vesting timestamp and will be ready to be vested * Addresses with totalEscrowedAccountBalance == 0 will not be migrated as they have all vested */ function importVestingSchedule(address[] calldata accounts, uint256[] calldata escrowAmounts) external onlyDuringSetup onlyOwner { require(accounts.length == escrowAmounts.length, "Account and escrowAmounts Length mismatch"); for (uint i = 0; i < accounts.length; i++) { address addressToMigrate = accounts[i]; uint256 escrowAmount = escrowAmounts[i]; // ensure account have escrow migration pending require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0"); require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending"); /* Import vesting entry with endTime as block.timestamp and escrowAmount */ _importVestingEntry( addressToMigrate, VestingEntries.VestingEntry({endTime: uint64(block.timestamp), escrowAmount: escrowAmount}) ); /* update totalBalancePendingMigration - reverts if escrowAmount > remaining balance to migrate */ totalBalancePendingMigration[addressToMigrate] = totalBalancePendingMigration[addressToMigrate].sub( escrowAmount ); emit ImportedVestingSchedule(addressToMigrate, block.timestamp, escrowAmount); } } /** * Migration for owner to migrate escrowed and vested account balances * Addresses with totalEscrowedAccountBalance == 0 will not be migrated as they have all vested */ function migrateAccountEscrowBalances( address[] calldata accounts, uint256[] calldata escrowBalances, uint256[] calldata vestedBalances ) external onlyDuringSetup onlyOwner { require(accounts.length == escrowBalances.length, "Number of accounts and balances don't match"); require(accounts.length == vestedBalances.length, "Number of accounts and vestedBalances don't match"); for (uint i = 0; i < accounts.length; i++) { address account = accounts[i]; uint escrowedAmount = escrowBalances[i]; uint vestedAmount = vestedBalances[i]; // ensure account doesn't have escrow migration pending / being imported more than once require(totalBalancePendingMigration[account] == 0, "Account migration is pending already"); /* Update totalEscrowedBalance for tracking the PeriFinance balance of this contract. */ totalEscrowedBalance = totalEscrowedBalance.add(escrowedAmount); /* Update totalEscrowedAccountBalance and totalVestedAccountBalance for each account */ totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(escrowedAmount); totalVestedAccountBalance[account] = totalVestedAccountBalance[account].add(vestedAmount); /* update totalBalancePendingMigration for account */ totalBalancePendingMigration[account] = escrowedAmount; emit MigratedAccountEscrow(account, escrowedAmount, vestedAmount, now); } } /* Internal function to add entry to vestingSchedules and emit event */ function _importVestingEntry(address account, VestingEntries.VestingEntry memory entry) internal { /* add vesting entry to account and assign an entryID to it */ uint entryID = BaseRewardEscrowV2._addVestingEntry(account, entry); emit ImportedVestingEntry(account, entryID, entry.escrowAmount, entry.endTime); } /* ========== L2 MIGRATION ========== */ function burnForMigration(address account, uint[] calldata entryIDs) external onlyPeriFinanceBridge returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries) { require(entryIDs.length > 0, "Entry IDs required"); vestingEntries = new VestingEntries.VestingEntry[](entryIDs.length); for (uint i = 0; i < entryIDs.length; i++) { VestingEntries.VestingEntry storage entry = vestingSchedules[account][entryIDs[i]]; if (entry.escrowAmount > 0) { vestingEntries[i] = entry; /* add the escrow amount to escrowedAccountBalance */ escrowedAccountBalance = escrowedAccountBalance.add(entry.escrowAmount); /* Delete the vesting entry being migrated */ delete vestingSchedules[account][entryIDs[i]]; } } /** * update account total escrow balances for migration * transfer the escrowed PERI being migrated to the L2 deposit contract */ if (escrowedAccountBalance > 0) { _reduceAccountEscrowBalances(account, escrowedAccountBalance); IERC20(address(periFinance())).transfer(periFinanceBridgeToOptimism(), escrowedAccountBalance); } emit BurnedForMigrationToL2(account, entryIDs, escrowedAccountBalance, block.timestamp); return (escrowedAccountBalance, vestingEntries); } /* ========== MODIFIERS ========== */ modifier onlyPeriFinanceBridge() { require(msg.sender == periFinanceBridgeToOptimism(), "Can only be invoked by PeriFinanceBridgeToOptimism contract"); _; } modifier systemActive() { systemStatus().requireSystemActive(); _; } /* ========== EVENTS ========== */ event MigratedAccountEscrow(address indexed account, uint escrowedAmount, uint vestedAmount, uint time); event ImportedVestingSchedule(address indexed account, uint time, uint escrowAmount); event BurnedForMigrationToL2(address indexed account, uint[] entryIDs, uint escrowedAmountMigrated, uint time); event ImportedVestingEntry(address indexed account, uint entryID, uint escrowAmount, uint endTime); event MigrateEntriesThresholdAmountUpdated(uint newAmount); }
https:docs.peri.finance/contracts/source/interfaces/ifeepool Views solhint-disable-next-line func-name-mixedcase Mutative Functions Restricted: used internally to PeriFinance
interface IFeePool { function FEE_ADDRESS() external view returns (address); function feesAvailable(address account) external view returns (uint, uint); function feePeriodDuration() external view returns (uint); function isFeesClaimable(address account) external view returns (bool); function targetThreshold() external view returns (uint); function totalFeesAvailable() external view returns (uint); function totalRewardsAvailable() external view returns (uint); function claimFees() external returns (bool); function claimOnBehalf(address claimingForAddress) external returns (bool); function closeCurrentFeePeriod() external; function appendAccountIssuanceRecord( address account, uint lockedAmount, uint debtEntryIndex, bytes32 currencyKey ) external; function recordFeePaid(uint pUSDAmount) external; function setRewardsToDistribute(uint amount) external; }
2,308,076
./partial_match/1/0x34A542aCD8A717B5933228Ae3C554B1328F36e14/sources/ERC20ByMetadrop.sol
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; }
2,631,284
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // 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) + 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 // 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.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; } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IAddressList { function add(address a) external returns (bool); function remove(address a) external returns (bool); function get(address a) external view returns (uint256); function contains(address a) external view returns (bool); function length() external view returns (uint256); function grantRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IAddressListFactory { function ours(address a) external view returns (bool); function listCount() external view returns (uint256); function listAt(uint256 idx) external view returns (address); function createList() external returns (address listaddr); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /* solhint-disable func-name-mixedcase */ import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; interface ISwapManager { event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period); function N_DEX() external view returns (uint256); function ROUTERS(uint256 i) external view returns (IUniswapV2Router02); function bestOutputFixedInput( address _from, address _to, uint256 _amountIn ) external view returns ( address[] memory path, uint256 amountOut, uint256 rIdx ); function bestPathFixedInput( address _from, address _to, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function bestInputFixedOutput( address _from, address _to, uint256 _amountOut ) external view returns ( address[] memory path, uint256 amountIn, uint256 rIdx ); function bestPathFixedOutput( address _from, address _to, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function safeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function safeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function comparePathsFixedInput( address[] memory pathA, address[] memory pathB, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function comparePathsFixedOutput( address[] memory pathA, address[] memory pathB, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function ours(address a) external view returns (bool); function oracleCount() external view returns (uint256); function oracleAt(uint256 idx) external view returns (address); function getOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external view returns (address); function createOrUpdateOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external returns (address oracleAddr); function consultForFree( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external view returns (uint256 amountOut, uint256 lastUpdatedAt); /// get the data we want and pay the gas to update function consult( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external returns ( uint256 amountOut, uint256 lastUpdatedAt, bool updated ); function updateOracles() external returns (uint256 updated, uint256 expected); function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface ICollateralManager { function addGemJoin(address[] calldata _gemJoins) external; function borrow(uint256 _amount) external; function createVault(bytes32 _collateralType) external returns (uint256 _vaultNum); function depositCollateral(uint256 _amount) external; function payback(uint256 _amount) external; function transferVaultOwnership(address _newOwner) external; function withdrawCollateral(uint256 _amount) external; function getVaultBalance(address _vaultOwner) external view returns (uint256 collateralLocked); function getVaultDebt(address _vaultOwner) external view returns (uint256 daiDebt); function getVaultInfo(address _vaultOwner) external view returns ( uint256 collateralLocked, uint256 daiDebt, uint256 collateralUsdRate, uint256 collateralRatio, uint256 minimumDebt ); function mcdManager() external view returns (address); function vaultNum(address _vaultOwner) external view returns (uint256 _vaultNum); function whatWouldWithdrawDo(address _vaultOwner, uint256 _amount) external view returns ( uint256 collateralLocked, uint256 daiDebt, uint256 collateralUsdRate, uint256 collateralRatio, uint256 minimumDebt ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IPoolRewards { /// Emitted after reward added event RewardAdded(address indexed rewardToken, uint256 reward, uint256 rewardDuration); /// Emitted whenever any user claim rewards event RewardPaid(address indexed user, address indexed rewardToken, uint256 reward); /// Emitted after adding new rewards token into rewardTokens array event RewardTokenAdded(address indexed rewardToken, address[] existingRewardTokens); function claimReward(address) external; function notifyRewardAmount( address _rewardToken, uint256 _rewardAmount, uint256 _rewardDuration ) external; function notifyRewardAmount( address[] memory _rewardTokens, uint256[] memory _rewardAmounts, uint256[] memory _rewardDurations ) external; function updateReward(address) external; function claimable(address _account) external view returns (address[] memory _rewardTokens, uint256[] memory _claimableAmounts); function lastTimeRewardApplicable(address _rewardToken) external view returns (uint256); function rewardForDuration() external view returns (address[] memory _rewardTokens, uint256[] memory _rewardForDuration); function rewardPerToken() external view returns (address[] memory _rewardTokens, uint256[] memory _rewardPerTokenRate); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function totalValueCurrent() external returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../bloq/IAddressList.sol"; interface IVesperPool is IERC20 { function deposit() external payable; function deposit(uint256 _share) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function poolRewards() external returns (address); function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function reportLoss(uint256 _loss) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function governor() external view returns (address); function keepers() external view returns (IAddressList); function maintainers() external view returns (IAddressList); function feeCollector() external view returns (address); function pricePerShare() external view returns (uint256); function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio ); function stopEverything() external view returns (bool); function token() external view returns (IERC20); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); function withdrawFee() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "../interfaces/bloq/ISwapManager.sol"; import "../interfaces/bloq/IAddressList.sol"; import "../interfaces/bloq/IAddressListFactory.sol"; import "../interfaces/vesper/IStrategy.sol"; import "../interfaces/vesper/IVesperPool.sol"; abstract contract Strategy is IStrategy, Context { using SafeERC20 for IERC20; IERC20 public immutable collateralToken; address public receiptToken; address public immutable override pool; IAddressList public keepers; address public override feeCollector; ISwapManager public swapManager; uint256 public oraclePeriod = 3600; // 1h uint256 public oracleRouterIdx = 0; // Uniswap V2 uint256 public swapSlippage = 10000; // 100% Don't use oracles by default address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 internal constant MAX_UINT_VALUE = type(uint256).max; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager); event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage); event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx); constructor( address _pool, address _swapManager, address _receiptToken ) { require(_pool != address(0), "pool-address-is-zero"); require(_swapManager != address(0), "sm-address-is-zero"); swapManager = ISwapManager(_swapManager); pool = _pool; collateralToken = IVesperPool(_pool).token(); receiptToken = _receiptToken; } modifier onlyGovernor { require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor"); _; } modifier onlyKeeper() { require(keepers.contains(_msgSender()), "caller-is-not-a-keeper"); _; } modifier onlyPool() { require(_msgSender() == pool, "caller-is-not-vesper-pool"); _; } /** * @notice Add given address in keepers list. * @param _keeperAddress keeper address to add. */ function addKeeper(address _keeperAddress) external onlyGovernor { require(keepers.add(_keeperAddress), "add-keeper-failed"); } /** * @notice Create keeper list * NOTE: Any function with onlyKeeper modifier will not work until this function is called. * NOTE: Due to gas constraint this function cannot be called in constructor. * @param _addressListFactory To support same code in eth side chain, user _addressListFactory as param * ethereum- 0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3 * polygon-0xD10D5696A350D65A9AA15FE8B258caB4ab1bF291 */ function init(address _addressListFactory) external onlyGovernor { require(address(keepers) == address(0), "keeper-list-already-created"); // Prepare keeper list IAddressListFactory _factory = IAddressListFactory(_addressListFactory); keepers = IAddressList(_factory.createList()); require(keepers.add(_msgSender()), "add-keeper-failed"); } /** * @notice Migrate all asset and vault ownership,if any, to new strategy * @dev _beforeMigration hook can be implemented in child strategy to do extra steps. * @param _newStrategy Address of new strategy */ function migrate(address _newStrategy) external virtual override onlyPool { require(_newStrategy != address(0), "new-strategy-address-is-zero"); require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy"); _beforeMigration(_newStrategy); IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this))); collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this))); } /** * @notice Remove given address from keepers list. * @param _keeperAddress keeper address to remove. */ function removeKeeper(address _keeperAddress) external onlyGovernor { require(keepers.remove(_keeperAddress), "remove-keeper-failed"); } /** * @notice Update fee collector * @param _feeCollector fee collector address */ function updateFeeCollector(address _feeCollector) external onlyGovernor { require(_feeCollector != address(0), "fee-collector-address-is-zero"); require(_feeCollector != feeCollector, "fee-collector-is-same"); emit UpdatedFeeCollector(feeCollector, _feeCollector); feeCollector = _feeCollector; } /** * @notice Update swap manager address * @param _swapManager swap manager address */ function updateSwapManager(address _swapManager) external onlyGovernor { require(_swapManager != address(0), "sm-address-is-zero"); require(_swapManager != address(swapManager), "sm-is-same"); emit UpdatedSwapManager(address(swapManager), _swapManager); swapManager = ISwapManager(_swapManager); } function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor { require(_newSwapSlippage <= 10000, "invalid-slippage-value"); emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage); swapSlippage = _newSwapSlippage; } function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor { require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index"); if (_newPeriod == 0) _newPeriod = oraclePeriod; require(_newPeriod > 59, "invalid-oracle-period"); emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx); oraclePeriod = _newPeriod; oracleRouterIdx = _newRouterIdx; } /// @dev Approve all required tokens function approveToken() external onlyKeeper { _approveToken(0); _approveToken(MAX_UINT_VALUE); } function setupOracles() external onlyKeeper { _setupOracles(); } /** * @dev Withdraw collateral token from lending pool. * @param _amount Amount of collateral token */ function withdraw(uint256 _amount) external override onlyPool { _withdraw(_amount); } /** * @dev Rebalance profit, loss and investment of this strategy */ function rebalance() external virtual override onlyKeeper { (uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport(); IVesperPool(pool).reportEarning(_profit, _loss, _payback); _reinvest(); } /** * @dev sweep given token to feeCollector of strategy * @param _fromToken token address to sweep */ function sweepERC20(address _fromToken) external override onlyKeeper { require(feeCollector != address(0), "fee-collector-not-set"); require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral"); require(!isReservedToken(_fromToken), "not-allowed-to-sweep"); if (_fromToken == ETH) { Address.sendValue(payable(feeCollector), address(this).balance); } else { uint256 _amount = IERC20(_fromToken).balanceOf(address(this)); IERC20(_fromToken).safeTransfer(feeCollector, _amount); } } /// @notice Returns address of token correspond to collateral token function token() external view override returns (address) { return receiptToken; } /// @dev Convert from 18 decimals to token defined decimals. Default no conversion. function convertFrom18(uint256 amount) public pure virtual returns (uint256) { return amount; } /** * @notice Calculate total value of asset under management * @dev Report total value in collateral token */ function totalValue() public view virtual override returns (uint256 _value); /** * @notice Calculate total value of asset under management (in real-time) * @dev Report total value in collateral token */ function totalValueCurrent() external virtual override returns (uint256) { return totalValue(); } /// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function isReservedToken(address _token) public view virtual override returns (bool); /** * @notice some strategy may want to prepare before doing migration. Example In Maker old strategy want to give vault ownership to new strategy * @param _newStrategy . */ function _beforeMigration(address _newStrategy) internal virtual; /** * @notice Generate report for current profit and loss. Also liquidate asset to payback * excess debt, if any. * @return _profit Calculate any realized profit and convert it to collateral, if not already. * @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token. * @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt. */ function _generateReport() internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _payback ) { uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this)); uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this)); _profit = _realizeProfit(_totalDebt); _loss = _realizeLoss(_totalDebt); _payback = _liquidate(_excessDebt); } function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) { return (_amount * (10000 - _slippage)) / (10000); } function _simpleOraclePath(address _from, address _to) internal pure returns (address[] memory path) { if (_from == WETH || _to == WETH) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; } } function _consultOracle( address _from, address _to, uint256 _amt ) internal returns (uint256, bool) { // from, to, amountIn, period, router (uint256 rate, uint256 lastUpdate, ) = swapManager.consult(_from, _to, _amt, oraclePeriod, oracleRouterIdx); // We're looking at a TWAP ORACLE with a 1 hr Period that has been updated within the last hour if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true); return (0, false); } function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) { require(path.length > 1, "invalid-oracle-path"); amountOut = _amountIn; bool isValid; for (uint256 i = 0; i < path.length - 1; i++) { (amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut); require(isValid, "invalid-oracle-rate"); } } /** * @notice Safe swap via Uniswap / Sushiswap (better rate of the two) * @dev There are many scenarios when token swap via Uniswap can fail, so this * method will wrap Uniswap call in a 'try catch' to make it fail safe. * however, this method will throw minAmountOut is not met * @param _from address of from token * @param _to address of to token * @param _amountIn Amount to be swapped * @param _minAmountOut minimum amount out */ function _safeSwap( address _from, address _to, uint256 _amountIn, uint256 _minAmountOut ) internal { (address[] memory path, uint256 amountOut, uint256 rIdx) = swapManager.bestOutputFixedInput(_from, _to, _amountIn); if (_minAmountOut == 0) _minAmountOut = 1; if (amountOut != 0) { swapManager.ROUTERS(rIdx).swapExactTokensForTokens( _amountIn, _minAmountOut, path, address(this), block.timestamp ); } } // These methods can be implemented by the inheriting strategy. /* solhint-disable no-empty-blocks */ function _claimRewardsAndConvertTo(address _toToken) internal virtual {} /** * @notice Set up any oracles that are needed for this strategy. */ function _setupOracles() internal virtual {} /* solhint-enable */ // These methods must be implemented by the inheriting strategy function _withdraw(uint256 _amount) internal virtual; function _approveToken(uint256 _amount) internal virtual; /** * @notice Withdraw collateral to payback excess debt in pool. * @param _excessDebt Excess debt of strategy in collateral token * @return _payback amount in collateral token. Usually it is equal to excess debt. */ function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback); /** * @notice Calculate earning and withdraw/convert it into collateral token. * @param _totalDebt Total collateral debt of this strategy * @return _profit Profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit); /** * @notice Calculate loss * @param _totalDebt Total collateral debt of this strategy * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss); /** * @notice Reinvest collateral. * @dev Once we file report back in pool, we might have some collateral in hand * which we want to reinvest aka deposit in lender/provider. */ function _reinvest() internal virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "../Strategy.sol"; import "../../interfaces/vesper/ICollateralManager.sol"; /// @dev This strategy will deposit collateral token in Maker, borrow Dai and /// deposit borrowed DAI in other lending pool to earn interest. abstract contract MakerStrategy is Strategy { using SafeERC20 for IERC20; address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ICollateralManager public immutable cm; bytes32 public immutable collateralType; uint256 public highWater; uint256 public lowWater; uint256 private constant WAT = 10**16; constructor( address _pool, address _cm, address _swapManager, address _receiptToken, bytes32 _collateralType ) Strategy(_pool, _swapManager, _receiptToken) { require(_cm != address(0), "cm-address-is-zero"); collateralType = _collateralType; cm = ICollateralManager(_cm); } /// @notice Create new Maker vault function createVault() external onlyGovernor { cm.createVault(collateralType); } /** * @dev If pool is underwater this function will resolve underwater condition. * If Debt in Maker is greater than Dai balance in lender then pool is underwater. * Lowering DAI debt in Maker will resolve underwater condition. * Resolve: Calculate required collateral token to lower DAI debt. Withdraw required * collateral token from Maker and convert those to DAI via Uniswap. * Finally payback debt in Maker using DAI. * @dev Also report loss in pool. */ function resurface() external onlyKeeper { _resurface(); } /** * @notice Update balancing factors aka high water and low water values. * Water mark values represent Collateral Ratio in Maker. For example 300 as high water * means 300% collateral ratio. * @param _highWater Value for high water mark. * @param _lowWater Value for low water mark. */ function updateBalancingFactor(uint256 _highWater, uint256 _lowWater) external onlyGovernor { require(_lowWater != 0, "lowWater-is-zero"); require(_highWater > _lowWater, "highWater-less-than-lowWater"); highWater = _highWater * WAT; lowWater = _lowWater * WAT; } /** * @notice Report total value of this strategy * @dev Make sure to return value in collateral token and in order to do that * we are using Uniswap to get collateral amount for earned DAI. */ function totalValue() public view virtual override returns (uint256 _totalValue) { uint256 _daiBalance = _getDaiBalance(); uint256 _debt = cm.getVaultDebt(address(this)); if (_daiBalance > _debt) { uint256 _daiEarned = _daiBalance - _debt; (, _totalValue) = swapManager.bestPathFixedInput(DAI, address(collateralToken), _daiEarned, 0); } _totalValue += convertFrom18(cm.getVaultBalance(address(this))); } function vaultNum() external view returns (uint256) { return cm.vaultNum(address(this)); } /// @dev Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function isReservedToken(address _token) public view virtual override returns (bool) { return _token == receiptToken; } /** * @notice Returns true if pool is underwater. * @notice Underwater - If debt is greater than earning of pool. * @notice Earning - Sum of DAI balance and DAI from accrued reward, if any, in lending pool. */ function isUnderwater() public view virtual returns (bool) { return cm.getVaultDebt(address(this)) > _getDaiBalance(); } /** * @notice Before migration hook. It will be called during migration * @dev Transfer Maker vault ownership to new strategy * @param _newStrategy Address of new strategy. */ function _beforeMigration(address _newStrategy) internal virtual override { cm.transferVaultOwnership(_newStrategy); } function _approveToken(uint256 _amount) internal virtual override { IERC20(DAI).safeApprove(address(cm), _amount); collateralToken.safeApprove(address(cm), _amount); collateralToken.safeApprove(pool, _amount); for (uint256 i = 0; i < swapManager.N_DEX(); i++) { collateralToken.safeApprove(address(swapManager.ROUTERS(i)), _amount); IERC20(DAI).safeApprove(address(swapManager.ROUTERS(i)), _amount); } } function _moveDaiToMaker(uint256 _amount) internal { if (_amount != 0) { _withdrawDaiFromLender(_amount); cm.payback(_amount); } } function _moveDaiFromMaker(uint256 _amount) internal virtual { cm.borrow(_amount); _amount = IERC20(DAI).balanceOf(address(this)); _depositDaiToLender(_amount); } /** * @notice Withdraw collateral to payback excess debt in pool. * @param _excessDebt Excess debt of strategy in collateral token * @return payback amount in collateral token. Usually it is equal to excess debt. */ function _liquidate(uint256 _excessDebt) internal virtual override returns (uint256) { _withdrawHere(_excessDebt); return _excessDebt; } /** * @notice Calculate earning and convert it to collateral token * @dev Also claim rewards if available. * Withdraw excess DAI from lender. * Swap net earned DAI to collateral token * @return profit in collateral token */ function _realizeProfit( uint256 /*_totalDebt*/ ) internal virtual override returns (uint256) { _claimRewardsAndConvertTo(DAI); _rebalanceDaiInLender(); uint256 _daiBalance = IERC20(DAI).balanceOf(address(this)); if (_daiBalance != 0) { _safeSwap(DAI, address(collateralToken), _daiBalance, 1); } return collateralToken.balanceOf(address(this)); } /** * @notice Calculate collateral loss from resurface, if any * @dev Difference of total debt of strategy in pool and collateral locked * in Maker vault is the loss. * @return loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal virtual override returns (uint256) { uint256 _collateralLocked = convertFrom18(cm.getVaultBalance(address(this))); return _totalDebt > _collateralLocked ? _totalDebt - _collateralLocked : 0; } /** * @notice Deposit collateral in Maker and rebalance collateral and debt in Maker. * @dev Based on defined risk parameter either borrow more DAI from Maker or * payback some DAI in Maker. It will try to mitigate risk of liquidation. */ function _reinvest() internal virtual override { uint256 _collateralBalance = collateralToken.balanceOf(address(this)); if (_collateralBalance != 0) { cm.depositCollateral(_collateralBalance); } ( uint256 _collateralLocked, uint256 _currentDebt, uint256 _collateralUsdRate, uint256 _collateralRatio, uint256 _minimumAllowedDebt ) = cm.getVaultInfo(address(this)); uint256 _maxDebt = (_collateralLocked * _collateralUsdRate) / highWater; if (_maxDebt < _minimumAllowedDebt) { // Dusting Scenario:: Based on collateral locked, if our max debt is less // than Maker defined minimum debt then payback whole debt and wind up. _moveDaiToMaker(_currentDebt); } else { if (_collateralRatio > highWater) { require(!isUnderwater(), "pool-is-underwater"); // Safe to borrow more DAI _moveDaiFromMaker(_maxDebt - _currentDebt); } else if (_collateralRatio < lowWater) { // Being below low water brings risk of liquidation in Maker. // Withdraw DAI from Lender and deposit in Maker _moveDaiToMaker(_currentDebt - _maxDebt); } } } function _resurface() internal virtual { require(isUnderwater(), "pool-is-above-water"); uint256 _daiNeeded = cm.getVaultDebt(address(this)) - _getDaiBalance(); (address[] memory _path, uint256 _collateralNeeded, uint256 rIdx) = swapManager.bestInputFixedOutput(address(collateralToken), DAI, _daiNeeded); if (_collateralNeeded != 0) { cm.withdrawCollateral(_collateralNeeded); swapManager.ROUTERS(rIdx).swapExactTokensForTokens( _collateralNeeded, 1, _path, address(this), block.timestamp ); cm.payback(IERC20(DAI).balanceOf(address(this))); IVesperPool(pool).reportLoss(_collateralNeeded); } } function _withdraw(uint256 _amount) internal override { _withdrawHere(_amount); collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this))); } // TODO do we need a safe withdraw function _withdrawHere(uint256 _amount) internal { ( uint256 collateralLocked, uint256 debt, uint256 collateralUsdRate, uint256 collateralRatio, uint256 minimumDebt ) = cm.whatWouldWithdrawDo(address(this), _amount); if (debt != 0 && collateralRatio < lowWater) { // If this withdraw results in Low Water scenario. uint256 maxDebt = (collateralLocked * collateralUsdRate) / highWater; if (maxDebt < minimumDebt) { // This is Dusting scenario _moveDaiToMaker(debt); } else if (maxDebt < debt) { _moveDaiToMaker(debt - maxDebt); } } cm.withdrawCollateral(_amount); } function _depositDaiToLender(uint256 _amount) internal virtual; function _rebalanceDaiInLender() internal virtual; function _withdrawDaiFromLender(uint256 _amount) internal virtual; function _getDaiBalance() internal view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./MakerStrategy.sol"; import "../../interfaces/vesper/IPoolRewards.sol"; /// @dev This strategy will deposit collateral token in Maker, borrow Dai and /// deposit borrowed DAI in Vesper DAI pool to earn interest. //solhint-disable no-empty-blocks abstract contract VesperMakerStrategy is MakerStrategy { using SafeERC20 for IERC20; address internal constant VSP = 0x1b40183EFB4Dd766f11bDa7A7c3AD8982e998421; constructor( address _pool, address _cm, address _swapManager, address _vPool, bytes32 _collateralType ) MakerStrategy(_pool, _cm, _swapManager, _vPool, _collateralType) { require(address(IVesperPool(_vPool).token()) == DAI, "not-a-valid-dai-pool"); } function _approveToken(uint256 _amount) internal override { super._approveToken(_amount); IERC20(DAI).safeApprove(address(receiptToken), _amount); for (uint256 i = 0; i < swapManager.N_DEX(); i++) { IERC20(VSP).safeApprove(address(swapManager.ROUTERS(i)), _amount); } } function _getDaiBalance() internal view override returns (uint256) { return (IVesperPool(receiptToken).pricePerShare() * IVesperPool(receiptToken).balanceOf(address(this))) / 1e18; } function _depositDaiToLender(uint256 _amount) internal override { IVesperPool(receiptToken).deposit(_amount); } function _withdrawDaiFromLender(uint256 _amount) internal override { uint256 _vAmount = (_amount * 1e18) / IVesperPool(receiptToken).pricePerShare(); IVesperPool(receiptToken).whitelistedWithdraw(_vAmount); } function _rebalanceDaiInLender() internal virtual override { uint256 _daiDebt = cm.getVaultDebt(address(this)); uint256 _daiBalance = _getDaiBalance(); if (_daiBalance > _daiDebt) { _withdrawDaiFromLender(_daiBalance - _daiDebt); } } /// @notice Claim rewardToken from lender and convert it into DAI function _claimRewardsAndConvertTo(address _toToken) internal virtual override { uint256 _vspAmount = IERC20(VSP).balanceOf(address(this)); if (_vspAmount > 0) { _safeSwap(VSP, _toToken, _vspAmount, 1); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./VesperMakerStrategy.sol"; //solhint-disable no-empty-blocks contract VesperMakerStrategyETH is VesperMakerStrategy { string public constant NAME = "Vesper-Maker-Strategy-ETH"; string public constant VERSION = "3.0.15"; constructor( address _pool, address _cm, address _swapManager, address _vPool ) VesperMakerStrategy(_pool, _cm, _swapManager, _vPool, "ETH-C") {} }
Deposit collateral in Maker and rebalance collateral and debt in Maker. Based on defined risk parameter either borrow more DAI from Maker or payback some DAI in Maker. It will try to mitigate risk of liquidation./ Dusting Scenario:: Based on collateral locked, if our max debt is less than Maker defined minimum debt then payback whole debt and wind up. Safe to borrow more DAI Being below low water brings risk of liquidation in Maker. Withdraw DAI from Lender and deposit in Maker
function _reinvest() internal virtual override { uint256 _collateralBalance = collateralToken.balanceOf(address(this)); if (_collateralBalance != 0) { cm.depositCollateral(_collateralBalance); } ( uint256 _collateralLocked, uint256 _currentDebt, uint256 _collateralUsdRate, uint256 _collateralRatio, uint256 _minimumAllowedDebt ) = cm.getVaultInfo(address(this)); uint256 _maxDebt = (_collateralLocked * _collateralUsdRate) / highWater; if (_maxDebt < _minimumAllowedDebt) { _moveDaiToMaker(_currentDebt); if (_collateralRatio > highWater) { require(!isUnderwater(), "pool-is-underwater"); _moveDaiFromMaker(_maxDebt - _currentDebt); _moveDaiToMaker(_currentDebt - _maxDebt); } } }
178,531
./partial_match/1/0xa202D5B0892f2981bA86C981884cebA49B8AE096/sources/DigitalaxGenesisStaking.sol
All the unstaking goes through this function Rewards to be given out is calculated Balance of stakers are updated as they unstake the nfts based on ether price/
function _unstake( address _user, uint256 _tokenId ) internal { Staker storage staker = stakers[_user]; uint256 amount = getGenesisContribution(_tokenId); staker.balance = staker.balance.sub(amount); stakedEthTotal = stakedEthTotal.sub(amount); uint256 lastIndex = staker.tokenIds.length - 1; uint256 lastIndexKey = staker.tokenIds[lastIndex]; staker.tokenIds[staker.tokenIndex[_tokenId]] = lastIndexKey; if (staker.tokenIds.length > 0) { staker.tokenIds.pop(); delete staker.tokenIndex[_tokenId]; } if (staker.balance == 0) { delete stakers[_user]; } delete tokenOwner[_tokenId]; genesisNFT.safeTransferFrom( address(this), _user, _tokenId ); emit Unstaked(_user, _tokenId); }
2,671,397
/** *Submitted for verification at Etherscan.io on 2021-04-17 */ pragma solidity ^0.5.0; /** * @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){ if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b,"Calculation error"); 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,"Calculation error"); 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,"Calculation error"); 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,"Calculation error"); 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,"Calculation error"); return a % b; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; } /** * @title Layerx Contract For ERC20 Tokens * @dev LAYERX tokens as per ERC20 Standards */ contract Layerx is IERC20, Owned { using SafeMath for uint256; string public symbol; string public name; uint8 public decimals; uint _totalSupply; uint public totalEthRewards = 0; uint stakeNum = 0; uint amtByDay = 27397260274000000000; uint public stakePeriod = 30 days; address public stakeCreator; bool isPaused = false; struct Stake { uint start; uint end; uint layerLockedTotal; uint layerxReward; uint ethReward; } struct StakeHolder { uint layerLocked; uint firstStake; uint time; } struct Rewards { uint layerLocked; uint layersx; uint eth; bool isReceived; } event logLockedTokens(address holder, uint amountLocked, uint timeLocked, uint stakeId); event logUnlockedTokens(address holder, uint amountUnlocked, uint timeUnlocked); event logWithdraw(address holder, uint layerx, uint eth, uint stakeId, uint time); event logCloseStake(uint id, uint amount, uint timeClosed); modifier paused { require(isPaused == false, "This contract was paused by the owner!"); _; } modifier exist (uint index) { require(index <= stakeNum, 'This stake does not exist.'); _; } mapping (address => StakeHolder) public stakeHolders; mapping (uint => Stake) public stakes; mapping (address => mapping (uint => Rewards)) public rewards; mapping (address => uint) balances; mapping (address => mapping(address => uint)) allowed; mapping (address => bool) private swap; IERC20 UNILAYER = IERC20(0x0fF6ffcFDa92c53F615a4A75D982f399C989366b); constructor(address _owner) public { owner = _owner; stakeCreator = owner; symbol = "LAYERX"; name = "UNILAYERX"; decimals = 18; _totalSupply = 40000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); stakes[0] = Stake(now, 0, 0, 0, 0); } /** * @dev Total number of tokens in existence. */ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } /** * @dev Gets the balance of the specified address. * @param tokenOwner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } 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; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } 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; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } 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; } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public onlyOwner { require(value > 0, "Invalid Amount."); require(_totalSupply >= value, "Invalid account state."); require(balances[owner] >= value, "Invalid account balances state."); _totalSupply = _totalSupply.sub(value); balances[owner] = balances[owner].sub(value); emit Transfer(owner, address(0), value); } /** * @dev Set new Stake Creator address. * @param _stakeCreator The address of the new Stake Creator. */ function setNewStakeCreator(address _stakeCreator) external onlyOwner { require(_stakeCreator != address(0), 'Do not use 0 address'); stakeCreator = _stakeCreator; } /** * @dev Set new pause status. * @param newIsPaused The pause status: 0 - not paused, 1 - paused. */ function setIsPaused(bool newIsPaused) external onlyOwner { isPaused = newIsPaused; } /** * @dev Set new Stake Period. * @param newStakePeriod indicates new stake period, it was 7 days by default. */ function setStakePeriod(uint256 newStakePeriod) external onlyOwner { stakePeriod = newStakePeriod; } /** * @dev Stake LAYER tokens for earning rewards, Tokens will be deducted from message sender account * @param payment Amount of LAYER to be staked in the pool */ function lock(uint payment) external paused { require(payment > 0, 'Payment must be greater than 0.'); require(UNILAYER.balanceOf(msg.sender) >= payment, 'Holder does not have enough tokens.'); require(UNILAYER.allowance(msg.sender, address(this)) >= payment, 'Call Approve function firstly.'); UNILAYER.transferFrom(msg.sender, address(this), payment); StakeHolder memory holder = stakeHolders[msg.sender]; Stake memory stake = stakes[stakeNum]; if(holder.layerLocked == 0) { holder.firstStake = stakeNum; holder.time = now; } else if(holder.layerLocked > 0 && stakeNum > holder.firstStake) { Rewards memory rwds = rewards[msg.sender][stakeNum-1]; require(rwds.isReceived == true,'Withdraw your rewards.'); } holder.layerLocked = holder.layerLocked.add(payment); stakeHolders[msg.sender] = holder; stake.layerLockedTotal = stake.layerLockedTotal.add(payment); stakes[stakeNum] = stake; emit logLockedTokens(msg.sender, payment, now, stakeNum); } /** * @dev Withdraw My Staked Tokens from staker pool */ function unlock() external paused { StakeHolder memory holder = stakeHolders[msg.sender]; uint amt = holder.layerLocked; require(amt > 0, 'You do not have locked tokens.'); require(UNILAYER.balanceOf(address(this)) >= amt, 'Insufficient account balance!'); if(holder.layerLocked > 0 && stakeNum > 0) { Rewards memory rwds = rewards[msg.sender][stakeNum-1]; require(rwds.isReceived == true,'Withdraw your rewards.'); } Stake memory stake = stakes[stakeNum]; stake.layerLockedTotal = stake.layerLockedTotal.sub(holder.layerLocked); stakes[stakeNum] = stake; delete stakeHolders[msg.sender]; UNILAYER.transfer(msg.sender, amt); emit logUnlockedTokens(msg.sender, amt, now); } /** * @dev Stake Creator finalizes the stake, the stake receives the accumulated ETH as reward and calculates everyone's percentages. */ function closeStake() external { require(msg.sender == stakeCreator, 'You cannot call this function'); Stake memory stake = stakes[stakeNum]; require(now >= stake.start.add(stakePeriod), 'You cannot call this function until stakePeriod is over'); stake.end = now; stake.ethReward = stake.ethReward.add(totalEthRewards); uint amtLayerx = stake.end.sub(stake.start).mul(amtByDay).div(1 days); if(amtLayerx > balances[owner]) { amtLayerx = balances[owner]; } stake.layerxReward = amtLayerx; stakes[stakeNum] = stake; emit logCloseStake(stakeNum, totalEthRewards, now); stakeNum++; stakes[stakeNum] = Stake(now, 0, stake.layerLockedTotal, 0, 0); totalEthRewards = 0; } /** * @dev Withdraw Reward Layerx Tokens and ETH * @param index Stake index */ function withdraw(uint index) external paused exist(index) { Rewards memory rwds = rewards[msg.sender][index]; Stake memory stake = stakes[index]; StakeHolder memory holder = stakeHolders[msg.sender]; uint endTime = holder.time + stakePeriod; require(endTime <= now, 'Wait the minimum time'); require(stake.end <= now, 'Invalid date for withdrawal.'); require(rwds.isReceived == false, 'You already withdrawal your rewards.'); require(balances[owner] >= rwds.layersx, 'Insufficient account balance!'); require(address(this).balance >= rwds.eth,'Invalid account state, not enough funds.'); require(index >= holder.firstStake, 'Invalid index.'); if(holder.firstStake != index) { Rewards memory rwdsOld = rewards[msg.sender][index-1]; require(rwdsOld.isReceived == true,'Withdraw your old rewards first.'); } rwds.isReceived = true; rwds.layerLocked = holder.layerLocked; if(rwds.layerLocked > 0) { rwds.layersx = rwds.layerLocked.mul(stake.layerxReward).div(stake.layerLockedTotal); rwds.eth = rwds.layerLocked.mul(stake.ethReward).div(stake.layerLockedTotal); } rewards[msg.sender][index] = rwds; emit logWithdraw(msg.sender, rwds.layersx, rwds.eth, index, now); if(rwds.layersx > 0) { balances[owner] = balances[owner].sub(rwds.layersx); balances[msg.sender] = balances[msg.sender].add(rwds.layersx); emit Transfer(owner, msg.sender, rwds.layersx); } if(rwds.eth > 0) { msg.sender.transfer(rwds.eth); } } /** * @dev Function to get the number of stakes * @return number of stakes */ function getStakesNum() external view returns (uint) { return stakeNum; } function stakeOf(address tokenOwner) public view returns (uint balance) { StakeHolder memory holder = stakeHolders[tokenOwner]; return holder.layerLocked; } /** * @dev Receive ETH and add value to the accumulated eth for stake */ function() external payable { totalEthRewards = totalEthRewards.add(msg.value); } function destroyContract() external onlyOwner { selfdestruct(msg.sender); } }
Receive ETH and add value to the accumulated eth for stake/
function() external payable { totalEthRewards = totalEthRewards.add(msg.value); }
1,691,471
pragma solidity 0.5.4; library safemath3 { //inject NONSTANDARD NAMING uint256 constant internal max_uint25 = 2 ** 256 - 1; // max uint256 //inject NONSTANDARD NAMING function MUL14(uint256 _a, uint256 _b) internal pure returns(uint256) { //inject NONSTANDARD NAMING if (_a == 0) { return 0; } require(max_uint25 / _a >= _b); return _a * _b; } function DIV12(uint256 _a, uint256 _b) internal pure returns(uint256) { //inject NONSTANDARD NAMING require(_b != 0); return _a / _b; } function SUB94(uint256 _a, uint256 _b) internal pure returns(uint256) { //inject NONSTANDARD NAMING require(_b <= _a); return _a - _b; } function ADD70(uint256 _a, uint256 _b) internal pure returns(uint256) { //inject NONSTANDARD NAMING require(max_uint25 - _a >= _b); return _a + _b; } } interface abcinterface55 { //inject NONSTANDARD NAMING function DECIMALS31() external view returns (uint8); //inject NONSTANDARD NAMING function TOKENFALLBACK96(address _from, uint _value, bytes calldata _data) external; //inject NONSTANDARD NAMING function TRANSFER8(address _to, uint _value) external returns (bool); //inject NONSTANDARD NAMING } contract ownable89 { //inject NONSTANDARD NAMING address public owner; event OWNERSHIPTRANSFERRED5(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () public { owner = msg.sender; } modifier ONLYOWNER84() { //inject NONSTANDARD NAMING require(msg.sender == owner); _; } function TRANSFEROWNERSHIP95(address newOwner) public ONLYOWNER84 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP10(newOwner); } function _TRANSFEROWNERSHIP10(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED5(owner, newOwner); owner = newOwner; } } contract pausable6 is ownable89 { //inject NONSTANDARD NAMING event PAUSE44(); //inject NONSTANDARD NAMING event UNPAUSE10(); //inject NONSTANDARD NAMING bool public paused = false; modifier WHENNOTPAUSED65() { //inject NONSTANDARD NAMING require(!paused); _; } modifier WHENPAUSED45() { //inject NONSTANDARD NAMING require(paused); _; } function PAUSE13() public ONLYOWNER84 WHENNOTPAUSED65 { //inject NONSTANDARD NAMING paused = true; emit PAUSE44(); } function UNPAUSE100() public ONLYOWNER84 WHENPAUSED45 { //inject NONSTANDARD NAMING paused = false; emit UNPAUSE10(); } } contract standardtoken75 { //inject NONSTANDARD NAMING using safemath3 for uint256; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 public totalSupply; event TRANSFER15(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL37(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING function BALANCEOF36(address _owner) public view returns(uint256) { //inject NONSTANDARD NAMING return balances[_owner]; } function ALLOWANCE8(address _owner, address _spender) public view returns(uint256) { //inject NONSTANDARD NAMING return allowed[_owner][_spender]; } function TRANSFER8(address _to, uint256 _value) public returns(bool) { //inject NONSTANDARD NAMING require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].SUB94(_value); balances[_to] = balances[_to].ADD70(_value); emit TRANSFER15(msg.sender, _to, _value); return true; } function APPROVE5(address _spender, uint256 _value) public returns(bool) { //inject NONSTANDARD NAMING allowed[msg.sender][_spender] = _value; emit APPROVAL37(msg.sender, _spender, _value); return true; } function TRANSFERFROM4(address _from, address _to, uint256 _value) public returns(bool) { //inject NONSTANDARD NAMING require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].SUB94(_value); balances[_to] = balances[_to].ADD70(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].SUB94(_value); emit TRANSFER15(_from, _to, _value); return true; } function INCREASEAPPROVAL59(address _spender, uint256 _addedValue) public returns(bool) { //inject NONSTANDARD NAMING allowed[msg.sender][_spender] = allowed[msg.sender][_spender].ADD70(_addedValue); emit APPROVAL37(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function DECREASEAPPROVAL60(address _spender, uint256 _subtractedValue) public returns(bool) { //inject NONSTANDARD NAMING uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.SUB94(_subtractedValue); } emit APPROVAL37(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function _BURN20(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); totalSupply = totalSupply.SUB94(value); balances[account] = balances[account].SUB94(value); emit TRANSFER15(account, address(0), value); } function _BURNFROM53(address account, uint256 value) internal { //inject NONSTANDARD NAMING // 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].SUB94(value); _BURN20(account, value); } } contract burnabletoken62 is standardtoken75 { //inject NONSTANDARD NAMING function BURN76(uint256 value) public { //inject NONSTANDARD NAMING _BURN20(msg.sender, value); } function BURNFROM19(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM53(from, value); } } contract pausabletoken80 is standardtoken75, pausable6 { //inject NONSTANDARD NAMING function TRANSFER8(address to, uint256 value) public WHENNOTPAUSED65 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFER8(to, value); } function TRANSFERFROM4(address from, address to, uint256 value) public WHENNOTPAUSED65 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFERFROM4(from, to, value); } function APPROVE5(address spender, uint256 value) public WHENNOTPAUSED65 returns (bool) { //inject NONSTANDARD NAMING return super.APPROVE5(spender, value); } function INCREASEAPPROVAL59(address spender, uint256 addedValue) public WHENNOTPAUSED65 returns (bool success) { //inject NONSTANDARD NAMING return super.INCREASEAPPROVAL59(spender, addedValue); } function DECREASEAPPROVAL60(address spender, uint256 subtractedValue) public WHENNOTPAUSED65 returns (bool success) { //inject NONSTANDARD NAMING return super.DECREASEAPPROVAL60(spender, subtractedValue); } } contract token13 is pausabletoken80, burnabletoken62 { //inject NONSTANDARD NAMING string public name; // name of Token string public symbol; // symbol of Token uint8 public decimals; constructor(string memory _name, string memory _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } contract bdr1 is token13 { //inject NONSTANDARD NAMING struct Trx { bool executed; address from; uint256 value; address[] signers; } mapping(address => bool) public isSigner; mapping(uint256 => Trx) public exchangeTrx; address public AbcInstance; // address of AbcToken uint256 public requestSigners = 2; // BDR => Abc need signers number uint256 public applyCounts = 0; // Sequence of exchange request mapping(address => uint256) public exchangeLock; event SETSIGNER61(address indexed signer,bool isSigner); // emit when add/remove signer //inject NONSTANDARD NAMING event APPLYEXCHANGETOKEN76(address indexed from,uint256 value,uint256 trxSeq); // emit when exchange successful //inject NONSTANDARD NAMING event CONFIRMTRX99(address indexed signer,uint256 indexed trxSeq); // emit when signer confirmed exchange request //inject NONSTANDARD NAMING event CANCLECONFIRMTRX58(address indexed signer,uint256 indexed trxSeq); // emit when signer cancles confirmed exchange request //inject NONSTANDARD NAMING event CANCLEEXCHANGEREQUEST46(address indexed signer,uint256 indexed trxSeq); // emit when signer/requester cancles exchange request //inject NONSTANDARD NAMING event TOKENEXCHANGE38(address indexed from,uint256 value,bool AbcExchangeBDR); // emit when Abc <=> Bdr,true:Abc => BDR,false:BDR => abc //inject NONSTANDARD NAMING event MINT96(address indexed target,uint256 value); //inject NONSTANDARD NAMING modifier ONLYSIGNER18() { //inject NONSTANDARD NAMING require(isSigner[msg.sender]); _; } constructor(string memory _name, string memory _symbol, uint8 _decimals) token13(_name,_symbol,_decimals) public { } function TRANSFER8(address _to,uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING require(_to != AbcInstance,"can't transfer to AbcToken address directly"); return super.TRANSFER8(_to,_value); } function TRANSFERFROM4(address _from, address _to,uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING require(_to != AbcInstance,"can't transferFrom to AbcToken address directly"); return super.TRANSFERFROM4(_from,_to,_value); } function SETABCINSTANCE98(address _abc) public ONLYOWNER84 { //inject NONSTANDARD NAMING require(_abc != address(0)); AbcInstance = _abc; } function SETSIGNERS29(address[] memory _signers,bool _addSigner) public ONLYOWNER84 { //inject NONSTANDARD NAMING for(uint256 i = 0;i< _signers.length;i++){ require(_signers[i] != address(0)); isSigner[_signers[i]] = _addSigner; emit SETSIGNER61(_signers[i],_addSigner); } } function SETREQUESTSIGNERS10(uint256 _requestSigners) public ONLYOWNER84 { //inject NONSTANDARD NAMING require(_requestSigners != 0); requestSigners = _requestSigners; } function ISCONFIRMER42(uint256 _trxSeq,address _signer) public view returns (bool) { //inject NONSTANDARD NAMING require(exchangeTrx[_trxSeq].from != address(0),"trxSeq not exist"); for(uint256 i = 0;i < exchangeTrx[_trxSeq].signers.length;i++){ if(exchangeTrx[_trxSeq].signers[i] == _signer){ return true; } } return false; } function GETCONFIRMERSLENGTHOFTRX91(uint256 _trxSeq) public view returns (uint256) { //inject NONSTANDARD NAMING return exchangeTrx[_trxSeq].signers.length; } function GETCONFIRMEROFTRX7(uint256 _trxSeq,uint256 _index) public view returns (address) { //inject NONSTANDARD NAMING require(_index < GETCONFIRMERSLENGTHOFTRX91(_trxSeq),"out of range"); return exchangeTrx[_trxSeq].signers[_index]; } function APPLYEXCHANGETOKEN24(uint256 _value) public WHENNOTPAUSED65 returns (uint256) { //inject NONSTANDARD NAMING uint256 trxSeq = applyCounts; require(exchangeTrx[trxSeq].from == address(0),"trxSeq already exist"); require(balances[msg.sender] >= _value); exchangeTrx[trxSeq].executed = false; exchangeTrx[trxSeq].from = msg.sender; exchangeTrx[trxSeq].value = _value; applyCounts = applyCounts.ADD70(1); balances[address(this)] = balances[address(this)].ADD70(_value); balances[exchangeTrx[trxSeq].from] = balances[exchangeTrx[trxSeq].from].SUB94(_value); exchangeLock[exchangeTrx[trxSeq].from] = exchangeLock[exchangeTrx[trxSeq].from].ADD70(_value); emit APPLYEXCHANGETOKEN76(exchangeTrx[trxSeq].from,exchangeTrx[trxSeq].value,trxSeq); emit TRANSFER15(msg.sender,address(this),_value); return trxSeq; } function CONFIRMEXCHANGETRX5(uint256 _trxSeq) public ONLYSIGNER18 { //inject NONSTANDARD NAMING require(exchangeTrx[_trxSeq].from != address(0),"_trxSeq not exist"); require(exchangeTrx[_trxSeq].signers.length < requestSigners,"trx already has enough signers"); require(exchangeTrx[_trxSeq].executed == false,"trx already executed"); require(ISCONFIRMER42(_trxSeq, msg.sender) == false,"signer already confirmed"); exchangeTrx[_trxSeq].signers.push(msg.sender); emit CONFIRMTRX99(msg.sender, _trxSeq); } function CANCELCONFIRM57(uint256 _trxSeq) public ONLYSIGNER18 { //inject NONSTANDARD NAMING require(exchangeTrx[_trxSeq].from != address(0),"_trxSeq not exist"); require(ISCONFIRMER42(_trxSeq, msg.sender),"Signer didn't confirm"); require(exchangeTrx[_trxSeq].executed == false,"trx already executed"); uint256 len = exchangeTrx[_trxSeq].signers.length; for(uint256 i = 0;i < len;i++){ if(exchangeTrx[_trxSeq].signers[i] == msg.sender){ exchangeTrx[_trxSeq].signers[i] = exchangeTrx[_trxSeq].signers[len.SUB94(1)] ; exchangeTrx[_trxSeq].signers.length --; break; } } emit CANCLECONFIRMTRX58(msg.sender,_trxSeq); } function CANCLEEXCHANGEREQUEST83(uint256 _trxSeq) public { //inject NONSTANDARD NAMING require(exchangeTrx[_trxSeq].from != address(0),"_trxSeq not exist"); require(exchangeTrx[_trxSeq].executed == false,"trx already executed"); require(isSigner[msg.sender] || exchangeTrx[_trxSeq].from == msg.sender); balances[address(this)] = balances[address(this)].SUB94(exchangeTrx[_trxSeq].value); balances[exchangeTrx[_trxSeq].from] = balances[exchangeTrx[_trxSeq].from].ADD70(exchangeTrx[_trxSeq].value); exchangeLock[exchangeTrx[_trxSeq].from] = exchangeLock[exchangeTrx[_trxSeq].from].SUB94(exchangeTrx[_trxSeq].value); delete exchangeTrx[_trxSeq]; emit CANCLEEXCHANGEREQUEST46(msg.sender,_trxSeq); emit TRANSFER15(address(this),exchangeTrx[_trxSeq].from,exchangeTrx[_trxSeq].value); } function EXECUTEEXCHANGETRX59(uint256 _trxSeq) public WHENNOTPAUSED65{ //inject NONSTANDARD NAMING address from = exchangeTrx[_trxSeq].from; uint256 value = exchangeTrx[_trxSeq].value; require(from != address(0),"trxSeq not exist"); require(exchangeTrx[_trxSeq].executed == false,"trxSeq has executed"); require(exchangeTrx[_trxSeq].signers.length >= requestSigners); require(from == msg.sender|| isSigner[msg.sender]); require(value <= balances[address(this)]); _BURN20(address(this), value); exchangeLock[from] = exchangeLock[from].SUB94(value); exchangeTrx[_trxSeq].executed = true; abcinterface55(AbcInstance).TOKENFALLBACK96(from,value,bytes("")); emit TOKENEXCHANGE38(exchangeTrx[_trxSeq].from,exchangeTrx[_trxSeq].value,false); } function TOKENFALLBACK96(address _from, uint _value, bytes memory) public { //inject NONSTANDARD NAMING require(msg.sender == AbcInstance); require(_from != address(0)); require(_value > 0); uint256 exchangeAmount = _value.MUL14(10**uint256(decimals)).DIV12(10**uint256(abcinterface55(AbcInstance).DECIMALS31())); _MINT16(_from, exchangeAmount); emit TRANSFER15(address(0x00),_from,exchangeAmount); emit TOKENEXCHANGE38(_from,_value,true); } function _MINT16(address target, uint256 value ) internal { //inject NONSTANDARD NAMING balances[target] = balances[target].ADD70(value); totalSupply = totalSupply.ADD70(value); emit MINT96(target,value); } }
inject NONSTANDARD NAMING
function APPROVE5(address _spender, uint256 _value) public returns(bool) {
974,735
pragma solidity ^0.4.18; contract SafeMathLib { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint c = a + b; assert(c>=a); return c; } function safeDiv(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; } } /** * @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; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * A token that defines fractional units as decimals. */ contract FractionalERC20 is ERC20 { uint8 public decimals; } /** * Standard ERC20 token with Short Hand Attack and approve() race condition mitigation. * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, SafeMathLib { /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint256 amount); /* Actual balances of token holders */ mapping(address => uint) balances; /* approve() allowances */ mapping (address => mapping (address => uint256)) allowed; 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] = safeSub(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to],_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint _allowance = allowed[_from][msg.sender]; require(_to != address(0)); require(_value <= balances[_from]); require(_value <= _allowance); require(balances[_to] + _value > balances[_to]); balances[_to] = safeAdd(balances[_to],_value); balances[_from] = safeSub(balances[_from],_value); allowed[_from][msg.sender] = safeSub(_allowance,_value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { 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, uint256 _addedValue) public returns (bool) { allowed[msg.sender][_spender] = safeAdd(allowed[msg.sender][_spender],_addedValue); 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, uint256 _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = safeSub(oldValue,_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { 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 { require(_value <= balances[msg.sender]); // 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 address burner = msg.sender; balances[burner] = safeSub(balances[burner],_value); totalSupply = safeSub(totalSupply,_value); Burn(burner, _value); } } /** * Upgrade agent interface inspired by Lunyr. * * Upgrade agent transfers tokens to a new contract. * Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting. */ contract UpgradeAgent { uint public originalSupply; /** Interface marker */ function isUpgradeAgent() public pure returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision. * * First envisioned by Golem and Lunyr projects. */ contract UpgradeableToken is StandardToken { /** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed _from, address indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address _upgradeMaster) public { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); require((state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)); // Validate input value. require (value != 0); balances[msg.sender] = safeSub(balances[msg.sender],value); // Take tokens out from circulation totalSupply = safeSub(totalSupply,value); totalUpgraded = safeAdd(totalUpgraded,value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { require(canUpgrade()); require(agent != 0x0); // Only a master can designate the next agent require(msg.sender == upgradeMaster); // Upgrade has already begun for an agent require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent); // Bad interface require(upgradeAgent.isUpgradeAgent()); // Make sure that token supplies match in source and target require(upgradeAgent.originalSupply() == totalSupply); UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns(UpgradeState) { if(!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { require(master != 0x0); require(msg.sender == upgradeMaster); upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begun. */ function canUpgrade() public view returns(bool) { return true; } } /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is ERC20, Ownable { /* The finalizer contract that allows unlift the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Limit token transfer until the crowdsale is over. * */ modifier canTransfer(address _sender) { if(!released) { require(transferAgents[_sender]); } _; } /** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } /** * One way function to release the tokens to the wild. * * Can be called only from the release agent that is the final ICO contract. It is only called if the crowdsale has been success (first milestone reached). */ function releaseTokenTransfer() public onlyReleaseAgent { released = true; } /** The function can be called only before or after the tokens have been releasesd */ modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } function transfer(address _to, uint _value) canTransfer(msg.sender) public returns (bool success) { // Call StandardToken.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) public returns (bool success) { // Call StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } } /** * A token that can increase its supply by another contract. * * This allows uncapped crowdsale by dynamically increasing the supply when money pours in. * Only mint agents, contracts whitelisted by owner, can mint new tokens. * */ contract MintableToken is StandardToken, Ownable { bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state); event Mint(address indexed to, uint256 amount); /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint256 amount) onlyMintAgent canMint public returns(bool){ totalSupply = safeAdd(totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event Mint(receiver, amount); Transfer(0, receiver, amount); return true; } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** Make sure we are not done yet. */ modifier canMint() { require(!mintingFinished); _; } } /** * A crowdsaled token. * * An ERC-20 token designed specifically for crowdsales with investor protection and further development path. * * - The token transfer() is disabled until the crowdsale is over * - The token contract gives an opt-in upgrade path to a new contract * - The same token can be part of several crowdsales through approve() mechanism * - The token can be capped (supply set in the constructor) or uncapped (crowdsale contract can mint new tokens) * */ contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken, BurnableToken { event UpdatedTokenInformation(string newName, string newSymbol); string public name; string public symbol; uint8 public decimals; /** * Construct the token. * * This token must be created through a team multisig wallet, so that it is owned by that wallet. * * @param _name Token name * @param _symbol Token symbol - should be all caps * @param _initialSupply How many tokens we start with * @param _decimals Number of decimal places * @param _mintable Are new tokens created over the crowdsale or do we distribute only the initial supply? Note that when the token becomes transferable the minting always ends. */ function CrowdsaleToken(string _name, string _symbol, uint _initialSupply, uint8 _decimals, bool _mintable) public UpgradeableToken(msg.sender) { // Create any address, can be transferred // to team multisig via changeOwner(), // also remember to call setUpgradeMaster() owner = msg.sender; name = _name; symbol = _symbol; totalSupply = _initialSupply; decimals = _decimals; // Create initially all balance on the team multisig balances[owner] = totalSupply; if(totalSupply > 0) { Minted(owner, totalSupply); } // No more new supply allowed after the token creation if(!_mintable) { mintingFinished = true; require(totalSupply != 0); } } /** * When token is released to be transferable, enforce no new tokens can be created. */ function releaseTokenTransfer() public onlyReleaseAgent { mintingFinished = true; super.releaseTokenTransfer(); } /** * Allow upgrade agent functionality kick in only if the crowdsale was success. */ function canUpgrade() public view returns(bool) { return released && super.canUpgrade(); } /** * Owner can update token information here */ function setTokenInformation(string _name, string _symbol) onlyOwner public { name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } } /** * Finalize agent defines what happens at the end of succeseful crowdsale. * * - Allocate tokens for founders, bounties and community * - Make tokens transferable * - etc. */ contract FinalizeAgent { function isFinalizeAgent() public pure returns(bool) { return true; } /** Return true if we can run finalizeCrowdsale() properly. * * This is a safety check function that doesn't allow crowdsale to begin * unless the finalizer has been set up properly. */ function isSane() public view returns (bool); /** Called once by crowdsale finalize() if the sale was success. */ function finalizeCrowdsale() public ; } /** * Interface for defining crowdsale pricing. */ contract PricingStrategy { /** Interface declaration. */ function isPricingStrategy() public pure returns (bool) { return true; } /** Self check if all references are correctly set. * * Checks that pricing strategy matches crowdsale parameters. */ function isSane(address crowdsale) public view returns (bool) { return true; } /** * When somebody tries to buy tokens for X eth, calculate how many tokens they get. * * * @param value - What is the value of the transaction send in as wei * @param tokensSold - how much tokens have been sold this far * @param weiRaised - how much money has been raised this far * @param msgSender - who is the investor of this transaction * @param decimals - how many decimal units the token has * @return Amount of tokens the investor receives */ function calculatePrice(uint256 value, uint256 weiRaised, uint256 tokensSold, address msgSender, uint256 decimals) public constant returns (uint256 tokenAmount); } /* * Haltable * * Abstract contract that allows children to implement an * emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. * * * Originally envisioned in FirstBlood ICO contract. */ contract Haltable is Ownable { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } contract Allocatable is Ownable { /** List of agents that are allowed to allocate new tokens */ mapping (address => bool) public allocateAgents; event AllocateAgentChanged(address addr, bool state ); /** * Owner can allow a crowdsale contract to allocate new tokens. */ function setAllocateAgent(address addr, bool state) onlyOwner public { allocateAgents[addr] = state; AllocateAgentChanged(addr, state); } modifier onlyAllocateAgent() { // Only crowdsale contracts are allowed to allocate new tokens require(allocateAgents[msg.sender]); _; } } /** * Abstract base contract for token sales. * * Handle * - start and end dates * - accepting investments * - minimum funding goal and refund * - various statistics during the crowdfund * - different pricing strategies * - different investment policies (require server side customer id, allow only whitelisted addresses) * */ contract Crowdsale is Allocatable, Haltable, SafeMathLib { /* Max investment count when we are still allowed to change the multisig address */ uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; /* The token we are selling */ FractionalERC20 public token; /* Token Vesting Contract */ address public tokenVestingAddress; /* How we are going to price our offering */ PricingStrategy public pricingStrategy; /* Post-success callback */ FinalizeAgent public finalizeAgent; /* tokens will be transfered from this address */ address public multisigWallet; /* if the funding goal is not reached, investors may withdraw their funds */ uint256 public minimumFundingGoal; /* the UNIX timestamp start date of the crowdsale */ uint256 public startsAt; /* the UNIX timestamp end date of the crowdsale */ uint256 public endsAt; /* the number of tokens already sold through this contract*/ uint256 public tokensSold = 0; /* How many wei of funding we have raised */ uint256 public weiRaised = 0; /* How many distinct addresses have invested */ uint256 public investorCount = 0; /* How much wei we have returned back to the contract after a failed crowdfund. */ uint256 public loadedRefund = 0; /* How much wei we have given back to investors.*/ uint256 public weiRefunded = 0; /* Has this crowdsale been finalized */ bool public finalized; /* Do we need to have unique contributor id for each customer */ bool public requireCustomerId; /** * Do we verify that contributor has been cleared on the server side (accredited investors only). * This method was first used in FirstBlood crowdsale to ensure all contributors have accepted terms on sale (on the web). */ bool public requiredSignedAddress; /* Server side address that signed allowed contributors (Ethereum addresses) that can participate the crowdsale */ address public signerAddress; /** How much ETH each address has invested to this crowdsale */ mapping (address => uint256) public investedAmountOf; /** How much tokens this crowdsale has credited for each investor address */ mapping (address => uint256) public tokenAmountOf; /** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */ mapping (address => bool) public earlyParticipantWhitelist; /** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */ uint256 public ownerTestValue; uint256 public earlyPariticipantWeiPrice =82815734989648; uint256 public whitelistBonusPercentage = 15; uint256 public whitelistPrincipleLockPercentage = 50; uint256 public whitelistBonusLockPeriod = 7776000; uint256 public whitelistPrincipleLockPeriod = 7776000; /** State machine * * - Preparing: All contract initialization calls and variables have not been set yet * - Prefunding: We have not passed start time yet * - Funding: Active crowdsale * - Success: Minimum funding goal reached * - Failure: Minimum funding goal not reached before ending time * - Finalized: The finalized has been called and succesfully executed * - Refunding: Refunds are loaded on the contract for reclaim. */ enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding} // A new investment was made event Invested(address investor, uint256 weiAmount, uint256 tokenAmount, uint128 customerId); // Refund was processed for a contributor event Refund(address investor, uint256 weiAmount); // The rules were changed what kind of investments we accept event InvestmentPolicyChanged(bool requireCustId, bool requiredSignedAddr, address signerAddr); // Address early participation whitelist status changed event Whitelisted(address addr, bool status); // Crowdsale end time has been changed event EndsAtChanged(uint256 endAt); // Crowdsale start time has been changed event StartAtChanged(uint256 endsAt); function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint256 _start, uint256 _end, uint256 _minimumFundingGoal, address _tokenVestingAddress) public { owner = msg.sender; token = FractionalERC20(_token); tokenVestingAddress = _tokenVestingAddress; setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; require(multisigWallet != 0); require(_start != 0); startsAt = _start; require(_end != 0); endsAt = _end; // Don't mess the dates require(startsAt < endsAt); // Minimum funding goal can be zero minimumFundingGoal = _minimumFundingGoal; } /** * Don't expect to just send in money and get tokens. */ function() payable public { invest(msg.sender); } /** Function to set default vesting schedule parameters. */ function setDefaultWhitelistVestingParameters(uint256 _bonusPercentage, uint256 _principleLockPercentage, uint256 _bonusLockPeriod, uint256 _principleLockPeriod, uint256 _earlyPariticipantWeiPrice) onlyAllocateAgent public { whitelistBonusPercentage = _bonusPercentage; whitelistPrincipleLockPercentage = _principleLockPercentage; whitelistBonusLockPeriod = _bonusLockPeriod; whitelistPrincipleLockPeriod = _principleLockPeriod; earlyPariticipantWeiPrice = _earlyPariticipantWeiPrice; } /** * Make an investment. * * Crowdsale must be running for one to invest. * We must have not pressed the emergency brake. * * @param receiver The Ethereum address who receives the tokens * @param customerId (optional) UUID v4 to track the successful payments on the server side * */ function investInternal(address receiver, uint128 customerId) stopInEmergency private { uint256 tokenAmount; uint256 weiAmount = msg.value; // Determine if it's a good time to accept investment from this participant if (getState() == State.PreFunding) { // Are we whitelisted for early deposit require(earlyParticipantWhitelist[receiver]); require(weiAmount >= safeMul(15, uint(10 ** 18))); require(weiAmount <= safeMul(50, uint(10 ** 18))); tokenAmount = safeDiv(safeMul(weiAmount, uint(10) ** token.decimals()), earlyPariticipantWeiPrice); if (investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount); tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount); // Update totals weiRaised = safeAdd(weiRaised,weiAmount); tokensSold = safeAdd(tokensSold,tokenAmount); // Check that we did not bust the cap require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)); if (safeAdd(whitelistPrincipleLockPercentage,whitelistBonusPercentage) > 0) { uint256 principleAmount = safeDiv(safeMul(tokenAmount, 100), safeAdd(whitelistBonusPercentage, 100)); uint256 bonusLockAmount = safeDiv(safeMul(whitelistBonusPercentage, principleAmount), 100); uint256 principleLockAmount = safeDiv(safeMul(whitelistPrincipleLockPercentage, principleAmount), 100); uint256 totalLockAmount = safeAdd(principleLockAmount, bonusLockAmount); TokenVesting tokenVesting = TokenVesting(tokenVestingAddress); // to prevent minting of tokens which will be useless as vesting amount cannot be updated require(!tokenVesting.isVestingSet(receiver)); require(totalLockAmount <= tokenAmount); assignTokens(tokenVestingAddress,totalLockAmount); // set vesting with default schedule tokenVesting.setVesting(receiver, principleLockAmount, whitelistPrincipleLockPeriod, bonusLockAmount, whitelistBonusLockPeriod); } // assign remaining tokens to contributor if (tokenAmount - totalLockAmount > 0) { assignTokens(receiver, tokenAmount - totalLockAmount); } // Pocket the money require(multisigWallet.send(weiAmount)); // Tell us invest was success Invested(receiver, weiAmount, tokenAmount, customerId); } else if(getState() == State.Funding) { // Retail participants can only come in when the crowdsale is running tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); require(tokenAmount != 0); if(investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount); tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount); // Update totals weiRaised = safeAdd(weiRaised,weiAmount); tokensSold = safeAdd(tokensSold,tokenAmount); // Check that we did not bust the cap require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)); assignTokens(receiver, tokenAmount); // Pocket the money require(multisigWallet.send(weiAmount)); // Tell us invest was success Invested(receiver, weiAmount, tokenAmount, customerId); } else { // Unwanted state require(false); } } /** * allocate tokens for the early investors. * * Preallocated tokens have been sold before the actual crowdsale opens. * This function mints the tokens and moves the crowdsale needle. * * Investor count is not handled; it is assumed this goes for multiple investors * and the token distribution happens outside the smart contract flow. * * No money is exchanged, as the crowdsale team already have received the payment. * * @param weiPrice Price of a single full token in wei * */ function preallocate(address receiver, uint256 tokenAmount, uint256 weiPrice, uint256 principleLockAmount, uint256 principleLockPeriod, uint256 bonusLockAmount, uint256 bonusLockPeriod) public onlyAllocateAgent { uint256 weiAmount = (weiPrice * tokenAmount)/10**uint256(token.decimals()); // This can be also 0, we give out tokens for free uint256 totalLockAmount = 0; weiRaised = safeAdd(weiRaised,weiAmount); tokensSold = safeAdd(tokensSold,tokenAmount); investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount); tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount); // cannot lock more than total tokens totalLockAmount = safeAdd(principleLockAmount, bonusLockAmount); require(totalLockAmount <= tokenAmount); // assign locked token to Vesting contract if (totalLockAmount > 0) { TokenVesting tokenVesting = TokenVesting(tokenVestingAddress); // to prevent minting of tokens which will be useless as vesting amount cannot be updated require(!tokenVesting.isVestingSet(receiver)); assignTokens(tokenVestingAddress,totalLockAmount); // set vesting with default schedule tokenVesting.setVesting(receiver, principleLockAmount, principleLockPeriod, bonusLockAmount, bonusLockPeriod); } // assign remaining tokens to contributor if (tokenAmount - totalLockAmount > 0) { assignTokens(receiver, tokenAmount - totalLockAmount); } // Tell us invest was success Invested(receiver, weiAmount, tokenAmount, 0); } /** * Track who is the customer making the payment so we can send thank you email. */ function investWithCustomerId(address addr, uint128 customerId) public payable { require(!requiredSignedAddress); require(customerId != 0); investInternal(addr, customerId); } /** * Allow anonymous contributions to this crowdsale. */ function invest(address addr) public payable { require(!requireCustomerId); require(!requiredSignedAddress); investInternal(addr, 0); } /** * Invest to tokens, recognize the payer and clear his address. * */ // function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { // investWithSignedAddress(msg.sender, customerId, v, r, s); // } /** * Invest to tokens, recognize the payer. * */ function buyWithCustomerId(uint128 customerId) public payable { investWithCustomerId(msg.sender, customerId); } /** * The basic entry point to participate the crowdsale process. * * Pay for funding, get invested tokens back in the sender address. */ function buy() public payable { invest(msg.sender); } /** * Finalize a succcesful crowdsale. * * The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { // Already finalized require(!finalized); // Finalizing is optional. We only call it if we are given a finalizing agent. if(address(finalizeAgent) != 0) { finalizeAgent.finalizeCrowdsale(); } finalized = true; } /** * Allow to (re)set finalize agent. * * Design choice: no state restrictions on setting this, so that we can fix fat finger mistakes. */ function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { finalizeAgent = addr; // Don't allow setting bad agent require(finalizeAgent.isFinalizeAgent()); } /** * Set policy do we need to have server-side customer ids for the investments. * */ function setRequireCustomerId(bool value) public onlyOwner { requireCustomerId = value; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } /** * Allow addresses to do early participation. * * TODO: Fix spelling error in the name */ function setEarlyParicipantWhitelist(address addr, bool status) public onlyAllocateAgent { earlyParticipantWhitelist[addr] = status; Whitelisted(addr, status); } function setWhiteList(address[] _participants) public onlyAllocateAgent { require(_participants.length > 0); uint256 participants = _participants.length; for (uint256 j=0; j<participants; j++) { require(_participants[j] != 0); earlyParticipantWhitelist[_participants[j]] = true; Whitelisted(_participants[j], true); } } /** * Allow crowdsale owner to close early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function setEndsAt(uint time) public onlyOwner { require(now <= time); endsAt = time; EndsAtChanged(endsAt); } /** * Allow crowdsale owner to begin early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function setStartAt(uint time) public onlyOwner { startsAt = time; StartAtChanged(endsAt); } /** * Allow to (re)set pricing strategy. * * Design choice: no state restrictions on the set, so that we can fix fat finger mistakes. */ function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { pricingStrategy = _pricingStrategy; // Don't allow setting bad agent require(pricingStrategy.isPricingStrategy()); } /** * Allow to change the team multisig address in the case of emergency. * * This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun * (we have done only few test transactions). After the crowdsale is going * then multisig address stays locked for the safety reasons. */ function setMultisig(address addr) public onlyOwner { // Change require(investorCount <= MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE); multisigWallet = addr; } /** * Allow load refunds back on the contract for the refunding. * * The team can transfer the funds back on the smart contract in the case the minimum goal was not reached.. */ function loadRefund() public payable inState(State.Failure) { require(msg.value != 0); loadedRefund = safeAdd(loadedRefund,msg.value); } /** * Investors can claim refund. */ function refund() public inState(State.Refunding) { uint256 weiValue = investedAmountOf[msg.sender]; require(weiValue != 0); investedAmountOf[msg.sender] = 0; weiRefunded = safeAdd(weiRefunded,weiValue); Refund(msg.sender, weiValue); require(msg.sender.send(weiValue)); } /** * @return true if the crowdsale has raised enough money to be a succes */ function isMinimumGoalReached() public constant returns (bool reached) { return weiRaised >= minimumFundingGoal; } /** * Check if the contract relationship looks good. */ function isFinalizerSane() public constant returns (bool sane) { return finalizeAgent.isSane(); } /** * Check if the contract relationship looks good. */ function isPricingSane() public constant returns (bool sane) { return pricingStrategy.isSane(address(this)); } /** * Crowdfund state machine management. * * We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale. */ function getState() public constant returns (State) { if(finalized) return State.Finalized; else if (address(finalizeAgent) == 0) return State.Preparing; else if (!finalizeAgent.isSane()) return State.Preparing; else if (!pricingStrategy.isSane(address(this))) return State.Preparing; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding; else return State.Failure; } /** This is for manual testing of multisig wallet interaction */ function setOwnerTestValue(uint val) public onlyOwner { ownerTestValue = val; } /** Interface marker. */ function isCrowdsale() public pure returns (bool) { return true; } // // Modifiers // /** Modified allowing execution only if the crowdsale is currently running. */ modifier inState(State state) { require(getState() == state); _; } // // Abstract functions // /** * Check if the current invested breaks our cap rules. * * * The child contract must define their own cap setting rules. * We allow a lot of flexibility through different capping strategies (ETH, token count) * Called from invest(). * * @param weiAmount The amount of wei the investor tries to invest in the current transaction * @param tokenAmount The amount of tokens we try to give to the investor in the current transaction * @param weiRaisedTotal What would be our total raised balance after this transaction * @param tokensSoldTotal What would be our total sold tokens count after this transaction * * @return true if taking this investment would break our cap rules */ function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); /** * Check if the current crowdsale is full and we can no longer sell any tokens. */ function isCrowdsaleFull() public constant returns (bool); /** * Create new tokens or transfer issued tokens to the investor depending on the cap model. */ function assignTokens(address receiver, uint tokenAmount) private; } /** * At the end of the successful crowdsale allocate % bonus of tokens to the team. * * Unlock tokens. * * BonusAllocationFinal must be set as the minting agent for the MintableToken. * */ contract BonusFinalizeAgent is FinalizeAgent, SafeMathLib { CrowdsaleToken public token; Crowdsale public crowdsale; uint256 public allocatedTokens; uint256 tokenCap; address walletAddress; function BonusFinalizeAgent(CrowdsaleToken _token, Crowdsale _crowdsale, uint256 _tokenCap, address _walletAddress) public { token = _token; crowdsale = _crowdsale; //crowdsale address must not be 0 require(address(crowdsale) != 0); tokenCap = _tokenCap; walletAddress = _walletAddress; } /* Can we run finalize properly */ function isSane() public view returns (bool) { return (token.mintAgents(address(this)) == true) && (token.releaseAgent() == address(this)); } /** Called once by crowdsale finalize() if the sale was success. */ function finalizeCrowdsale() public { // if finalized is not being called from the crowdsale // contract then throw require (msg.sender == address(crowdsale)); // get the total sold tokens count. uint256 tokenSupply = token.totalSupply(); allocatedTokens = safeSub(tokenCap,tokenSupply); if ( allocatedTokens > 0) { token.mint(walletAddress, allocatedTokens); } token.releaseTokenTransfer(); } } /** * ICO crowdsale contract that is capped by amout of ETH. * * - Tokens are dynamically created during the crowdsale * * */ contract MintedEthCappedCrowdsale is Crowdsale { /* Maximum amount of wei this crowdsale can raise. */ uint public weiCap; function MintedEthCappedCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint256 _start, uint256 _end, uint256 _minimumFundingGoal, uint256 _weiCap, address _tokenVestingAddress) Crowdsale(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal,_tokenVestingAddress) public { weiCap = _weiCap; } /** * Called from invest() to confirm if the curret investment does not break our cap rule. */ function isBreakingCap(uint256 weiAmount, uint256 tokenAmount, uint256 weiRaisedTotal, uint256 tokensSoldTotal) public constant returns (bool limitBroken) { return weiRaisedTotal > weiCap; } function isCrowdsaleFull() public constant returns (bool) { return weiRaised >= weiCap; } /** * Dynamically create tokens and assign them to the investor. */ function assignTokens(address receiver, uint256 tokenAmount) private { MintableToken mintableToken = MintableToken(token); mintableToken.mint(receiver, tokenAmount); } } /// @dev Tranche based pricing with special support for pre-ico deals. /// Implementing "first price" tranches, meaning, that if byers order is /// covering more than one tranche, the price of the lowest tranche will apply /// to the whole order. contract EthTranchePricing is PricingStrategy, Ownable, SafeMathLib { uint public constant MAX_TRANCHES = 10; // This contains all pre-ICO addresses, and their prices (weis per token) mapping (address => uint256) public preicoAddresses; /** * Define pricing schedule using tranches. */ struct Tranche { // Amount in weis when this tranche becomes active uint amount; // How many tokens per wei you will get while this tranche is active uint price; } // Store tranches in a fixed array, so that it can be seen in a blockchain explorer // Tranche 0 is always (0, 0) // (TODO: change this when we confirm dynamic arrays are explorable) Tranche[10] public tranches; // How many active tranches we have uint public trancheCount; /// @dev Contruction, creating a list of tranches /// @param _tranches uint[] tranches Pairs of (start amount, price) function EthTranchePricing(uint[] _tranches) public { // Need to have tuples, length check require(!(_tranches.length % 2 == 1 || _tranches.length >= MAX_TRANCHES*2)); trancheCount = _tranches.length / 2; uint256 highestAmount = 0; for(uint256 i=0; i<_tranches.length/2; i++) { tranches[i].amount = _tranches[i*2]; tranches[i].price = _tranches[i*2+1]; // No invalid steps require(!((highestAmount != 0) && (tranches[i].amount <= highestAmount))); highestAmount = tranches[i].amount; } // We need to start from zero, otherwise we blow up our deployment require(tranches[0].amount == 0); // Last tranche price must be zero, terminating the crowdale require(tranches[trancheCount-1].price == 0); } /// @dev This is invoked once for every pre-ICO address, set pricePerToken /// to 0 to disable /// @param preicoAddress PresaleFundCollector address /// @param pricePerToken How many weis one token cost for pre-ico investors function setPreicoAddress(address preicoAddress, uint pricePerToken) public onlyOwner { preicoAddresses[preicoAddress] = pricePerToken; } /// @dev Iterate through tranches. You reach end of tranches when price = 0 /// @return tuple (time, price) function getTranche(uint256 n) public constant returns (uint, uint) { return (tranches[n].amount, tranches[n].price); } function getFirstTranche() private constant returns (Tranche) { return tranches[0]; } function getLastTranche() private constant returns (Tranche) { return tranches[trancheCount-1]; } function getPricingStartsAt() public constant returns (uint) { return getFirstTranche().amount; } function getPricingEndsAt() public constant returns (uint) { return getLastTranche().amount; } function isSane(address _crowdsale) public view returns(bool) { // Our tranches are not bound by time, so we can't really check are we sane // so we presume we are ;) // In the future we could save and track raised tokens, and compare it to // the Crowdsale contract. return true; } /// @dev Get the current tranche or bail out if we are not in the tranche periods. /// @param weiRaised total amount of weis raised, for calculating the current tranche /// @return {[type]} [description] function getCurrentTranche(uint256 weiRaised) private constant returns (Tranche) { uint i; for(i=0; i < tranches.length; i++) { if(weiRaised < tranches[i].amount) { return tranches[i-1]; } } } /// @dev Get the current price. /// @param weiRaised total amount of weis raised, for calculating the current tranche /// @return The current price or 0 if we are outside trache ranges function getCurrentPrice(uint256 weiRaised) public constant returns (uint256 result) { return getCurrentTranche(weiRaised).price; } /// @dev Calculate the current price for buy in amount. function calculatePrice(uint256 value, uint256 weiRaised, uint256 tokensSold, address msgSender, uint256 decimals) public constant returns (uint256) { uint256 multiplier = 10 ** decimals; // This investor is coming through pre-ico if(preicoAddresses[msgSender] > 0) { return safeMul(value, multiplier) / preicoAddresses[msgSender]; } uint256 price = getCurrentPrice(weiRaised); return safeMul(value, multiplier) / price; } function() payable public { revert(); // No money on this contract } } /** * Contract to enforce Token Vesting */ contract TokenVesting is Allocatable, SafeMathLib { address public TokenAddress; /** keep track of total tokens yet to be released, * this should be less than or equal to tokens held by this contract. */ uint256 public totalUnreleasedTokens; struct VestingSchedule { uint256 startAt; uint256 principleLockAmount; uint256 principleLockPeriod; uint256 bonusLockAmount; uint256 bonusLockPeriod; uint256 amountReleased; bool isPrincipleReleased; bool isBonusReleased; } mapping (address => VestingSchedule) public vestingMap; event VestedTokensReleased(address _adr, uint256 _amount); function TokenVesting(address _TokenAddress) public { TokenAddress = _TokenAddress; } /** Function to set/update vesting schedule. PS - Amount cannot be changed once set */ function setVesting(address _adr, uint256 _principleLockAmount, uint256 _principleLockPeriod, uint256 _bonusLockAmount, uint256 _bonuslockPeriod) public onlyAllocateAgent { VestingSchedule storage vestingSchedule = vestingMap[_adr]; // data validation require(safeAdd(_principleLockAmount, _bonusLockAmount) > 0); //startAt is set current time as start time. vestingSchedule.startAt = block.timestamp; vestingSchedule.bonusLockPeriod = safeAdd(block.timestamp,_bonuslockPeriod); vestingSchedule.principleLockPeriod = safeAdd(block.timestamp,_principleLockPeriod); // check if enough tokens are held by this contract ERC20 token = ERC20(TokenAddress); uint256 _totalAmount = safeAdd(_principleLockAmount, _bonusLockAmount); require(token.balanceOf(this) >= safeAdd(totalUnreleasedTokens, _totalAmount)); vestingSchedule.principleLockAmount = _principleLockAmount; vestingSchedule.bonusLockAmount = _bonusLockAmount; vestingSchedule.isPrincipleReleased = false; vestingSchedule.isBonusReleased = false; totalUnreleasedTokens = safeAdd(totalUnreleasedTokens, _totalAmount); vestingSchedule.amountReleased = 0; } function isVestingSet(address adr) public constant returns (bool isSet) { return vestingMap[adr].principleLockAmount != 0 || vestingMap[adr].bonusLockAmount != 0; } /** Release tokens as per vesting schedule, called by contributor */ function releaseMyVestedTokens() public { releaseVestedTokens(msg.sender); } /** Release tokens as per vesting schedule, called by anyone */ function releaseVestedTokens(address _adr) public { VestingSchedule storage vestingSchedule = vestingMap[_adr]; uint256 _totalTokens = safeAdd(vestingSchedule.principleLockAmount, vestingSchedule.bonusLockAmount); // check if all tokens are not vested require(safeSub(_totalTokens, vestingSchedule.amountReleased) > 0); // calculate total vested tokens till now uint256 amountToRelease = 0; if (block.timestamp >= vestingSchedule.principleLockPeriod && !vestingSchedule.isPrincipleReleased) { amountToRelease = safeAdd(amountToRelease,vestingSchedule.principleLockAmount); vestingSchedule.amountReleased = safeAdd(vestingSchedule.amountReleased, amountToRelease); vestingSchedule.isPrincipleReleased = true; } if (block.timestamp >= vestingSchedule.bonusLockPeriod && !vestingSchedule.isBonusReleased) { amountToRelease = safeAdd(amountToRelease,vestingSchedule.bonusLockAmount); vestingSchedule.amountReleased = safeAdd(vestingSchedule.amountReleased, amountToRelease); vestingSchedule.isBonusReleased = true; } // transfer vested tokens require(amountToRelease > 0); ERC20 token = ERC20(TokenAddress); token.transfer(_adr, amountToRelease); // decrement overall unreleased token count totalUnreleasedTokens = safeSub(totalUnreleasedTokens, amountToRelease); VestedTokensReleased(_adr, amountToRelease); } }
Iterate through tranches. You reach end of tranches when price = 0 return tuple (time, price)
function getTranche(uint256 n) public constant returns (uint, uint) { return (tranches[n].amount, tranches[n].price); }
10,178,095
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "maki-swap-lib/contracts/math/SafeMath.sol"; import "maki-swap-lib/contracts/token/HRC20/IHRC20.sol"; import "maki-swap-lib/contracts/token/HRC20/SafeHRC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./MakiToken.sol"; import "./SoyBar.sol"; interface IMigratorChef { // Perform LP token migration from legacy MakiSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to MakiSwap LP tokens. // MakiSwap must mint EXACTLY the same amount of Maki LP tokens or // else something bad will happen. Traditional MakiSwap does not // do that so be careful! function migrate(IHRC20 token) external returns (IHRC20); } // MasterChef is the master of Maki. She can make Maki and she is a fair lady. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once MAKI is sufficiently // distributed and the community can show to govern itself. contract MasterChef is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeHRC20 for IHRC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of MAKI // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accMakiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accMakiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IHRC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. MAKIs to distribute per block. uint256 lastRewardBlock; // Last block number that MAKIs distribution occurs. uint256 accMakiPerShare; // Accumulated MAKIs per share, times 1e12. See below. } //** ADDRESSES **// // The MAKI TOKEN! MakiToken public maki; // The SOY TOKEN! SoyBar public soy; // Team address, which recieves 1.5 MAKI per block (mutable by team) address public team = msg.sender; // Treasury address, which recieves 1.5 MAKI per block (mutable by team and treasury) address public treasury = msg.sender; // The migrator contract. It has a lot of power. Can only be set through governance (treasury). IMigratorChef public migrator; // ** GLOBAL VARIABLES ** // // MAKI tokens created per block. uint256 public makiPerBlock = 16e18; // 16 MAKI per block minted // Bonus muliplier for early maki makers. uint256 public bonusMultiplier = 1; // The block number when MAKI mining starts. uint256 public startBlock = block.number; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // ** POOL VARIABLES ** // // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; event Team(address team); event Treasury(address treasury); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( MakiToken _maki, SoyBar _soy ) public { maki = _maki; soy = _soy; // staking pool poolInfo.push( PoolInfo({ lpToken: _maki, allocPoint: 1000, lastRewardBlock: startBlock, accMakiPerShare: 0 }) ); totalAllocPoint = 1000; } modifier validatePoolByPid(uint256 _pid) { require(_pid < poolInfo.length, "pool does not exist"); _; } // VALIDATION -- ELIMINATES POOL DUPLICATION RISK -- NONE function checkPoolDuplicate(IHRC20 _token ) internal view { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].lpToken != _token, "add: existing pool"); } } function updateMultiplier(uint256 multiplierNumber) public { require(msg.sender == treasury, "updateMultiplier: only treasury may update"); bonusMultiplier = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // ADD -- NEW LP TOKEN POOL -- OWNER function add(uint256 _allocPoint, IHRC20 _lpToken, bool _withUpdate) public onlyOwner { checkPoolDuplicate(_lpToken); addPool(_allocPoint, _lpToken, _withUpdate); } function addPool(uint256 _allocPoint, IHRC20 _lpToken, bool _withUpdate) internal { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accMakiPerShare: 0 }) ); updateStakingPool(); } // UPDATE -- ALLOCATION POINT -- OWNER function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner validatePoolByPid(_pid) { require(_pid < poolInfo.length, "set: pool does not exist"); if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add( _allocPoint ); updateStakingPool(); } } // UPDATE -- STAKING POOL -- INTERNAL function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add( points ); poolInfo[0].allocPoint = points; } } // SET -- MIGRATOR CONTRACT -- OWNER function setMigrator(IMigratorChef _migrator) public { require(msg.sender == treasury, "setMigrator: must be from treasury"); migrator = _migrator; } // MIGRATE -- LP TOKENS TO ANOTHER CONTRACT -- MIGRATOR function migrate(uint256 _pid) public validatePoolByPid(_pid) { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IHRC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IHRC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // VIEW -- BONUS MULTIPLIER -- PUBLIC function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(bonusMultiplier); } // VIEW -- PENDING MAKI function pendingMaki(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accMakiPerShare = pool.accMakiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 makiReward = multiplier.mul(makiPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accMakiPerShare = accMakiPerShare.add( makiReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accMakiPerShare).div(1e12).sub(user.rewardDebt); } // UPDATE -- REWARD VARIABLES FOR ALL POOLS (HIGH GAS POSSIBLE) -- PUBLIC function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // UPDATE -- REWARD VARIABLES (POOL) -- PUBLIC function updatePool(uint256 _pid) public validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 makiReward = multiplier.mul(makiPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); uint256 adminFee = makiReward.mul(1000).div(10650); uint256 netReward = makiReward.sub(adminFee.mul(2)); maki.mint(team, adminFee); // 1.50 MAKI per block to team (9.375%) maki.mint(treasury, adminFee); // 1.50 MAKI per block to treasury (9.375%) maki.mint(address(soy), netReward); pool.accMakiPerShare = pool.accMakiPerShare.add( netReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // DEPOSIT -- LP TOKENS -- LP OWNERS function deposit(uint256 _pid, uint256 _amount) public nonReentrant validatePoolByPid(_pid) { require(_pid != 0, "deposit MAKI by staking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { // already deposited assets uint256 pending = user.amount.mul(pool.accMakiPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { // sends pending rewards, if applicable safeMakiTransfer(msg.sender, pending); } } if (_amount > 0) { // if adding more pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMakiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // WITHDRAW -- LP TOKENS -- STAKERS function withdraw(uint256 _pid, uint256 _amount) public nonReentrant validatePoolByPid(_pid) { require(_pid != 0, "withdraw MAKI by unstaking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accMakiPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeMakiTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accMakiPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // STAKE -- MAKI TO MASTERCHEF -- PUBLIC MAKI HOLDERS function enterStaking(uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMakiPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeMakiTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMakiPerShare).div(1e12); soy.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); } // WITHDRAW -- MAKI tokens from STAKING. function leaveStaking(uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accMakiPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeMakiTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accMakiPerShare).div(1e12); soy.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); } // TRANSFER -- TRANSFERS SOY -- INTERNAL function safeMakiTransfer(address _to, uint256 _amount) internal { soy.safeMakiTransfer(_to, _amount); } // UPDATE -- TREASURY ADDRESS -- TREASURY || TEAM function newTreasury(address _treasury) public { require( msg.sender == treasury || msg.sender == team, "treasury: invalid permissions" ); treasury = _treasury; emit Treasury(_treasury); } // UPDATE -- TEAM ADDRESS -- TEAM function newTeam(address _team) public { require(msg.sender == team, "team: le who are you?"); team = _team; emit Team(_team); } }
UPDATE -- ALLOCATION POINT -- OWNER
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner validatePoolByPid(_pid) { require(_pid < poolInfo.length, "set: pool does not exist"); if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add( _allocPoint ); updateStakingPool(); } }
15,849,319
/** *Submitted for verification at Etherscan.io on 2020-03-11 */ pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg interface DharmaTransferFacilitatorV1Interface { event RoleModified(Role indexed role, address account); event RolePaused(Role indexed role); event RoleUnpaused(Role indexed role); enum Role { TRANSFERRER, PAUSER } struct RoleStatus { address account; bool paused; } function enactDDaiTransfer( address senderSmartWallet, address recipientInitialSigningKey, // the receiver's key ring address recipientSmartWallet, uint256 value, uint256 expiration, bytes32 salt, bytes calldata signatures ) external; function deploySenderWalletAndEnactDDaiTransfer( address senderInitialSigningKey, // the sender's key ring address senderSmartWallet, address recipientInitialSigningKey, // the receiver's key ring address recipientSmartWallet, uint256 value, uint256 expiration, bytes32 salt, bytes calldata signatures ) external; function deploySenderKeyRingAndEnactDDaiTransfer( address senderInitialKeyRingSigningKey, // initial key on sender's key ring address senderKeyRing, // the sender's key ring address senderSmartWallet, address recipientInitialSigningKey, // the receiver's key ring address recipientSmartWallet, uint256 value, uint256 expiration, bytes32 salt, bytes calldata signatures ) external; function deploySenderKeyRingAndWalletAndEnactDDaiTransfer( address senderInitialKeyRingSigningKey, // initial key on sender's key ring address senderKeyRing, // the sender's key ring address senderSmartWallet, address recipientInitialSigningKey, // the receiver's key ring address recipientSmartWallet, uint256 value, uint256 expiration, bytes32 salt, bytes calldata signatures ) external; function withdraw( ERC20Interface token, address recipient, uint256 amount ) external returns (bool success); function callGeneric( address payable target, uint256 amount, bytes calldata data ) external returns (bool ok, bytes memory returnData); function setLimit(uint256 daiAmount) external; function setRole(Role role, address account) external; function removeRole(Role role) external; function pause(Role role) external; function unpause(Role role) external; function isPaused(Role role) external view returns (bool paused); function isRole(Role role) external view returns (bool hasRole); function getTransferrer() external view returns (address transferrer); function getPauser() external view returns (address pauser); function getLimit() external view returns ( uint256 daiAmount, uint256 dDaiAmount ); function isDharmaSmartWallet( address smartWallet, address initialUserSigningKey ) external pure returns (bool dharmaSmartWallet); } interface ERC20Interface { function balanceOf(address) external view returns (uint256); function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); } interface DTokenInterface { function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool success); function modifyAllowanceViaMetaTransaction( address owner, address spender, uint256 value, uint256 expiration, bytes32 salt, bytes calldata signatures ) external returns (bool success); function approve(address, uint256) external returns (bool); function exchangeRateCurrent() external view returns (uint256); function getMetaTransactionMessageHash( bytes4 functionSelector, bytes calldata arguments, uint256 expiration, bytes32 salt ) external view returns (bytes32 digest, bool valid); function allowance(address, address) external view returns (uint256); } interface DharmaSmartWalletFactoryV1Interface { function newSmartWallet( address userSigningKey ) external returns (address wallet); function getNextSmartWallet( address userSigningKey ) external view returns (address wallet); } interface DharmaKeyRingFactoryV2Interface { function newKeyRing( address userSigningKey, address targetKeyRing ) external returns (address keyRing); function getNextKeyRing( address userSigningKey ) external view returns (address targetKeyRing); } library SafeMath { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } } /** * @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. * * In order to transfer ownership, a recipient must be specified, at which point * the specified recipient can call `acceptOwnership` and take ownership. */ contract TwoStepOwnable { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); address private _owner; address private _newPotentialOwner; /** * @dev Initialize contract by setting transaction submitter as initial owner. */ constructor() internal { _owner = tx.origin; emit OwnershipTransferred(address(0), _owner); } /** * @dev Allows a new account (`newOwner`) to accept ownership. * Can only be called by the current owner. */ function transferOwnership(address newOwner) external onlyOwner { require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } /** * @dev Cancel a transfer of ownership to a new account. * Can only be called by the current owner. */ function cancelOwnershipTransfer() external onlyOwner { delete _newPotentialOwner; } /** * @dev Transfers ownership of the contract to the caller. * Can only be called by a new potential owner set by the current owner. */ function acceptOwnership() external { require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OwnershipTransferred(_owner, msg.sender); _owner = msg.sender; } /** * @dev Returns the address of the current owner. */ function owner() external view returns (address) { return _owner; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "TwoStepOwnable: caller is not the owner."); _; } } /** * @title DharmaTransferFacilitatorV1 * @author 0age * @notice This contract is owned by Dharma and used to facilitate peer-to-peer * payments on the platform. It designates a collection of "roles" - these * are dedicated accounts that can be modified by the owner, and that can * trigger specific functionality on the contract. These roles are: * - transferrer (0): initiates token transfers between smart wallets by designating a recipient and transferring on behalf of the sender * - pauser (1): pauses any role (only the owner is then able to unpause it) * * When making transfers, the transferrer must adhere to two constraints: * - it must provide "proof" that the recipient is a smart wallet by including * the initial user signing key used to derive the smart wallet address * - it must not attempt to transfer more Dai, or more than the Dai-equivalent * value of Dharma Dai, than the current "limit" set by the owner. * * Smart wallet "proofs" can be validated via `isSmartWallet`. */ contract DharmaTransferFacilitatorV1 is DharmaTransferFacilitatorV1Interface, TwoStepOwnable { using SafeMath for uint256; // Maintain a role status mapping with assigned accounts and paused states. mapping(uint256 => RoleStatus) private _roles; // Maintain a maximum allowable transfer size (in Dai) for the transferrer. uint256 private _limit; // This contract interacts with Dai and Dharma Dai. ERC20Interface internal constant _DAI = ERC20Interface( 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet ); DTokenInterface internal constant _DDAI = DTokenInterface( 0x00000000001876eB1444c986fD502e618c587430 ); // The "Create2 Header" is used to compute smart wallet deployment addresses. bytes21 internal constant _CREATE2_HEADER = bytes21( 0xfffc00c80b0000007f73004edb00094cad80626d8d // control character + factory ); // The "Wallet creation code" header & footer are also used to derive wallets. bytes internal constant _WALLET_CREATION_CODE_HEADER = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906e26750c571ce882b17016557279adaa9083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906e26750c571ce882b17016557279adaa9083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a7231582020202020202055706772616465426561636f6e50726f7879563120202020202064736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; bytes28 internal constant _WALLET_CREATION_CODE_FOOTER = bytes28( 0x00000000000000000000000000000000000000000000000000000000 ); DharmaSmartWalletFactoryV1Interface internal constant _WALLET_FACTORY = ( DharmaSmartWalletFactoryV1Interface( 0xfc00C80b0000007F73004edB00094caD80626d8D ) ); DharmaKeyRingFactoryV2Interface internal constant _KEYRING_FACTORY = ( DharmaKeyRingFactoryV2Interface( 0x2484000059004afB720000dc738434fA6200F49D ) ); // Use the smart wallet instance runtime code hash to verify expected targets. bytes32 internal constant _SMART_WALLET_INSTANCE_RUNTIME_HASH = bytes32( 0xe25d4f154acb2394ee6c18d64fb5635959ba063d57f83091ec9cf34be16224d7 ); // The keyring instance runtime code hash is used to verify expected targets. bytes32 internal constant _KEY_RING_INSTANCE_RUNTIME_HASH = bytes32( 0xb15b24278e79e856d35b262e76ff7d3a759b17e625ff72adde4116805af59648 ); /** * @notice In the constructor, set the initial owner to the transaction * submitter and cap the size of transfers to 300 dai worth of dDai. */ constructor() public { // Set the initial limit to 300 Dai. _limit = 300 * 1e18; } /** * @notice Prove that `recipientSmartWallet` is a Dharma smart wallet address * using `recipientInitialSigningKey`, attempt to modify the allowance of this * contract for the sender using the meta-transaction via `senderSmartWallet`, * `value`, `expiration`, `salt`, and `signatures`, then transfer `value` dDai * from the sender to the recipient, reverting on failure. Only the owner or * the transferrer role may call this function. * @param senderSmartWallet address The wallet of the sender. * @param recipientInitialSigningKey address The input to recipient's wallet. * @param recipientSmartWallet address The wallet of the recipient. * @param value uint256 The amount of dDai to approve and transfer. * @param expiration uint256 The timestamp where the meta-transaction expires. * @param salt bytes32 The salt associated with the meta-transaction. * @param signatures bytes The signature or signatures associated with the * meta-transaction. */ function enactDDaiTransfer( address senderSmartWallet, address recipientInitialSigningKey, // the receiver's key ring address recipientSmartWallet, uint256 value, uint256 expiration, bytes32 salt, bytes calldata signatures ) external onlyOwnerOr(Role.TRANSFERRER) { // Ensure that the receiver has a Dharma Smart Wallet (deployed or not). require( _isSmartWallet(recipientSmartWallet, recipientInitialSigningKey), "Could not resolve receiver's smart wallet using provided signing key." ); // Attempt to modify the allowance. _tryApprovalViaMetaTransaction( senderSmartWallet, value, expiration, salt, signatures ); // Make the transfer from the sender's smart wallet to the receiver's. bool ok = _DDAI.transferFrom(senderSmartWallet, recipientSmartWallet, value); require(ok, "Dharma Dai transfer failed."); } /** * @notice Prove that `recipientSmartWallet` is a Dharma smart wallet address * using `recipientInitialSigningKey`, deploy sender's smart wallet (unless it * is already deployed) using `senderInitialSigningKey`, attempt to modify the * allowance of this contract for the sender using the meta-transaction via * `senderSmartWallet`, `value`, `expiration`, `salt`, and `signatures`, then * transfer `value` dDai from the sender to the recipient, reverting on * failure. Only the owner or the transferrer role may call this function. * @param senderInitialSigningKey address The sender's key ring, used as the * input to the smart wallet deployment. * @param senderSmartWallet address The wallet of the sender. * @param recipientInitialSigningKey address The input to recipient's wallet. * @param recipientSmartWallet address The wallet of the recipient. * @param value uint256 The amount of dDai to approve and transfer. * @param expiration uint256 The timestamp where the meta-transaction expires. * @param salt bytes32 The salt associated with the meta-transaction. * @param signatures bytes The signature or signatures associated with the * meta-transaction. */ function deploySenderWalletAndEnactDDaiTransfer( address senderInitialSigningKey, // the sender's key ring address senderSmartWallet, address recipientInitialSigningKey, // the receiver's key ring address recipientSmartWallet, uint256 value, uint256 expiration, bytes32 salt, bytes calldata signatures ) external onlyOwnerOr(Role.TRANSFERRER) { // Ensure the recipient is valid and that dDai amount is under the limit. _enforceRecipientAndValue( recipientSmartWallet, recipientInitialSigningKey, value ); // Deploy the sender's smart wallet if necessary. _deployNewSmartWalletIfNeeded(senderInitialSigningKey, senderSmartWallet); // Attempt to modify the allowance. _tryApprovalViaMetaTransaction( senderSmartWallet, value, expiration, salt, signatures ); // Make the transfer from the sender's smart wallet to the receiver's. bool ok = _DDAI.transferFrom(senderSmartWallet, recipientSmartWallet, value); require(ok, "Dharma Dai transfer failed."); } /** * @notice Prove that `recipientSmartWallet` is a Dharma smart wallet address * using `recipientInitialSigningKey`, deploy sender's key ring (unless it is * already deployed) using `senderInitialKeyRingSigningKey`, attempt to modify * the allowance of this contract for the sender using the meta-transaction * via `senderSmartWallet`, `value`, `expiration`, `salt`, and `signatures`, * then transfer `value` dDai from the sender to the recipient, reverting on * failure. Only the owner or the transferrer role may call this function. * @param senderInitialKeyRingSigningKey address The input to the key ring. * @param senderKeyRing address The sender's keyring; the smart wallet input. * @param senderSmartWallet address The wallet of the sender. * @param recipientInitialSigningKey address The input to recipient's wallet. * @param recipientSmartWallet address The wallet of the recipient. * @param value uint256 The amount of dDai to approve and transfer. * @param expiration uint256 The timestamp where the meta-transaction expires. * @param salt bytes32 The salt associated with the meta-transaction. * @param signatures bytes The signature or signatures associated with the * meta-transaction. */ function deploySenderKeyRingAndEnactDDaiTransfer( address senderInitialKeyRingSigningKey, // initial key on sender's key ring address senderKeyRing, // the sender's key ring address senderSmartWallet, address recipientInitialSigningKey, // the receiver's key ring address recipientSmartWallet, uint256 value, uint256 expiration, bytes32 salt, bytes calldata signatures ) external onlyOwnerOr(Role.TRANSFERRER) { // Ensure the recipient is valid and that dDai amount is under the limit. _enforceRecipientAndValue( recipientSmartWallet, recipientInitialSigningKey, value ); // Deploy the sender's key ring if necessary. _deployNewKeyRingIfNeeded(senderInitialKeyRingSigningKey, senderKeyRing); // Attempt to modify the allowance. _tryApprovalViaMetaTransaction( senderSmartWallet, value, expiration, salt, signatures ); // Make the transfer from the sender's smart wallet to the receiver's. bool ok = _DDAI.transferFrom(senderSmartWallet, recipientSmartWallet, value); require(ok, "Dharma Dai transfer failed."); } /** * @notice Prove that `recipientSmartWallet` is a Dharma smart wallet address * using `recipientInitialSigningKey`, deploy sender's key ring (unless it is * already deployed) using `senderInitialKeyRingSigningKey`, deploy sender's * smart wallet (unless it is already deployed) using `senderKeyRing`, attempt * to modify the allowance of this contract for the sender using the * meta-transaction via `senderSmartWallet`, `value`, `expiration`, `salt`, * and `signatures`, then transfer `value` dDai from the sender to the * recipient, reverting on failure. Only the owner or the transferrer role may * call this function. * @param senderInitialKeyRingSigningKey address The input to the key ring. * @param senderKeyRing address The sender's keyring; the smart wallet input. * @param senderSmartWallet address The wallet of the sender. * @param recipientInitialSigningKey address The input to recipient's wallet. * @param recipientSmartWallet address The wallet of the recipient. * @param value uint256 The amount of dDai to approve and transfer. * @param expiration uint256 The timestamp where the meta-transaction expires. * @param salt bytes32 The salt associated with the meta-transaction. * @param signatures bytes The signature or signatures associated with the * meta-transaction. */ function deploySenderKeyRingAndWalletAndEnactDDaiTransfer( address senderInitialKeyRingSigningKey, // initial key on sender's key ring address senderKeyRing, // the sender's key ring address senderSmartWallet, address recipientInitialSigningKey, // the receiver's key ring address recipientSmartWallet, uint256 value, uint256 expiration, bytes32 salt, bytes calldata signatures ) external onlyOwnerOr(Role.TRANSFERRER) { // Ensure the recipient is valid and that dDai amount is under the limit. _enforceRecipientAndValue( recipientSmartWallet, recipientInitialSigningKey, value ); // Deploy the sender's key ring if necessary. _deployNewKeyRingIfNeeded(senderInitialKeyRingSigningKey, senderKeyRing); // Deploy the sender's smart wallet if necessary. _deployNewSmartWalletIfNeeded(senderKeyRing, senderSmartWallet); // Attempt to modify the allowance. _tryApprovalViaMetaTransaction( senderSmartWallet, value, expiration, salt, signatures ); // Make the transfer from the sender's smart wallet to the receiver's. bool ok = _DDAI.transferFrom(senderSmartWallet, recipientSmartWallet, value); require(ok, "Dharma Dai transfer failed."); } /** * @notice Transfer `amount` of ERC20 token `token` to `recipient`. Only the * owner may call this function. * @param token ERC20Interface The ERC20 token to transfer. * @param recipient address The account to transfer the tokens to. * @param amount uint256 The amount of tokens to transfer. * @return A boolean to indicate if the transfer was successful - note that * unsuccessful ERC20 transfers will usually revert. */ function withdraw( ERC20Interface token, address recipient, uint256 amount ) external onlyOwner returns (bool success) { // Transfer the token to the specified recipient. success = token.transfer(recipient, amount); } /** * @notice Call account `target`, supplying value `amount` and data `data`. * Only the owner may call this function. * @param target address The account to call. * @param amount uint256 The amount of ether to include as an endowment. * @param data bytes The data to include along with the call. * @return A boolean to indicate if the call was successful, as well as the * returned data or revert reason. */ function callGeneric( address payable target, uint256 amount, bytes calldata data ) external onlyOwner returns (bool ok, bytes memory returnData) { // Call the specified target and supply the specified data. (ok, returnData) = (false, bytes(msg.data)); target.call.value(amount)(data); //inject UNHANDLED EXCEPTION } /** * @notice Set `daiAmount` as the new limit on the size of finalized deposits. * Only the owner may call this function. * @param daiAmount uint256 The new limit on the size of finalized deposits. */ function setLimit(uint256 daiAmount) external onlyOwner { // Set the new limit. _limit = daiAmount; } /** * @notice Pause a currently unpaused role and emit a `RolePaused` event. Only * the owner or the designated pauser may call this function. Also, bear in * mind that only the owner may unpause a role once paused. * @param role The role to pause. Permitted roles are transferrer (0) and * pauser (1). */ function pause(Role role) external onlyOwnerOr(Role.PAUSER) { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(!storedRoleStatus.paused, "Role in question is already paused."); storedRoleStatus.paused = true; emit RolePaused(role); } /** * @notice Unpause a currently paused role and emit a `RoleUnpaused` event. * Only the owner may call this function. * @param role The role to pause. Permitted roles are transferrer (0) and * pauser (1). */ function unpause(Role role) external onlyOwner { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(storedRoleStatus.paused, "Role in question is already unpaused."); storedRoleStatus.paused = false; emit RoleUnpaused(role); } /** * @notice Set a new account on a given role and emit a `RoleModified` event * if the role holder has changed. Only the owner may call this function. * @param role The role that the account will be set for. Permitted roles are * transferrer (0) and pauser (1). * @param account The account to set as the designated role bearer. */ function setRole(Role role, address account) external onlyOwner { require(account != address(0), "Must supply an account."); _setRole(role, account); } /** * @notice Remove any current role bearer for a given role and emit a * `RoleModified` event if a role holder was previously set. Only the owner * may call this function. * @param role The role that the account will be removed from. Permitted roles * are transferrer (0) and pauser (1). */ function removeRole(Role role) external onlyOwner { _setRole(role, address(0)); } /** * @notice External view function to check whether or not the functionality * associated with a given role is currently paused or not. The owner or the * pauser may pause any given role (including the pauser itself), but only the * owner may unpause functionality. Additionally, the owner may call paused * functions directly. * @param role The role to check the pause status on. Permitted roles are * transferrer (0) and pauser (1). * @return A boolean to indicate if the functionality associated with the role * in question is currently paused. */ function isPaused(Role role) external view returns (bool paused) { paused = _isPaused(role); } /** * @notice External view function to check whether the caller is the current * role holder. * @param role The role to check for. Permitted roles are transferrer (0) and * pauser (1). * @return A boolean indicating if the caller has the specified role. */ function isRole(Role role) external view returns (bool hasRole) { hasRole = _isRole(role); } /** * @notice External view function to check the account currently holding the * transferrer role. The transferrer can process transfers using unordered * approval meta-transactions and in doing so specify the recipient, but it * must prove that the recipient is a Dharma Smart Wallet and adhere to the * current limit. * @return The address of the current transferrer, or the null address if none * is set. */ function getTransferrer() external view returns (address transferrer) { transferrer = _roles[uint256(Role.TRANSFERRER)].account; } /** * @notice External view function to check the account currently holding the * pauser role. The pauser can pause any role from taking its standard action, * though the owner will still be able to call the associated function in the * interim and is the only entity able to unpause the given role once paused. * @return The address of the current pauser, or the null address if none is * set. */ function getPauser() external view returns (address pauser) { pauser = _roles[uint256(Role.PAUSER)].account; } /** * @notice External view function to check the current limit on transfer * amount enforced for the transferrer, expressed in Dai and in Dharma Dai. * @return The Dai and Dharma Dai limit on transfer amount. */ function getLimit() external view returns ( uint256 daiAmount, uint256 dDaiAmount ) { daiAmount = _limit; dDaiAmount = (daiAmount.mul(1e18)).div(_DDAI.exchangeRateCurrent()); } /** * @notice External pure function to check whether a "proof" that a given * smart wallet is actually a Dharma Smart Wallet, based on the initial user * signing key, is valid or not. This proof only works when the Dharma Smart * Wallet in question is derived using V1 of the Dharma Smart Wallet Factory. * @param smartWallet address The smart wallet to check. * @param initialUserSigningKey address The initial user signing key supplied * when deriving the smart wallet address - this could be an EOA or a Dharma * key ring address. * @return A boolean indicating if the specified smart wallet account is * indeed a smart wallet based on the specified initial user signing key. */ function isDharmaSmartWallet( address smartWallet, address initialUserSigningKey ) external pure returns (bool dharmaSmartWallet) { dharmaSmartWallet = _isSmartWallet(smartWallet, initialUserSigningKey); } /** * @notice Internal function to set a new account on a given role and emit a * `RoleModified` event if the role holder has changed. * @param role The role that the account will be set for. Permitted roles are * transferrer (0) and pauser (1). * @param account The account to set as the designated role bearer. */ function _setRole(Role role, address account) internal { RoleStatus storage storedRoleStatus = _roles[uint256(role)]; if (account != storedRoleStatus.account) { storedRoleStatus.account = account; emit RoleModified(role, account); } } /** * @notice Internal function to set an approval, or to continue if a given * metatransaction has been used for an approval before but allowance is still * set (for instance, by a griefer that has lifted it from calldata while the * transaction is still in the mempool and used it to frontrun the call). If * one of these steps fails, revert. * @param senderSmartWallet address The wallet of the sender. * @param value uint256 The amount of dDai to approve. * @param expiration uint256 The timestamp where the meta-transaction expires. * @param salt bytes32 The salt associated with the meta-transaction. * @param signatures bytes The signature or signatures associated with the * meta-transaction. */ function _tryApprovalViaMetaTransaction( address senderSmartWallet, uint256 value, uint256 expiration, bytes32 salt, bytes memory signatures ) internal { // Attempt to modify the allowance. (bool ok, bytes memory returnData) = (false, bytes(msg.data)); address(_DDAI).call( abi.encodeWithSelector( _DDAI.modifyAllowanceViaMetaTransaction.selector, senderSmartWallet, address(this), value, true, // increase expiration, salt, signatures ) ); //inject UNHANDLED EXCEPTION // Protect against griefing via frontrunning by handling specific reverts. if (!ok) { // Determine whether the meta-transaction in question has been used yet. (, bool valid) = _DDAI.getMetaTransactionMessageHash( _DDAI.modifyAllowanceViaMetaTransaction.selector, abi.encode(senderSmartWallet, address(this), value, true), expiration, salt ); // Revert with the original message if it has not been used. if (valid) { assembly { revert(add(32, returnData), mload(returnData)) } } // If it has been used, determine if there is still sufficient allowance. uint256 allowance = _DDAI.allowance(senderSmartWallet, address(this)); // Revert with the original message if allowance is insufficient. if (allowance < value) { assembly { revert(add(32, returnData), mload(returnData)) } } } } /** * @notice Internal function to deploy a key ring if needed. If expected key * ring address does not match the next key ring address, revert. */ function _deployNewKeyRingIfNeeded( address initialSigningKey, address expectedKeyRing ) internal returns (address keyRing) { // Only deploy if a smart wallet doesn't already exist at expected address. bytes32 hash; assembly { hash := extcodehash(expectedKeyRing) } if (hash != _KEY_RING_INSTANCE_RUNTIME_HASH) { require( _KEYRING_FACTORY.getNextKeyRing(initialSigningKey) == expectedKeyRing, "Key ring to be deployed does not match expected key ring." ); keyRing = _KEYRING_FACTORY.newKeyRing(initialSigningKey, expectedKeyRing); } else { // Note: the key ring at the expected address may have been modified so that // the supplied user signing key is no longer a valid key - therefore, treat // this helper as a way to protect against race conditions, not as a primary // mechanism for interacting with key ring contracts. keyRing = expectedKeyRing; } } /** * @notice Internal function to deploy a smart wallet if needed. If expected * smart wallet address does not match the next smart wallet address, revert. */ function _deployNewSmartWalletIfNeeded( address userSigningKey, // the key ring address expectedSmartWallet ) internal returns (address smartWallet) { // Only deploy if a smart wallet doesn't already exist at expected address. bytes32 hash; assembly { hash := extcodehash(expectedSmartWallet) } if (hash != _SMART_WALLET_INSTANCE_RUNTIME_HASH) { require( _WALLET_FACTORY.getNextSmartWallet(userSigningKey) == expectedSmartWallet, "Smart wallet to be deployed does not match expected smart wallet." ); smartWallet = _WALLET_FACTORY.newSmartWallet(userSigningKey); } else { // Note: the smart wallet at the expected address may have been modified // so that the supplied user signing key is no longer a valid key. // Therefore, treat this helper as a way to protect against race // conditions, not as a primary mechanism for interacting with smart // wallet contracts. smartWallet = expectedSmartWallet; } } /** * @notice Internal view function to ensure that a recipient is a valid target * for the transferrer to select and that the value being transferred does not * exceed the current limit. */ function _enforceRecipientAndValue( address recipient, address recipientInitialSigningKey, uint256 dDaiAmount ) internal view { // Ensure that the recipient is indeed a smart wallet. require( _isSmartWallet(recipient, recipientInitialSigningKey), "Could not resolve smart wallet using provided signing key." ); // Get the current dDai exchange rate. uint256 exchangeRate = _DDAI.exchangeRateCurrent(); // Ensure that an exchange rate was actually returned. require(exchangeRate != 0, "Could not retrieve dDai exchange rate."); // Get the equivalent Dai amount of the transfer. uint256 daiEquivalent = (dDaiAmount.mul(exchangeRate)) / 1e18; // Ensure that the amount to transfer is lower than the limit. require(daiEquivalent < _limit, "Transfer size exceeds the limit."); } /** * @notice Internal view function to check whether the caller is the current * role holder. * @param role The role to check for. Permitted roles are transferrer (0) and * pauser (1). * @return A boolean indicating if the caller has the specified role. */ function _isRole(Role role) internal view returns (bool hasRole) { hasRole = msg.sender == _roles[uint256(role)].account; } /** * @notice Internal view function to check whether the given role is paused or * not. * @param role The role to check for. Permitted roles are transferrer (0) and * pauser (1). * @return A boolean indicating if the specified role is paused or not. */ function _isPaused(Role role) internal view returns (bool paused) { paused = _roles[uint256(role)].paused; } /** * @notice Internal view function to enforce that the given initial user * signing key resolves to the given smart wallet when deployed through the * Dharma Smart Wallet Factory V1. * @param smartWallet address The smart wallet. * @param initialUserSigningKey address The initial user signing key. */ function _isSmartWallet( address smartWallet, address initialUserSigningKey ) internal pure returns (bool) { // Derive the keccak256 hash of the smart wallet initialization code. bytes32 initCodeHash = keccak256( abi.encodePacked( _WALLET_CREATION_CODE_HEADER, initialUserSigningKey, _WALLET_CREATION_CODE_FOOTER ) ); // Attempt to derive a smart wallet address that matches the one provided. address target; for (uint256 nonce = 0; nonce < 10; nonce++) { target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using all inputs. abi.encodePacked( // pack all inputs to the hash together. _CREATE2_HEADER, // pass in control character + factory address. nonce, // pass in current nonce as the salt. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); // Exit early if the provided smart wallet matches derived target address. if (target == smartWallet) { return true; } // Otherwise, increment the nonce and derive a new salt. nonce++; } // Explicity recognize no target was found matching provided smart wallet. return false; } /** * @notice Modifier that throws if called by any account other than the owner * or the supplied role, or if the caller is not the owner and the role in * question is paused. * @param role The role to require unless the caller is the owner. Permitted * roles are transferrer (0) and pauser (1). */ modifier onlyOwnerOr(Role role) { if (!isOwner()) { require(_isRole(role), "Caller does not have a required role."); require(!_isPaused(role), "Role in question is currently paused."); } _; } }
Call account `target`, supplying value `amount` and data `data`. Only the owner may call this function. target address The account to call. amount uint256 The amount of ether to include as an endowment. data bytes The data to include along with the call. return A boolean to indicate if the call was successful, as well as the returned data or revert reason./ Call the specified target and supply the specified data.
function callGeneric( address payable target, uint256 amount, bytes calldata data ) external onlyOwner returns (bool ok, bytes memory returnData) { (ok, returnData) = (false, bytes(msg.data)); }
12,753,272
// SPDX-License-Identifier: AGPL-3.0 // Feel free to change the license, but this is what we use // Feel free to change this version of Solidity. We support >=0.6.0 <0.7.0; pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // These are the core Yearn libraries import { BaseStrategy, StrategyParams } from "@yearnvaults/contracts/BaseStrategy.sol"; import "@openzeppelinV3/contracts/token/ERC20/IERC20.sol"; import "@openzeppelinV3/contracts/math/SafeMath.sol"; import "@openzeppelinV3/contracts/utils/Address.sol"; import "@openzeppelinV3/contracts/token/ERC20/SafeERC20.sol"; // Import interfaces for many popular DeFi projects, or add your own! //import "../interfaces/<protocol>/<Interface>.sol"; contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; constructor(address _vault) public BaseStrategy(_vault) { // You can set these parameters on deployment to whatever you want // minReportDelay = 6300; // profitFactor = 100; // debtThreshold = 0; } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external override pure returns (string memory) { // Add your own name here, suggestion e.g. "StrategyCreamYFI" return "Strategy<ProtocolName><TokenType>"; } /* * Provide an accurate estimate for the total amount of assets (principle + return) * that this strategy is currently managing, denominated in terms of `want` tokens. * This total should be "realizable" e.g. the total value that could *actually* be * obtained from this strategy if it were to divest it's entire position based on * current on-chain conditions. * * NOTE: care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through flashloan * attacks, oracle manipulations, or other DeFi attack mechanisms). * * NOTE: It is up to governance to use this function in order to correctly order * this strategy relative to its peers in order to minimize losses for the * Vault based on sudden withdrawals. This value should be higher than the * total debt of the strategy and higher than it's expected value to be "safe". */ function estimatedTotalAssets() public override view returns (uint256) { // TODO: Build a more accurate estimate using the value of all positions in terms of `want` return want.balanceOf(address(this)); } /* * Perform any strategy unwinding or other calls necessary to capture the "free return" * this strategy has generated since the last time it's core position(s) were adjusted. * Examples include unwrapping extra rewards. This call is only used during "normal operation" * of a Strategy, and should be optimized to minimize losses as much as possible. This method * returns any realized profits and/or realized losses incurred, and should return the total * amounts of profits/losses/debt payments (in `want` tokens) for the Vault's accounting * (e.g. `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. It is okay for it * to be less than `_debtOutstanding`, as that should only used as a guide for how much * is left to pay back. Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // TODO: Do stuff here to free up any returns back into `want` // NOTE: Return `_profit` which is value generated by all positions, priced in `want` // NOTE: Should try to free up at least `_debtOutstanding` of underlying position } /* * Perform any adjustments to the core position(s) of this strategy given * what change the Vault made in the "investable capital" available to the * strategy. Note that all "free capital" in the strategy after the report * was made is available for reinvestment. Also note that this number could * be 0, and you should handle that scenario accordingly. */ function adjustPosition(uint256 _debtOutstanding) internal override { // TODO: Do something to invest excess `want` tokens (from the Vault) into your positions // NOTE: Try to adjust positions so that `_debtOutstanding` can be freed up on *next* harvest (not immediately) } /* * Make as much capital as possible "free" for the Vault to take. Some * slippage is allowed. The goal is for the strategy to divest as quickly as possible * while not suffering exorbitant losses. This function is used during emergency exit * instead of `prepareReturn()`. This method returns any realized losses incurred, and * should also return the amount of `want` tokens available to repay outstanding debt * to the Vault. */ function exitPosition(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment) { // TODO: Do stuff here to free up as much as possible of all positions back into `want` // TODO: returns any realized profit/losses incurred, and should also return the amount // of `want` tokens available to repay back to the Vault. } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amountNeeded`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed) { // TODO: Do stuff here to free up to `_amountNeeded` from all positions back into `want` // NOTE: Return `_amountFreed`, which should be `<= _amountNeeded` } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary /* * Do anything necesseary to prepare this strategy for migration, such * as transfering any reserve or LP tokens, CDPs, or other tokens or stores of value. */ function prepareMigration(address _newStrategy) internal override { // TODO: Transfer any non-`want` tokens to the new strategy // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one } // Override this to add all tokens/tokenized positions this contract manages // on a *persistent* basis (e.g. not just for swapping back to want ephemerally) // NOTE: Do *not* include `want`, already included in `sweep` below // // Example: // // function protectedTokens() internal override view returns (address[] memory) { // address[] memory protected = new address[](3); // protected[0] = tokenA; // protected[1] = tokenB; // protected[2] = tokenC; // return protected; // } function protectedTokens() internal override view returns (address[] memory) {} }
Perform any strategy unwinding or other calls necessary to capture the "free return" this strategy has generated since the last time it's core position(s) were adjusted. Examples include unwrapping extra rewards. This call is only used during "normal operation" of a Strategy, and should be optimized to minimize losses as much as possible. This method returns any realized profits and/or realized losses incurred, and should return the total amounts of profits/losses/debt payments (in `want` tokens) for the Vault's accounting (e.g. `want.balanceOf(this) >= _debtPayment + _profit - _loss`). NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. It is okay for it to be less than `_debtOutstanding`, as that should only used as a guide for how much is left to pay back. Payments should be made to minimize loss from slippage, debt, withdrawal fees, etc./ TODO: Do stuff here to free up any returns back into `want` NOTE: Return `_profit` which is value generated by all positions, priced in `want` NOTE: Should try to free up at least `_debtOutstanding` of underlying position
function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { }
1,754,288
./partial_match/44787/0xC91861F105ef19a5DF133221EFc6e58322014251/sources/contracts/v4/ExchangeService.sol
Tokens are sent to the basket service, where they are held. The value of a given token is dependent on all the tokens supported by the exchange and the value returned by its current price in Celo (e.G. the cUSD, assuming 1 cUSD = USD). In return the sender will receive a fixed amount Nylon from the basket service. Requirements: - given token must exist on the exchange service. - price feed related to the token must exist on the exchange. - sufficient token balance of the sender must be present. {exchange} is callable by anyone./
function exchange(address _token, uint256 _amount) external sufficientBalance(_token, _amount) { uint256 fixedAmount = SafeMath.div(_amount, 2); (, , uint256 price) = _amount.valueOf(_evaluatePrice(_token)); uint256 variableAmount = SafeMath.div(price, 2); uint256 totalAmount = SafeMath.add(fixedAmount, variableAmount); if (_token == address(cUSD)) { require( cUSD.balanceOf(address(this)) > fixedAmount, "cUSD balance of exchange service is insufficient!" ); require( cEUR.balanceOf(address(this)) > variableAmount, "cEUR balance of exchange service is insufficient!" ); cUSD.safeTransfer(address(this), _amount); cUSD.safeTransfer(address(basket), fixedAmount); cEUR.safeTransfer(address(basket), variableAmount); require( cEUR.balanceOf(address(this)) > fixedAmount, "cEUR balance of exchange service is insufficient!" ); require( cUSD.balanceOf(address(this)) > variableAmount, "cUSD balance of exchange service is insufficient!" ); cEUR.safeTransfer(address(this), _amount); cEUR.safeTransfer(address(basket), fixedAmount); cUSD.safeTransfer(address(basket), variableAmount); } basket.transferNylon(_msgSender(), totalAmount); }
16,956,814
// SPDX-License-Identifier: MIT pragma solidity =0.8.10; import "../../utils/TokenUtils.sol"; import "../ActionBase.sol"; import "./helpers/ReflexerHelper.sol"; /// @title Supply collateral to a Reflexer safe contract ReflexerSupply is ActionBase, ReflexerHelper { using TokenUtils for address; struct Params { uint256 safeId; uint256 amount; address adapterAddr; address from; } /// @inheritdoc ActionBase function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable override returns (bytes32) { Params memory inputData = parseInputs(_callData); inputData.safeId = _parseParamUint(inputData.safeId, _paramMapping[0], _subData, _returnValues); inputData.amount = _parseParamUint(inputData.amount, _paramMapping[1], _subData, _returnValues); inputData.adapterAddr = _parseParamAddr(inputData.adapterAddr, _paramMapping[2], _subData, _returnValues); inputData.from = _parseParamAddr(inputData.from, _paramMapping[3], _subData, _returnValues); (uint256 returnAmount, bytes memory logData) = _reflexerSupply(inputData.safeId, inputData.amount, inputData.adapterAddr, inputData.from); emit ActionEvent("ReflexerSupply", logData); return bytes32(returnAmount); } /// @inheritdoc ActionBase function executeActionDirect(bytes memory _callData) public payable override { Params memory inputData = parseInputs(_callData); (, bytes memory logData) = _reflexerSupply(inputData.safeId, inputData.amount, inputData.adapterAddr, inputData.from); logger.logActionDirectEvent("ReflexerSupply", logData); } /// @inheritdoc ActionBase function actionType() public pure override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice Supplies collateral to the safe /// @param _safeId Id of the safe /// @param _amount Amount of tokens to supply /// @param _adapterAddr Adapter address of the reflexer collateral /// @param _from Address where to pull the collateral from function _reflexerSupply( uint256 _safeId, uint256 _amount, address _adapterAddr, address _from ) internal returns (uint256, bytes memory) { address tokenAddr = getTokenFromAdapter(_adapterAddr); // if amount type(uint).max, pull current _from balance if (_amount == type(uint256).max) { _amount = tokenAddr.getBalance(_from); } // Pull the underlying token and adapter the reflexer adapter pool tokenAddr.pullTokensIfNeeded(_from, _amount); tokenAddr.approveToken(_adapterAddr, _amount); IBasicTokenAdapters(_adapterAddr).join(address(this), _amount); int256 convertAmount = toPositiveInt(_amount); // Supply to the safe balance safeEngine.modifySAFECollateralization( safeManager.collateralTypes(_safeId), safeManager.safes(_safeId), address(this), address(this), convertAmount, 0 ); bytes memory logData = abi.encode(_safeId, _amount, _adapterAddr, _from); return (_amount, logData); } function parseInputs(bytes memory _callData) public pure returns (Params memory params) { params = abi.decode(_callData, (Params)); } }
@inheritdoc ActionBase
function executeActionDirect(bytes memory _callData) public payable override { Params memory inputData = parseInputs(_callData); (, bytes memory logData) = _reflexerSupply(inputData.safeId, inputData.amount, inputData.adapterAddr, inputData.from); logger.logActionDirectEvent("ReflexerSupply", logData); }
13,106,613
./full_match/80001/0x7cbA0423bafEa1dfd576ffA482222017f9b93eD3/sources/NftStaking.sol
If address already has ERC721 Token/s staked, calculate the rewards. Increment the amountStaked and map msg.sender to the Token Id of the staked Token to later send back on withdrawal. Finally give timeOfLastUpdate the value of now. If wallet has tokens staked, calculate the rewards before adding the new token
function stake(uint256 _tokenId) external nonReentrant { if (stakers[msg.sender].amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); }
5,605,301
pragma solidity 0.6.12; // SPDX-License-Identifier: MIT /** * @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); } /** * @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; } } /** * @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); } } } } /** * @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"); } } } /* * @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 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 { } } interface IController { function vaults(address) external view returns (address); function rewards() external view returns (address); function want(address) external view returns (address); // NOTE: Only StrategyControllerV2 implements this function balanceOf(address) external view returns (uint); function withdraw(address, uint) external; function earn(address, uint) external; } interface OneSplitAudit { function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 flags ) external payable returns(uint256 returnAmount); function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns( uint256 returnAmount, uint256[] memory distribution ); } contract hdPoolDAI is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI IERC20 public HDCORE = IERC20(0x63Da3b945e86FE2D1FCAf4eb138474E934E2B94f); address public onesplit = address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e); uint public onesplitParts = 1; uint public onesplitSlippageMin = 500; // 5% default uint public constant onesplitSlippageMax = 10000; uint public min = 9500; uint public constant max = 10000; uint public HDCOREMin = 50; // 0.5% default uint public constant HDCOREMax = 10000; bool public enableHDCOREYield = true; address public governance; address public controller; constructor (address _controller) public ERC20( string(abi.encodePacked("HDCORE ", ERC20(address(token)).name())), string(abi.encodePacked("h", ERC20(address(token)).symbol())) ) { _setupDecimals(ERC20(address(token)).decimals()); governance = msg.sender; controller = _controller; } // Total balance of token in both vault and corresponding strategy function balance() public view returns (uint) { return token.balanceOf(address(this)) .add(IController(controller).balanceOf(address(token))); } function setMin(uint _min) external { require(msg.sender == governance, "!governance"); min = _min; } function setHDCOREBuyMin(uint _HDCOREMin) external { require(msg.sender == governance, "!governance"); HDCOREMin = _HDCOREMin; } function setOneSplitSlippageMin(uint _onesplitSlippageMin) external { require(msg.sender == governance, "!governance"); onesplitSlippageMin = _onesplitSlippageMin; } function setOneSplit(address _onesplit) public { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setOneSplitParts(uint _onesplitParts) public { require(msg.sender == governance, "!governance"); onesplitParts = _onesplitParts; } function setEnableHDCOREYield(bool _status) public { require(msg.sender == governance, "!governance"); enableHDCOREYield = _status; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) public { require(msg.sender == governance, "!governance"); controller = _controller; } // Custom logic in here for how much the vault allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint) { return token.balanceOf(address(this)).mul(min).div(max); } // Called by Keeper to put deposited token into strategy function earn() public { uint _bal = available(); token.safeTransfer(controller, _bal); IController(controller).earn(address(token), _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint _amount) public { uint _pool = balance(); uint _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint _shares) public { uint r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint b = token.balanceOf(address(this)); if (b < r) { uint _withdraw = r.sub(b); IController(controller).withdraw(address(token), _withdraw); uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } if (!enableHDCOREYield) { token.safeTransfer(msg.sender, r); } else { uint tokenToBuyHDCORE = r.mul(HDCOREMin).div(HDCOREMax); r = r.sub(tokenToBuyHDCORE); token.safeTransfer(msg.sender, r); if (tokenToBuyHDCORE > 0) { uint _before = IERC20(HDCORE).balanceOf(address(this)); token.safeApprove(onesplit, 0); token.safeApprove(onesplit, tokenToBuyHDCORE); uint[] memory _distribution; uint _expected; (_expected, _distribution) = OneSplitAudit(onesplit).getExpectedReturn(address(token), address(HDCORE), tokenToBuyHDCORE, onesplitParts, 0); uint _expectedAfterSlippage = _expected.sub(_expected.mul(onesplitSlippageMin).div(onesplitSlippageMax)); OneSplitAudit(onesplit).swap(address(token), address(HDCORE), tokenToBuyHDCORE, _expectedAfterSlippage, _distribution, 0); uint _after = IERC20(HDCORE).balanceOf(address(this)); if (_after > _before) { uint _diff = _after.sub(_before); HDCORE.safeTransfer(msg.sender, _diff); } } } } // Shouldn't have any dangling HDCORE balance in the pool function withdrawHDCOREInCaseStuck() public { require(msg.sender == governance, "!governance"); uint _amount = HDCORE.balanceOf(address(this)); HDCORE.safeTransfer(msg.sender, _amount); } function getPricePerFullShare() public view returns (uint) { return balance().mul(1e18).div(totalSupply()); } }
No rebalance implementation for lower fees and faster swaps Check balance
function withdraw(uint _shares) public { uint r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint b = token.balanceOf(address(this)); if (b < r) { uint _withdraw = r.sub(b); IController(controller).withdraw(address(token), _withdraw); uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } if (!enableHDCOREYield) { token.safeTransfer(msg.sender, r); uint tokenToBuyHDCORE = r.mul(HDCOREMin).div(HDCOREMax); r = r.sub(tokenToBuyHDCORE); token.safeTransfer(msg.sender, r); if (tokenToBuyHDCORE > 0) { uint _before = IERC20(HDCORE).balanceOf(address(this)); token.safeApprove(onesplit, 0); token.safeApprove(onesplit, tokenToBuyHDCORE); uint[] memory _distribution; uint _expected; (_expected, _distribution) = OneSplitAudit(onesplit).getExpectedReturn(address(token), address(HDCORE), tokenToBuyHDCORE, onesplitParts, 0); uint _expectedAfterSlippage = _expected.sub(_expected.mul(onesplitSlippageMin).div(onesplitSlippageMax)); OneSplitAudit(onesplit).swap(address(token), address(HDCORE), tokenToBuyHDCORE, _expectedAfterSlippage, _distribution, 0); uint _after = IERC20(HDCORE).balanceOf(address(this)); if (_after > _before) { uint _diff = _after.sub(_before); HDCORE.safeTransfer(msg.sender, _diff); } } } }
10,596,477
/* The MIT License (MIT) Copyright 2017 - 2018, Alchemy Limited, LLC and Smart Contract Solutions. 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.4.21; /** * Reference: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/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) { if (a == 0) { return 0; } uint256 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 c; } /** * @dev Substracts 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) { uint256 c = a + b; assert(c >= a); return c; } } /* end SafeMath library */ /// @title Math operation when both numbers has decimal places. /// @notice Use this contract when both numbers has 18 decimal places. contract FixedMath { using SafeMath for uint; uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; uint constant internal DECIMALS = 18; uint constant internal DECMULT = 10 ** DECIMALS; /// @notice Multiplication. function fMul(uint x, uint y) internal pure returns (uint) { return (x.mul(y)).div(DECMULT); } /// @notice Division. function fDiv(uint numerator, uint divisor) internal pure returns (uint) { return (numerator.mul(DECMULT)).div(divisor); } /// @notice Square root. /// @dev Reference: https://stackoverflow.com/questions/3766020/binary-search-to-compute-square-root-java function fSqrt(uint n) internal pure returns (uint) { if (n == 0) { return 0; } uint z = n * n; require(z / n == n); uint high = fAdd(n, DECMULT); uint low = 0; while (fSub(high, low) > 1) { uint mid = fAdd(low, high) / 2; if (fSqr(mid) <= n) { low = mid; } else { high = mid; } } return low; } /// @notice Square. function fSqr(uint n) internal pure returns (uint) { return fMul(n, n); } /// @notice Add. function fAdd(uint x, uint y) internal pure returns (uint) { return x.add(y); } /// @notice Sub. function fSub(uint x, uint y) internal pure returns (uint) { return x.sub(y); } } /// @title A formula contract for converter contract Formula is FixedMath { /// @notice Trade in reserve(ETH/MET) and mint new smart tokens /// @param smartTokenSupply Total supply of smart token /// @param reserveTokensSent Amount of token sent by caller /// @param reserveTokenBalance Balance of reserve token in the contract /// @return Smart token minted function returnForMint(uint smartTokenSupply, uint reserveTokensSent, uint reserveTokenBalance) internal pure returns (uint) { uint s = smartTokenSupply; uint e = reserveTokensSent; uint r = reserveTokenBalance; /// smartToken for mint(T) = S * (sqrt(1 + E/R) - 1) /// DECMULT is same as 1 for values with 18 decimal places return ((fMul(s, (fSub(fSqrt(fAdd(DECMULT, fDiv(e, r))), DECMULT)))).mul(METDECMULT)).div(DECMULT); } /// @notice Redeem smart tokens, get back reserve(ETH/MET) token /// @param smartTokenSupply Total supply of smart token /// @param smartTokensSent Smart token sent /// @param reserveTokenBalance Balance of reserve token in the contract /// @return Reserve token redeemed function returnForRedemption(uint smartTokenSupply, uint smartTokensSent, uint reserveTokenBalance) internal pure returns (uint) { uint s = smartTokenSupply; uint t = smartTokensSent; uint r = reserveTokenBalance; /// reserveToken (E) = R * (1 - (1 - T/S)**2) /// DECMULT is same as 1 for values with 18 decimal places return ((fMul(r, (fSub(DECMULT, fSqr(fSub(DECMULT, fDiv(t, s))))))).mul(METDECMULT)).div(DECMULT); } } /// @title Pricer contract to calculate descending price during auction. contract Pricer { using SafeMath for uint; uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; uint public minimumPrice = 33*10**11; uint public minimumPriceInDailyAuction = 1; uint public tentimes; uint public hundredtimes; uint public thousandtimes; uint constant public MULTIPLIER = 1984320568*10**5; /// @notice Pricer constructor, calculate 10, 100 and 1000 times of 0.99. function initPricer() public { uint x = METDECMULT; uint i; /// Calculate 10 times of 0.99 for (i = 0; i < 10; i++) { x = x.mul(99).div(100); } tentimes = x; x = METDECMULT; /// Calculate 100 times of 0.99 using tentimes calculated above. /// tentimes has 18 decimal places and due to this METDECMLT is /// used as divisor. for (i = 0; i < 10; i++) { x = x.mul(tentimes).div(METDECMULT); } hundredtimes = x; x = METDECMULT; /// Calculate 1000 times of 0.99 using hundredtimes calculated above. /// hundredtimes has 18 decimal places and due to this METDECMULT is /// used as divisor. for (i = 0; i < 10; i++) { x = x.mul(hundredtimes).div(METDECMULT); } thousandtimes = x; } /// @notice Price of MET at nth minute out during operational auction /// @param initialPrice The starting price ie last purchase price /// @param _n The number of minutes passed since last purchase /// @return The resulting price function priceAt(uint initialPrice, uint _n) public view returns (uint price) { uint mult = METDECMULT; uint i; uint n = _n; /// If quotient of n/1000 is greater than 0 then calculate multiplier by /// multiplying thousandtimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/1000. if (n / 1000 > 0) { for (i = 0; i < n / 1000; i++) { mult = mult.mul(thousandtimes).div(METDECMULT); } n = n % 1000; } /// If quotient of n/100 is greater than 0 then calculate multiplier by /// multiplying hundredtimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/100. if (n / 100 > 0) { for (i = 0; i < n / 100; i++) { mult = mult.mul(hundredtimes).div(METDECMULT); } n = n % 100; } /// If quotient of n/10 is greater than 0 then calculate multiplier by /// multiplying tentimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/10. if (n / 10 > 0) { for (i = 0; i < n / 10; i++) { mult = mult.mul(tentimes).div(METDECMULT); } n = n % 10; } /// Calculate multiplier by multiplying 0.99 and mult, repeat it n times. for (i = 0; i < n; i++) { mult = mult.mul(99).div(100); } /// price is calculated as initialPrice multiplied by 0.99 and that too _n times. /// Here mult is METDECMULT multiplied by 0.99 and that too _n times. price = initialPrice.mul(mult).div(METDECMULT); if (price < minimumPriceInDailyAuction) { price = minimumPriceInDailyAuction; } } /// @notice Price of MET at nth minute during initial auction. /// @param lastPurchasePrice The price of MET in last transaction /// @param numTicks The number of minutes passed since last purchase /// @return The resulting price function priceAtInitialAuction(uint lastPurchasePrice, uint numTicks) public view returns (uint price) { /// Price will decrease linearly every minute by the factor of MULTIPLIER. /// If lastPurchasePrice is greater than decrease in price then calculated the price. /// Return minimumPrice, if calculated price is less than minimumPrice. /// If decrease in price is more than lastPurchasePrice then simply return the minimumPrice. if (lastPurchasePrice > MULTIPLIER.mul(numTicks)) { price = lastPurchasePrice.sub(MULTIPLIER.mul(numTicks)); } if (price < minimumPrice) { price = minimumPrice; } } } /// @dev Reference: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md /// @notice ERC20 standard interface interface ERC20 { function totalSupply() public constant returns (uint256); function balanceOf(address _owner) public constant returns (uint256); function allowance(address _owner, address _spender) public constant returns (uint256); event Transfer(address indexed _from, address indexed _to, uint256 _value); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function approve(address _spender, uint256 _value) public returns (bool); } /// @title Ownable contract Ownable { address public owner; event OwnershipChanged(address indexed prevOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @param _newOwner /// @return true/false function changeOwnership(address _newOwner) public onlyOwner returns (bool) { require(_newOwner != address(0)); require(_newOwner != owner); emit OwnershipChanged(owner, _newOwner); owner = _newOwner; return true; } } /// @title Owned contract Owned is Ownable { address public newOwner; /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @param _newOwner /// @return true/false function changeOwnership(address _newOwner) public onlyOwner returns (bool) { require(_newOwner != owner); newOwner = _newOwner; return true; } /// @notice Allows the new owner to accept ownership of the contract. /// @return true/false function acceptOwnership() public returns (bool) { require(msg.sender == newOwner); emit OwnershipChanged(owner, newOwner); owner = newOwner; return true; } } /// @title Mintable contract to allow minting and destroy. contract Mintable is Owned { using SafeMath for uint256; event Mint(address indexed _to, uint _value); event Destroy(address indexed _from, uint _value); event Transfer(address indexed _from, address indexed _to, uint256 _value); uint256 internal _totalSupply; mapping(address => uint256) internal _balanceOf; address public autonomousConverter; address public minter; ITokenPorter public tokenPorter; /// @notice init reference of other contract and initial supply /// @param _autonomousConverter /// @param _minter /// @param _initialSupply /// @param _decmult Decimal places function initMintable(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { require(autonomousConverter == 0x0 && _autonomousConverter != 0x0); require(minter == 0x0 && _minter != 0x0); autonomousConverter = _autonomousConverter; minter = _minter; _totalSupply = _initialSupply.mul(_decmult); _balanceOf[_autonomousConverter] = _totalSupply; } function totalSupply() public constant returns (uint256) { return _totalSupply; } function balanceOf(address _owner) public constant returns (uint256) { return _balanceOf[_owner]; } /// @notice set address of token porter /// @param _tokenPorter address of token porter function setTokenPorter(address _tokenPorter) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); tokenPorter = ITokenPorter(_tokenPorter); return true; } /// @notice allow minter and tokenPorter to mint token and assign to address /// @param _to /// @param _value Amount to be minted function mint(address _to, uint _value) public returns (bool) { require(msg.sender == minter || msg.sender == address(tokenPorter)); _balanceOf[_to] = _balanceOf[_to].add(_value); _totalSupply = _totalSupply.add(_value); emit Mint(_to, _value); emit Transfer(0x0, _to, _value); return true; } /// @notice allow autonomousConverter and tokenPorter to mint token and assign to address /// @param _from /// @param _value Amount to be destroyed function destroy(address _from, uint _value) public returns (bool) { require(msg.sender == autonomousConverter || msg.sender == address(tokenPorter)); _balanceOf[_from] = _balanceOf[_from].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Destroy(_from, _value); emit Transfer(_from, 0x0, _value); return true; } } /// @title Token contract contract Token is ERC20, Mintable { mapping(address => mapping(address => uint256)) internal _allowance; function initToken(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { initMintable(_autonomousConverter, _minter, _initialSupply, _decmult); } /// @notice Provide allowance information function allowance(address _owner, address _spender) public constant returns (uint256) { return _allowance[_owner][_spender]; } /// @notice Transfer tokens from sender to the provided address. /// @param _to Receiver of the tokens /// @param _value Amount of token /// @return true/false function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_to != minter); require(_to != address(this)); require(_to != autonomousConverter); Proceeds proceeds = Auctions(minter).proceeds(); require((_to != address(proceeds))); _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /// @notice Transfer tokens based on allowance. /// msg.sender must have allowance for spending the tokens from owner ie _from /// @param _from Owner of the tokens /// @param _to Receiver of the tokens /// @param _value Amount of tokens to transfer /// @return true/false function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_to != minter && _from != minter); require(_to != address(this) && _from != address(this)); Proceeds proceeds = Auctions(minter).proceeds(); require(_to != address(proceeds) && _from != address(proceeds)); //AC can accept MET via this function, needed for MetToEth conversion require(_from != autonomousConverter); require(_allowance[_from][msg.sender] >= _value); _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 Approve spender to spend the tokens ie approve allowance /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != address(this)); _allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /// @notice Transfer the tokens from sender to all the address provided in the array. /// @dev Left 160 bits are the recipient address and the right 96 bits are the token amount. /// @param bits array of uint /// @return true/false function multiTransfer(uint[] bits) public returns (bool) { for (uint i = 0; i < bits.length; i++) { address a = address(bits[i] >> 96); uint amount = bits[i] & ((1 << 96) - 1); if (!transfer(a, amount)) revert(); } return true; } /// @notice Increase allowance of spender /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approveMore(address _spender, uint256 _value) public returns (bool) { uint previous = _allowance[msg.sender][_spender]; uint newAllowance = previous.add(_value); _allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } /// @notice Decrease allowance of spender /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approveLess(address _spender, uint256 _value) public returns (bool) { uint previous = _allowance[msg.sender][_spender]; uint newAllowance = previous.sub(_value); _allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } } /// @title Smart tokens are an intermediate token generated during conversion of MET-ETH contract SmartToken is Mintable { uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; function initSmartToken(address _autonomousConverter, address _minter, uint _initialSupply) public onlyOwner { initMintable(_autonomousConverter, _minter, _initialSupply, METDECMULT); } } /// @title ERC20 token. Metronome token contract METToken is Token { string public constant name = "Metronome"; string public constant symbol = "MET"; uint8 public constant decimals = 18; bool public transferAllowed; function initMETToken(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { initToken(_autonomousConverter, _minter, _initialSupply, _decmult); } /// @notice Transferable modifier to allow transfer only after initial auction ended. modifier transferable() { require(transferAllowed); _; } function enableMETTransfers() public returns (bool) { require(!transferAllowed && Auctions(minter).isInitialAuctionEnded()); transferAllowed = true; return true; } /// @notice Transfer tokens from caller to another address /// @param _to address The address which you want to transfer to /// @param _value uint256 the amout of tokens to be transfered function transfer(address _to, uint256 _value) public transferable returns (bool) { return super.transfer(_to, _value); } /// @notice Transfer tokens from one address to another /// @param _from address The address from which you want to transfer /// @param _to address The address which you want to transfer to /// @param _value uint256 the amout of tokens to be transfered function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) { return super.transferFrom(_from, _to, _value); } /// @notice Transfer the token from sender to all the addresses provided in array. /// @dev Left 160 bits are the recipient address and the right 96 bits are the token amount. /// @param bits array of uint /// @return true/false function multiTransfer(uint[] bits) public transferable returns (bool) { return super.multiTransfer(bits); } mapping (address => bytes32) public roots; function setRoot(bytes32 data) public { roots[msg.sender] = data; } function getRoot(address addr) public view returns (bytes32) { return roots[addr]; } function rootsMatch(address a, address b) public view returns (bool) { return roots[a] == roots[b]; } /// @notice import MET tokens from another chain to this chain. /// @param _destinationChain destination chain name /// @param _addresses _addresses[0] is destMetronomeAddr and _addresses[1] is recipientAddr /// @param _extraData extra information for import /// @param _burnHashes _burnHashes[0] is previous burnHash, _burnHashes[1] is current burnHash /// @param _supplyOnAllChains MET supply on all supported chains /// @param _importData _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee /// _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, _importData[5] is _dailyMintable /// _importData[6] is _burnSequence, _importData[7] is _dailyAuctionStartTime /// @param _proof proof /// @return true/false function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool) { require(address(tokenPorter) != 0x0); return tokenPorter.importMET(_originChain, _destinationChain, _addresses, _extraData, _burnHashes, _supplyOnAllChains, _importData, _proof); } /// @notice export MET tokens from this chain to another chain. /// @param _destChain destination chain address /// @param _destMetronomeAddr address of Metronome contract on the destination chain /// where this MET will be imported. /// @param _destRecipAddr address of account on destination chain /// @param _amount amount /// @param _extraData extra information for future expansion /// @return true/false function export(bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool) { require(address(tokenPorter) != 0x0); return tokenPorter.export(msg.sender, _destChain, _destMetronomeAddr, _destRecipAddr, _amount, _fee, _extraData); } struct Sub { uint startTime; uint payPerWeek; uint lastWithdrawTime; } event LogSubscription(address indexed subscriber, address indexed subscribesTo); event LogCancelSubscription(address indexed subscriber, address indexed subscribesTo); mapping (address => mapping (address => Sub)) public subs; /// @notice subscribe for a weekly recurring payment /// @param _startTime Subscription start time. /// @param _payPerWeek weekly payment /// @param _recipient address of beneficiary /// @return true/false function subscribe(uint _startTime, uint _payPerWeek, address _recipient) public returns (bool) { require(_startTime >= block.timestamp); require(_payPerWeek != 0); require(_recipient != 0); subs[msg.sender][_recipient] = Sub(_startTime, _payPerWeek, _startTime); emit LogSubscription(msg.sender, _recipient); return true; } /// @notice cancel a subcription. /// @param _recipient address of beneficiary /// @return true/false function cancelSubscription(address _recipient) public returns (bool) { require(subs[msg.sender][_recipient].startTime != 0); require(subs[msg.sender][_recipient].payPerWeek != 0); subs[msg.sender][_recipient].startTime = 0; subs[msg.sender][_recipient].payPerWeek = 0; subs[msg.sender][_recipient].lastWithdrawTime = 0; emit LogCancelSubscription(msg.sender, _recipient); return true; } /// @notice get subcription details /// @param _owner /// @param _recipient /// @return startTime, payPerWeek, lastWithdrawTime function getSubscription(address _owner, address _recipient) public constant returns (uint startTime, uint payPerWeek, uint lastWithdrawTime) { Sub storage sub = subs[_owner][_recipient]; return ( sub.startTime, sub.payPerWeek, sub.lastWithdrawTime ); } /// @notice caller can withdraw the token from subscribers. /// @param _owner subcriber /// @return true/false function subWithdraw(address _owner) public transferable returns (bool) { require(subWithdrawFor(_owner, msg.sender)); return true; } /// @notice Allow callers to withdraw token in one go from all of its subscribers /// @param _owners array of address of subscribers /// @return number of successful transfer done function multiSubWithdraw(address[] _owners) public returns (uint) { uint n = 0; for (uint i=0; i < _owners.length; i++) { if (subWithdrawFor(_owners[i], msg.sender)) { n++; } } return n; } /// @notice Trigger MET token transfers for all pairs of subscribers and beneficiaries /// @dev address at i index in owners and recipients array is subcriber-beneficiary pair. /// @param _owners /// @param _recipients /// @return number of successful transfer done function multiSubWithdrawFor(address[] _owners, address[] _recipients) public returns (uint) { // owners and recipients need 1-to-1 mapping, must be same length require(_owners.length == _recipients.length); uint n = 0; for (uint i = 0; i < _owners.length; i++) { if (subWithdrawFor(_owners[i], _recipients[i])) { n++; } } return n; } function subWithdrawFor(address _from, address _to) internal returns (bool) { Sub storage sub = subs[_from][_to]; if (sub.startTime > 0 && sub.startTime < block.timestamp && sub.payPerWeek > 0) { uint weekElapsed = (now.sub(sub.lastWithdrawTime)).div(7 days); uint amount = weekElapsed.mul(sub.payPerWeek); if (weekElapsed > 0 && _balanceOf[_from] >= amount) { subs[_from][_to].lastWithdrawTime = block.timestamp; _balanceOf[_from] = _balanceOf[_from].sub(amount); _balanceOf[_to] = _balanceOf[_to].add(amount); emit Transfer(_from, _to, amount); return true; } } return false; } } /// @title Autonomous Converter contract for MET <=> ETH exchange contract AutonomousConverter is Formula, Owned { SmartToken public smartToken; METToken public reserveToken; Auctions public auctions; enum WhichToken { Eth, Met } bool internal initialized = false; event LogFundsIn(address indexed from, uint value); event ConvertEthToMet(address indexed from, uint eth, uint met); event ConvertMetToEth(address indexed from, uint eth, uint met); function init(address _reserveToken, address _smartToken, address _auctions) public onlyOwner payable { require(!initialized); auctions = Auctions(_auctions); reserveToken = METToken(_reserveToken); smartToken = SmartToken(_smartToken); initialized = true; } function handleFund() public payable { require(msg.sender == address(auctions.proceeds())); emit LogFundsIn(msg.sender, msg.value); } function getMetBalance() public view returns (uint) { return balanceOf(WhichToken.Met); } function getEthBalance() public view returns (uint) { return balanceOf(WhichToken.Eth); } /// @notice return the expected MET for ETH /// @param _depositAmount ETH. /// @return expected MET value for ETH function getMetForEthResult(uint _depositAmount) public view returns (uint256) { return convertingReturn(WhichToken.Eth, _depositAmount); } /// @notice return the expected ETH for MET /// @param _depositAmount MET. /// @return expected ETH value for MET function getEthForMetResult(uint _depositAmount) public view returns (uint256) { return convertingReturn(WhichToken.Met, _depositAmount); } /// @notice send ETH and get MET /// @param _mintReturn execute conversion only if return is equal or more than _mintReturn /// @return returnedMet MET retured after conversion function convertEthToMet(uint _mintReturn) public payable returns (uint returnedMet) { returnedMet = convert(WhichToken.Eth, _mintReturn, msg.value); emit ConvertEthToMet(msg.sender, msg.value, returnedMet); } /// @notice send MET and get ETH /// @dev Caller will be required to approve the AutonomousConverter to initiate the transfer /// @param _amount MET amount /// @param _mintReturn execute conversion only if return is equal or more than _mintReturn /// @return returnedEth ETh returned after conversion function convertMetToEth(uint _amount, uint _mintReturn) public returns (uint returnedEth) { returnedEth = convert(WhichToken.Met, _mintReturn, _amount); emit ConvertMetToEth(msg.sender, returnedEth, _amount); } function balanceOf(WhichToken which) internal view returns (uint) { if (which == WhichToken.Eth) return address(this).balance; if (which == WhichToken.Met) return reserveToken.balanceOf(this); revert(); } function convertingReturn(WhichToken whichFrom, uint _depositAmount) internal view returns (uint256) { WhichToken to = WhichToken.Met; if (whichFrom == WhichToken.Met) { to = WhichToken.Eth; } uint reserveTokenBalanceFrom = balanceOf(whichFrom).add(_depositAmount); uint mintRet = returnForMint(smartToken.totalSupply(), _depositAmount, reserveTokenBalanceFrom); uint newSmartTokenSupply = smartToken.totalSupply().add(mintRet); uint reserveTokenBalanceTo = balanceOf(to); return returnForRedemption( newSmartTokenSupply, mintRet, reserveTokenBalanceTo); } function convert(WhichToken whichFrom, uint _minReturn, uint amnt) internal returns (uint) { WhichToken to = WhichToken.Met; if (whichFrom == WhichToken.Met) { to = WhichToken.Eth; require(reserveToken.transferFrom(msg.sender, this, amnt)); } uint mintRet = mint(whichFrom, amnt, 1); return redeem(to, mintRet, _minReturn); } function mint(WhichToken which, uint _depositAmount, uint _minReturn) internal returns (uint256 amount) { require(_minReturn > 0); amount = mintingReturn(which, _depositAmount); require(amount >= _minReturn); require(smartToken.mint(msg.sender, amount)); } function mintingReturn(WhichToken which, uint _depositAmount) internal view returns (uint256) { uint256 smartTokenSupply = smartToken.totalSupply(); uint256 reserveBalance = balanceOf(which); return returnForMint(smartTokenSupply, _depositAmount, reserveBalance); } function redeem(WhichToken which, uint _amount, uint _minReturn) internal returns (uint redeemable) { require(_amount <= smartToken.balanceOf(msg.sender)); require(_minReturn > 0); redeemable = redemptionReturn(which, _amount); require(redeemable >= _minReturn); uint256 reserveBalance = balanceOf(which); require(reserveBalance >= redeemable); uint256 tokenSupply = smartToken.totalSupply(); require(_amount < tokenSupply); smartToken.destroy(msg.sender, _amount); if (which == WhichToken.Eth) { msg.sender.transfer(redeemable); } else { require(reserveToken.transfer(msg.sender, redeemable)); } } function redemptionReturn(WhichToken which, uint smartTokensSent) internal view returns (uint256) { uint smartTokenSupply = smartToken.totalSupply(); uint reserveTokenBalance = balanceOf(which); return returnForRedemption( smartTokenSupply, smartTokensSent, reserveTokenBalance); } } /// @title Proceeds contract contract Proceeds is Owned { using SafeMath for uint256; AutonomousConverter public autonomousConverter; Auctions public auctions; event LogProceedsIn(address indexed from, uint value); event LogClosedAuction(address indexed from, uint value); uint latestAuctionClosed; function initProceeds(address _autonomousConverter, address _auctions) public onlyOwner { require(address(auctions) == 0x0 && _auctions != 0x0); require(address(autonomousConverter) == 0x0 && _autonomousConverter != 0x0); autonomousConverter = AutonomousConverter(_autonomousConverter); auctions = Auctions(_auctions); } function handleFund() public payable { require(msg.sender == address(auctions)); emit LogProceedsIn(msg.sender, msg.value); } /// @notice Forward 0.25% of total ETH balance of proceeds to AutonomousConverter contract function closeAuction() public { uint lastPurchaseTick = auctions.lastPurchaseTick(); uint currentAuction = auctions.currentAuction(); uint val = ((address(this).balance).mul(25)).div(10000); if (val > 0 && (currentAuction > auctions.whichAuction(lastPurchaseTick)) && (latestAuctionClosed < currentAuction)) { latestAuctionClosed = currentAuction; autonomousConverter.handleFund.value(val)(); emit LogClosedAuction(msg.sender, val); } } } /// @title Auction contract. Send ETH to the contract address and buy MET. contract Auctions is Pricer, Owned { using SafeMath for uint256; METToken public token; Proceeds public proceeds; address[] public founders; mapping(address => TokenLocker) public tokenLockers; uint internal constant DAY_IN_SECONDS = 86400; uint internal constant DAY_IN_MINUTES = 1440; uint public genesisTime; uint public lastPurchaseTick; uint public lastPurchasePrice; uint public constant INITIAL_GLOBAL_DAILY_SUPPLY = 2880 * METDECMULT; uint public INITIAL_FOUNDER_SUPPLY = 1999999 * METDECMULT; uint public INITIAL_AC_SUPPLY = 1 * METDECMULT; uint public totalMigratedOut = 0; uint public totalMigratedIn = 0; uint public timeScale = 1; uint public constant INITIAL_SUPPLY = 10000000 * METDECMULT; uint public mintable = INITIAL_SUPPLY; uint public initialAuctionDuration = 7 days; uint public initialAuctionEndTime; uint public dailyAuctionStartTime; uint public constant DAILY_PURCHASE_LIMIT = 1000 ether; mapping (address => uint) internal purchaseInTheAuction; mapping (address => uint) internal lastPurchaseAuction; bool public minted; bool public initialized; uint public globalSupplyAfterPercentageLogic = 52598080 * METDECMULT; uint public constant AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS = 14791; bytes8 public chain = "ETH"; event LogAuctionFundsIn(address indexed sender, uint amount, uint tokens, uint purchasePrice, uint refund); function Auctions() public { mintable = INITIAL_SUPPLY - 2000000 * METDECMULT; } /// @notice Payable function to buy MET in descending price auction function () public payable running { require(msg.value > 0); uint amountForPurchase = msg.value; uint excessAmount; if (currentAuction() > whichAuction(lastPurchaseTick)) { proceeds.closeAuction(); restartAuction(); } if (isInitialAuctionEnded()) { require(now >= dailyAuctionStartTime); if (lastPurchaseAuction[msg.sender] < currentAuction()) { if (amountForPurchase > DAILY_PURCHASE_LIMIT) { excessAmount = amountForPurchase.sub(DAILY_PURCHASE_LIMIT); amountForPurchase = DAILY_PURCHASE_LIMIT; } purchaseInTheAuction[msg.sender] = msg.value; lastPurchaseAuction[msg.sender] = currentAuction(); } else { require(purchaseInTheAuction[msg.sender] < DAILY_PURCHASE_LIMIT); if (purchaseInTheAuction[msg.sender].add(amountForPurchase) > DAILY_PURCHASE_LIMIT) { excessAmount = (purchaseInTheAuction[msg.sender].add(amountForPurchase)).sub(DAILY_PURCHASE_LIMIT); amountForPurchase = amountForPurchase.sub(excessAmount); } purchaseInTheAuction[msg.sender] = purchaseInTheAuction[msg.sender].add(msg.value); } } uint _currentTick = currentTick(); uint weiPerToken; uint tokens; uint refund; (weiPerToken, tokens, refund) = calcPurchase(amountForPurchase, _currentTick); require(tokens > 0); if (now < initialAuctionEndTime && (token.totalSupply()).add(tokens) >= INITIAL_SUPPLY) { initialAuctionEndTime = now; dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = _currentTick; lastPurchasePrice = weiPerToken; assert(tokens <= mintable); mintable = mintable.sub(tokens); assert(refund <= amountForPurchase); uint ethForProceeds = amountForPurchase.sub(refund); proceeds.handleFund.value(ethForProceeds)(); require(token.mint(msg.sender, tokens)); refund = refund.add(excessAmount); if (refund > 0) { if (purchaseInTheAuction[msg.sender] > 0) { purchaseInTheAuction[msg.sender] = purchaseInTheAuction[msg.sender].sub(refund); } msg.sender.transfer(refund); } emit LogAuctionFundsIn(msg.sender, ethForProceeds, tokens, lastPurchasePrice, refund); } modifier running() { require(isRunning()); _; } function isRunning() public constant returns (bool) { return (block.timestamp >= genesisTime && genesisTime > 0); } /// @notice current tick(minute) of the metronome clock /// @return tick count function currentTick() public view returns(uint) { return whichTick(block.timestamp); } /// @notice current auction /// @return auction count function currentAuction() public view returns(uint) { return whichAuction(currentTick()); } /// @notice tick count at the timestamp t. /// @param t timestamp /// @return tick count function whichTick(uint t) public view returns(uint) { if (genesisTime > t) { revert(); } return (t - genesisTime) * timeScale / 1 minutes; } /// @notice Auction count at given the timestamp t /// @param t timestamp /// @return Auction count function whichAuction(uint t) public view returns(uint) { if (whichTick(dailyAuctionStartTime) > t) { return 0; } else { return ((t - whichTick(dailyAuctionStartTime)) / DAY_IN_MINUTES) + 1; } } /// @notice one single function telling everything about Metronome Auction function heartbeat() public view returns ( bytes8 _chain, address auctionAddr, address convertAddr, address tokenAddr, uint minting, uint totalMET, uint proceedsBal, uint currTick, uint currAuction, uint nextAuctionGMT, uint genesisGMT, uint currentAuctionPrice, uint _dailyMintable, uint _lastPurchasePrice) { _chain = chain; convertAddr = proceeds.autonomousConverter(); tokenAddr = token; auctionAddr = this; totalMET = token.totalSupply(); proceedsBal = address(proceeds).balance; currTick = currentTick(); currAuction = currentAuction(); if (currAuction == 0) { nextAuctionGMT = dailyAuctionStartTime; } else { nextAuctionGMT = (currAuction * DAY_IN_SECONDS) / timeScale + dailyAuctionStartTime; } genesisGMT = genesisTime; currentAuctionPrice = currentPrice(); _dailyMintable = dailyMintable(); minting = currentMintable(); _lastPurchasePrice = lastPurchasePrice; } /// @notice Skip Initialization and minting if we're not the OG Metronome /// @param _token MET token contract address /// @param _proceeds Address of Proceeds contract /// @param _genesisTime The block.timestamp when first auction started on OG chain /// @param _minimumPrice Nobody can buy tokens for less than this price /// @param _startingPrice Start price of MET when first auction starts /// @param _timeScale time scale factor for auction. will be always 1 in live environment /// @param _chain chain where this contract is being deployed /// @param _initialAuctionEndTime Initial Auction end time in ETH chain. function skipInitBecauseIAmNotOg(address _token, address _proceeds, uint _genesisTime, uint _minimumPrice, uint _startingPrice, uint _timeScale, bytes8 _chain, uint _initialAuctionEndTime) public onlyOwner returns (bool) { require(!minted); require(!initialized); require(_timeScale != 0); require(address(token) == 0x0 && _token != 0x0); require(address(proceeds) == 0x0 && _proceeds != 0x0); initPricer(); // minting substitute section token = METToken(_token); proceeds = Proceeds(_proceeds); INITIAL_FOUNDER_SUPPLY = 0; INITIAL_AC_SUPPLY = 0; mintable = 0; // // initial auction substitute section genesisTime = _genesisTime; initialAuctionEndTime = _initialAuctionEndTime; // if initialAuctionEndTime is midnight, then daily auction will start immediately // after initial auction. if (initialAuctionEndTime == (initialAuctionEndTime / 1 days) * 1 days) { dailyAuctionStartTime = initialAuctionEndTime; } else { dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = 0; if (_minimumPrice > 0) { minimumPrice = _minimumPrice; } timeScale = _timeScale; if (_startingPrice > 0) { lastPurchasePrice = _startingPrice * 1 ether; } else { lastPurchasePrice = 2 ether; } chain = _chain; minted = true; initialized = true; return true; } /// @notice Initialize Auctions parameters /// @param _startTime The block.timestamp when first auction starts /// @param _minimumPrice Nobody can buy tokens for less than this price /// @param _startingPrice Start price of MET when first auction starts /// @param _timeScale time scale factor for auction. will be always 1 in live environment function initAuctions(uint _startTime, uint _minimumPrice, uint _startingPrice, uint _timeScale) public onlyOwner returns (bool) { require(minted); require(!initialized); require(_timeScale != 0); initPricer(); if (_startTime > 0) { genesisTime = (_startTime / (1 minutes)) * (1 minutes) + 60; } else { genesisTime = block.timestamp + 60 - (block.timestamp % 60); } initialAuctionEndTime = genesisTime + initialAuctionDuration; // if initialAuctionEndTime is midnight, then daily auction will start immediately // after initial auction. if (initialAuctionEndTime == (initialAuctionEndTime / 1 days) * 1 days) { dailyAuctionStartTime = initialAuctionEndTime; } else { dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = 0; if (_minimumPrice > 0) { minimumPrice = _minimumPrice; } timeScale = _timeScale; if (_startingPrice > 0) { lastPurchasePrice = _startingPrice * 1 ether; } else { lastPurchasePrice = 2 ether; } for (uint i = 0; i < founders.length; i++) { TokenLocker tokenLocker = tokenLockers[founders[i]]; tokenLocker.lockTokenLocker(); } initialized = true; return true; } function createTokenLocker(address _founder, address _token) public onlyOwner { require(_token != 0x0); require(_founder != 0x0); founders.push(_founder); TokenLocker tokenLocker = new TokenLocker(address(this), _token); tokenLockers[_founder] = tokenLocker; tokenLocker.changeOwnership(_founder); } /// @notice Mint initial supply for founder and move to token locker /// @param _founders Left 160 bits are the founder address and the right 96 bits are the token amount. /// @param _token MET token contract address /// @param _proceeds Address of Proceeds contract function mintInitialSupply(uint[] _founders, address _token, address _proceeds, address _autonomousConverter) public onlyOwner returns (bool) { require(!minted); require(_founders.length != 0); require(address(token) == 0x0 && _token != 0x0); require(address(proceeds) == 0x0 && _proceeds != 0x0); require(_autonomousConverter != 0x0); token = METToken(_token); proceeds = Proceeds(_proceeds); // _founders will be minted into individual token lockers uint foundersTotal; for (uint i = 0; i < _founders.length; i++) { address addr = address(_founders[i] >> 96); require(addr != 0x0); uint amount = _founders[i] & ((1 << 96) - 1); require(amount > 0); TokenLocker tokenLocker = tokenLockers[addr]; require(token.mint(address(tokenLocker), amount)); tokenLocker.deposit(addr, amount); foundersTotal = foundersTotal.add(amount); } // reconcile minted total for founders require(foundersTotal == INITIAL_FOUNDER_SUPPLY); // mint a small amount to the AC require(token.mint(_autonomousConverter, INITIAL_AC_SUPPLY)); minted = true; return true; } /// @notice Suspend auction if not started yet function stopEverything() public onlyOwner { if (genesisTime < block.timestamp) { revert(); } genesisTime = genesisTime + 1000 years; initialAuctionEndTime = genesisTime; dailyAuctionStartTime = genesisTime; } /// @notice Return information about initial auction status. function isInitialAuctionEnded() public view returns (bool) { return (initialAuctionEndTime != 0 && (now >= initialAuctionEndTime || token.totalSupply() >= INITIAL_SUPPLY)); } /// @notice Global MET supply function globalMetSupply() public view returns (uint) { uint currAuc = currentAuction(); if (currAuc > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { return globalSupplyAfterPercentageLogic; } else { return INITIAL_SUPPLY.add(INITIAL_GLOBAL_DAILY_SUPPLY.mul(currAuc)); } } /// @notice Global MET daily supply. Daily supply is greater of 1) 2880 2)2% of then outstanding supply per year. /// @dev 2% logic will kicks in at 14792th auction. function globalDailySupply() public view returns (uint) { uint dailySupply = INITIAL_GLOBAL_DAILY_SUPPLY; uint thisAuction = currentAuction(); if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { uint lastAuctionPurchase = whichAuction(lastPurchaseTick); uint recentAuction = AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS + 1; if (lastAuctionPurchase > recentAuction) { recentAuction = lastAuctionPurchase; } uint totalAuctions = thisAuction - recentAuction; if (totalAuctions > 1) { // derived formula to find close to accurate daily supply when some auction missed. uint factor = 36525 + ((totalAuctions - 1) * 2); dailySupply = (globalSupplyAfterPercentageLogic.mul(2).mul(factor)).div(36525 ** 2); } else { dailySupply = globalSupplyAfterPercentageLogic.mul(2).div(36525); } if (dailySupply < INITIAL_GLOBAL_DAILY_SUPPLY) { dailySupply = INITIAL_GLOBAL_DAILY_SUPPLY; } } return dailySupply; } /// @notice Current price of MET in current auction /// @return weiPerToken function currentPrice() public constant returns (uint weiPerToken) { weiPerToken = calcPriceAt(currentTick()); } /// @notice Daily mintable MET in current auction function dailyMintable() public constant returns (uint) { return nextAuctionSupply(0); } /// @notice Total tokens on this chain function tokensOnThisChain() public view returns (uint) { uint totalSupply = token.totalSupply(); uint currMintable = currentMintable(); return totalSupply.add(currMintable); } /// @notice Current mintable MET in auction function currentMintable() public view returns (uint) { uint currMintable = mintable; uint currAuction = currentAuction(); uint totalAuctions = currAuction.sub(whichAuction(lastPurchaseTick)); if (totalAuctions > 0) { currMintable = mintable.add(nextAuctionSupply(totalAuctions)); } return currMintable; } /// @notice prepare auction when first import is done on a non ETH chain function prepareAuctionForNonOGChain() public { require(msg.sender == address(token.tokenPorter()) || msg.sender == address(token)); require(token.totalSupply() == 0); require(chain != "ETH"); lastPurchaseTick = currentTick(); } /// @notice Find out what the results would be of a prospective purchase /// @param _wei Amount of wei the purchaser will pay /// @param _timestamp Prospective purchase timestamp /// @return weiPerToken expected MET token rate /// @return tokens Expected token for a prospective purchase /// @return refund Wei refund the purchaser will get if amount is excess and MET supply is less function whatWouldPurchaseDo(uint _wei, uint _timestamp) public constant returns (uint weiPerToken, uint tokens, uint refund) { weiPerToken = calcPriceAt(whichTick(_timestamp)); uint calctokens = METDECMULT.mul(_wei).div(weiPerToken); tokens = calctokens; if (calctokens > mintable) { tokens = mintable; uint weiPaying = mintable.mul(weiPerToken).div(METDECMULT); refund = _wei.sub(weiPaying); } } /// @notice Return the information about the next auction /// @return _startTime Start time of next auction /// @return _startPrice Start price of MET in next auction /// @return _auctionTokens MET supply in next auction function nextAuction() internal constant returns(uint _startTime, uint _startPrice, uint _auctionTokens) { if (block.timestamp < genesisTime) { _startTime = genesisTime; _startPrice = lastPurchasePrice; _auctionTokens = mintable; return; } uint recentAuction = whichAuction(lastPurchaseTick); uint currAuc = currentAuction(); uint totalAuctions = currAuc - recentAuction; _startTime = dailyAuctionStartTime; if (currAuc > 1) { _startTime = auctionStartTime(currentTick()); } _auctionTokens = nextAuctionSupply(totalAuctions); if (totalAuctions > 1) { _startPrice = lastPurchasePrice / 100 + 1; } else { if (mintable == 0 || totalAuctions == 0) { // Sold out scenario or someone querying projected start price of next auction _startPrice = (lastPurchasePrice * 2) + 1; } else { // Timed out and all tokens not sold. if (currAuc == 1) { // If initial auction timed out then price before start of new auction will touch floor price _startPrice = minimumPrice * 2; } else { // Descending price till end of auction and then multiply by 2 uint tickWhenAuctionEnded = whichTick(_startTime); uint numTick = 0; if (tickWhenAuctionEnded > lastPurchaseTick) { numTick = tickWhenAuctionEnded - lastPurchaseTick; } _startPrice = priceAt(lastPurchasePrice, numTick) * 2; } } } } /// @notice Calculate results of a purchase /// @param _wei Amount of wei the purchaser will pay /// @param _t Prospective purchase tick /// @return weiPerToken expected MET token rate /// @return tokens Expected token for a prospective purchase /// @return refund Wei refund the purchaser will get if amount is excess and MET supply is less function calcPurchase(uint _wei, uint _t) internal view returns (uint weiPerToken, uint tokens, uint refund) { require(_t >= lastPurchaseTick); uint numTicks = _t - lastPurchaseTick; if (isInitialAuctionEnded()) { weiPerToken = priceAt(lastPurchasePrice, numTicks); } else { weiPerToken = priceAtInitialAuction(lastPurchasePrice, numTicks); } uint calctokens = METDECMULT.mul(_wei).div(weiPerToken); tokens = calctokens; if (calctokens > mintable) { tokens = mintable; uint ethPaying = mintable.mul(weiPerToken).div(METDECMULT); refund = _wei.sub(ethPaying); } } /// @notice MET supply for next Auction also considering carry forward met. /// @param totalAuctionMissed auction count when no purchase done. function nextAuctionSupply(uint totalAuctionMissed) internal view returns (uint supply) { uint thisAuction = currentAuction(); uint tokensHere = token.totalSupply().add(mintable); supply = INITIAL_GLOBAL_DAILY_SUPPLY; uint dailySupplyAtLastPurchase; if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { supply = globalDailySupply(); if (totalAuctionMissed > 1) { dailySupplyAtLastPurchase = globalSupplyAfterPercentageLogic.mul(2).div(36525); supply = dailySupplyAtLastPurchase.add(supply).mul(totalAuctionMissed).div(2); } supply = (supply.mul(tokensHere)).div(globalSupplyAfterPercentageLogic); } else { if (totalAuctionMissed > 1) { supply = supply.mul(totalAuctionMissed); } uint previousGlobalMetSupply = INITIAL_SUPPLY.add(INITIAL_GLOBAL_DAILY_SUPPLY.mul(whichAuction(lastPurchaseTick))); supply = (supply.mul(tokensHere)).div(previousGlobalMetSupply); } } /// @notice price at a number of minutes out in Initial auction and daily auction /// @param _tick Metronome tick /// @return weiPerToken function calcPriceAt(uint _tick) internal constant returns (uint weiPerToken) { uint recentAuction = whichAuction(lastPurchaseTick); uint totalAuctions = whichAuction(_tick).sub(recentAuction); uint prevPrice; uint numTicks = 0; // Auction is sold out and metronome clock is in same auction if (mintable == 0 && totalAuctions == 0) { return lastPurchasePrice; } // Metronome has missed one auction ie no purchase in last auction if (totalAuctions > 1) { prevPrice = lastPurchasePrice / 100 + 1; numTicks = numTicksSinceAuctionStart(_tick); } else if (totalAuctions == 1) { // Metronome clock is in new auction, next auction // previous auction sold out if (mintable == 0) { prevPrice = lastPurchasePrice * 2; } else { // previous auctions timed out // first daily auction if (whichAuction(_tick) == 1) { prevPrice = minimumPrice * 2; } else { prevPrice = priceAt(lastPurchasePrice, numTicksTillAuctionStart(_tick)) * 2; } } numTicks = numTicksSinceAuctionStart(_tick); } else { //Auction is running prevPrice = lastPurchasePrice; numTicks = _tick - lastPurchaseTick; } require(numTicks >= 0); if (isInitialAuctionEnded()) { weiPerToken = priceAt(prevPrice, numTicks); } else { weiPerToken = priceAtInitialAuction(prevPrice, numTicks); } } /// @notice Calculate number of ticks elapsed between auction start time and given tick. /// @param _tick Given metronome tick function numTicksSinceAuctionStart(uint _tick) private view returns (uint ) { uint currentAuctionStartTime = auctionStartTime(_tick); return _tick - whichTick(currentAuctionStartTime); } /// @notice Calculate number of ticks elapsed between lastPurchaseTick and auctions start time of given tick. /// @param _tick Given metronome tick function numTicksTillAuctionStart(uint _tick) private view returns (uint) { uint currentAuctionStartTime = auctionStartTime(_tick); return whichTick(currentAuctionStartTime) - lastPurchaseTick; } /// @notice First calculate the auction which contains the given tick and then calculate /// auction start time of given tick. /// @param _tick Metronome tick function auctionStartTime(uint _tick) private view returns (uint) { return ((whichAuction(_tick)) * 1 days) / timeScale + dailyAuctionStartTime - 1 days; } /// @notice start the next day's auction function restartAuction() private { uint time; uint price; uint auctionTokens; (time, price, auctionTokens) = nextAuction(); uint thisAuction = currentAuction(); if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { globalSupplyAfterPercentageLogic = globalSupplyAfterPercentageLogic.add(globalDailySupply()); } mintable = mintable.add(auctionTokens); lastPurchasePrice = price; lastPurchaseTick = whichTick(time); } } /// @title This contract serves as a locker for a founder's tokens contract TokenLocker is Ownable { using SafeMath for uint; uint internal constant QUARTER = 91 days + 450 minutes; Auctions public auctions; METToken public token; bool public locked = false; uint public deposited; uint public lastWithdrawTime; uint public quarterlyWithdrawable; event Withdrawn(address indexed who, uint amount); event Deposited(address indexed who, uint amount); modifier onlyAuction() { require(msg.sender == address(auctions)); _; } modifier preLock() { require(!locked); _; } modifier postLock() { require(locked); _; } /// @notice Constructor to initialize TokenLocker contract. /// @param _auctions Address of auctions contract /// @param _token Address of METToken contract function TokenLocker(address _auctions, address _token) public { require(_auctions != 0x0); require(_token != 0x0); auctions = Auctions(_auctions); token = METToken(_token); } /// @notice If auctions is initialized, call to this function will result in /// locking of deposited tokens and further deposit of tokens will not be allowed. function lockTokenLocker() public onlyAuction { require(auctions.initialAuctionEndTime() != 0); require(auctions.initialAuctionEndTime() >= auctions.genesisTime()); locked = true; } /// @notice It will deposit tokens into the locker for given beneficiary. /// @param beneficiary Address of the beneficiary, whose tokens are being locked. /// @param amount Amount of tokens being locked function deposit (address beneficiary, uint amount ) public onlyAuction preLock { uint totalBalance = token.balanceOf(this); require(totalBalance.sub(deposited) >= amount); deposited = deposited.add(amount); emit Deposited(beneficiary, amount); } /// @notice This function will allow token withdraw from locker. /// 25% of total deposited tokens can be withdrawn after initial auction end. /// Remaining 75% can be withdrawn in equal amount over 12 quarters. function withdraw() public onlyOwner postLock { require(deposited > 0); uint withdrawable = 0; uint withdrawTime = auctions.initialAuctionEndTime(); if (lastWithdrawTime == 0 && auctions.isInitialAuctionEnded()) { withdrawable = withdrawable.add((deposited.mul(25)).div(100)); quarterlyWithdrawable = (deposited.sub(withdrawable)).div(12); lastWithdrawTime = withdrawTime; } require(lastWithdrawTime != 0); if (now >= lastWithdrawTime.add(QUARTER)) { uint daysSinceLastWithdraw = now.sub(lastWithdrawTime); uint totalQuarters = daysSinceLastWithdraw.div(QUARTER); require(totalQuarters > 0); withdrawable = withdrawable.add(quarterlyWithdrawable.mul(totalQuarters)); if (now >= withdrawTime.add(QUARTER.mul(12))) { withdrawable = deposited; } lastWithdrawTime = lastWithdrawTime.add(totalQuarters.mul(QUARTER)); } if (withdrawable > 0) { deposited = deposited.sub(withdrawable); token.transfer(msg.sender, withdrawable); emit Withdrawn(msg.sender, withdrawable); } } } /// @title Interface for TokenPorter contract. /// Define events and functions for TokenPorter contract interface ITokenPorter { event ExportOnChainClaimedReceiptLog(address indexed destinationMetronomeAddr, address indexed destinationRecipientAddr, uint amount); event ExportReceiptLog(bytes8 destinationChain, address destinationMetronomeAddr, address indexed destinationRecipientAddr, uint amountToBurn, uint fee, bytes extraData, uint currentTick, uint indexed burnSequence, bytes32 indexed currentBurnHash, bytes32 prevBurnHash, uint dailyMintable, uint[] supplyOnAllChains, uint genesisTime, uint blockTimestamp, uint dailyAuctionStartTime); event ImportReceiptLog(address indexed destinationRecipientAddr, uint amountImported, uint fee, bytes extraData, uint currentTick, uint indexed importSequence, bytes32 indexed currentHash, bytes32 prevHash, uint dailyMintable, uint blockTimestamp, address caller); function export(address tokenOwner, bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool); function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool); } /// @title This contract will provide export functionality for tokens. contract TokenPorter is ITokenPorter, Owned { using SafeMath for uint; Auctions public auctions; METToken public token; Validator public validator; ChainLedger public chainLedger; uint public burnSequence = 1; uint public importSequence = 1; bytes32[] public exportedBurns; uint[] public supplyOnAllChains = new uint[](6); /// @notice mapping that tracks valid destination chains for export mapping(bytes8 => address) public destinationChains; /// @notice Initialize TokenPorter contract. /// @param _tokenAddr Address of metToken contract /// @param _auctionsAddr Address of auctions contract function initTokenPorter(address _tokenAddr, address _auctionsAddr) public onlyOwner { require(_tokenAddr != 0x0); require(_auctionsAddr != 0x0); auctions = Auctions(_auctionsAddr); token = METToken(_tokenAddr); } /// @notice set address of validator contract /// @param _validator address of validator contract function setValidator(address _validator) public onlyOwner returns (bool) { require(_validator != 0x0); validator = Validator(_validator); return true; } /// @notice set address of chainLedger contract /// @param _chainLedger address of chainLedger contract function setChainLedger(address _chainLedger) public onlyOwner returns (bool) { require(_chainLedger != 0x0); chainLedger = ChainLedger(_chainLedger); return true; } /// @notice only owner can add destination chains /// @param _chainName string of destination blockchain name /// @param _contractAddress address of destination MET token to import to function addDestinationChain(bytes8 _chainName, address _contractAddress) public onlyOwner returns (bool) { require(_chainName != 0 && _contractAddress != address(0)); destinationChains[_chainName] = _contractAddress; return true; } /// @notice only owner can remove destination chains /// @param _chainName string of destination blockchain name function removeDestinationChain(bytes8 _chainName) public onlyOwner returns (bool) { require(_chainName != 0); require(destinationChains[_chainName] != address(0)); destinationChains[_chainName] = address(0); return true; } /// @notice holds claims from users that have exported on-chain /// @param key is address of destination MET token contract /// @param subKey is address of users account that burned their original MET token mapping (address => mapping(address => uint)) public claimables; /// @notice destination MET token contract calls claimReceivables to record burned /// tokens have been minted in new chain /// @param recipients array of addresses of each user that has exported from /// original chain. These can be generated by ExportReceiptLog function claimReceivables(address[] recipients) public returns (uint) { require(recipients.length > 0); uint total; for (uint i = 0; i < recipients.length; i++) { address recipient = recipients[i]; uint amountBurned = claimables[msg.sender][recipient]; if (amountBurned > 0) { claimables[msg.sender][recipient] = 0; emit ExportOnChainClaimedReceiptLog(msg.sender, recipient, amountBurned); total = total.add(1); } } return total; } /// @notice import MET tokens from another chain to this chain. /// @param _destinationChain destination chain name /// @param _addresses _addresses[0] is destMetronomeAddr and _addresses[1] is recipientAddr /// @param _extraData extra information for import /// @param _burnHashes _burnHashes[0] is previous burnHash, _burnHashes[1] is current burnHash /// @param _supplyOnAllChains MET supply on all supported chains /// @param _importData _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee /// _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, _importData[5] is _dailyMintable /// _importData[6] is _burnSequence, _importData[7] is _dailyAuctionStartTime /// @param _proof proof /// @return true/false function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool) { require(msg.sender == address(token)); require(_importData.length == 8); require(_addresses.length == 2); require(_burnHashes.length == 2); require(validator.isReceiptClaimable(_originChain, _destinationChain, _addresses, _extraData, _burnHashes, _supplyOnAllChains, _importData, _proof)); validator.claimHash(_burnHashes[1]); require(_destinationChain == auctions.chain()); uint amountToImport = _importData[1].add(_importData[2]); require(amountToImport.add(token.totalSupply()) <= auctions.globalMetSupply()); require(_addresses[0] == address(token)); if (_importData[1] == 0) { return false; } if (importSequence == 1 && token.totalSupply() == 0) { auctions.prepareAuctionForNonOGChain(); } token.mint(_addresses[1], _importData[1]); emit ImportReceiptLog(_addresses[1], _importData[1], _importData[2], _extraData, auctions.currentTick(), importSequence, _burnHashes[1], _burnHashes[0], auctions.dailyMintable(), now, msg.sender); importSequence++; chainLedger.registerImport(_originChain, _destinationChain, _importData[1]); return true; } /// @notice Export MET tokens from this chain to another chain. /// @param tokenOwner Owner of the token, whose tokens are being exported. /// @param _destChain Destination chain for exported tokens /// @param _destMetronomeAddr Metronome address on destination chain /// @param _destRecipAddr Recipient address on the destination chain /// @param _amount Amount of token being exported /// @param _extraData Extra data for this export /// @return boolean true/false based on the outcome of export function export(address tokenOwner, bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool) { require(msg.sender == address(token)); require(_destChain != 0x0 && _destMetronomeAddr != 0x0 && _destRecipAddr != 0x0 && _amount != 0); require(destinationChains[_destChain] == _destMetronomeAddr); require(token.balanceOf(tokenOwner) >= _amount.add(_fee)); token.destroy(tokenOwner, _amount.add(_fee)); uint dailyMintable = auctions.dailyMintable(); uint currentTick = auctions.currentTick(); if (burnSequence == 1) { exportedBurns.push(keccak256(uint8(0))); } if (_destChain == auctions.chain()) { claimables[_destMetronomeAddr][_destRecipAddr] = claimables[_destMetronomeAddr][_destRecipAddr].add(_amount); } uint blockTime = block.timestamp; bytes32 currentBurn = keccak256( blockTime, auctions.chain(), _destChain, _destMetronomeAddr, _destRecipAddr, _amount, currentTick, auctions.genesisTime(), dailyMintable, token.totalSupply(), _extraData, exportedBurns[burnSequence - 1]); exportedBurns.push(currentBurn); supplyOnAllChains[0] = token.totalSupply(); emit ExportReceiptLog(_destChain, _destMetronomeAddr, _destRecipAddr, _amount, _fee, _extraData, currentTick, burnSequence, currentBurn, exportedBurns[burnSequence - 1], dailyMintable, supplyOnAllChains, auctions.genesisTime(), blockTime, auctions.dailyAuctionStartTime()); burnSequence = burnSequence + 1; chainLedger.registerExport(auctions.chain(), _destChain, _amount); return true; } } contract ChainLedger is Owned { using SafeMath for uint; mapping (bytes8 => uint) public balance; mapping (bytes8 => bool) public validChain; bytes8[] public chains; address public tokenPorter; Auctions public auctions; event LogRegisterChain(address indexed caller, bytes8 indexed chain, uint supply, bool outcome); event LogRegisterExport(address indexed caller, bytes8 indexed originChain, bytes8 indexed destChain, uint amount); event LogRegisterImport(address indexed caller, bytes8 indexed originChain, bytes8 indexed destChain, uint amount); function initChainLedger(address _tokenPorter, address _auctionsAddr) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); require(_auctionsAddr != 0x0); tokenPorter = _tokenPorter; auctions = Auctions(_auctionsAddr); return true; } function registerChain(bytes8 chain, uint supply) public onlyOwner returns (bool) { require(!validChain[chain]); validChain[chain] = true; chains.push(chain); balance[chain] = supply; emit LogRegisterChain(msg.sender, chain, supply, true); } function registerExport(bytes8 originChain, bytes8 destChain, uint amount) public { require(msg.sender == tokenPorter || msg.sender == owner); require(validChain[originChain] && validChain[destChain]); require(balance[originChain] >= amount); balance[originChain] = balance[originChain].sub(amount); balance[destChain] = balance[destChain].add(amount); emit LogRegisterExport(msg.sender, originChain, destChain, amount); } function registerImport(bytes8 originChain, bytes8 destChain, uint amount) public { require(msg.sender == tokenPorter || msg.sender == owner); require(validChain[originChain] && validChain[destChain]); balance[originChain] = balance[originChain].sub(amount); balance[destChain] = balance[destChain].add(amount); emit LogRegisterImport(msg.sender, originChain, destChain, amount); } } contract Validator is Owned { mapping (bytes32 => mapping (address => bool)) public hashAttestations; mapping (address => bool) public isValidator; mapping (address => uint8) public validatorNum; address[] public validators; address public metToken; address public tokenPorter; mapping (bytes32 => bool) public hashClaimed; uint8 public threshold = 2; event LogAttestation(bytes32 indexed hash, address indexed who, bool isValid); /// @param _validator1 first validator /// @param _validator2 second validator /// @param _validator3 third validator function initValidator(address _validator1, address _validator2, address _validator3) public onlyOwner { // Clear old validators. Validators can be updated multiple times for (uint8 i = 0; i < validators.length; i++) { delete isValidator[validators[i]]; delete validatorNum[validators[i]]; } delete validators; validators.push(_validator1); validators.push(_validator2); validators.push(_validator3); // TODO: This will be NA, Bloq and a third party (escrow or company) at launch, // and should be scripted into deploy isValidator[_validator1] = true; isValidator[_validator2] = true; isValidator[_validator3] = true; validatorNum[_validator1] = 0; validatorNum[_validator2] = 1; validatorNum[_validator3] = 2; } /// @notice set address of token porter /// @param _tokenPorter address of token porter function setTokenPorter(address _tokenPorter) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); tokenPorter = _tokenPorter; return true; } function validateHash(bytes32 hash) public { require(isValidator[msg.sender]); hashAttestations[hash][msg.sender] = true; emit LogAttestation(hash, msg.sender, true); } function invalidateHash(bytes32 hash) public { require(isValidator[msg.sender]); hashAttestations[hash][msg.sender] = false; emit LogAttestation(hash, msg.sender, false); } function hashClaimable(bytes32 hash) public view returns(bool) { if (hashClaimed[hash]) { return false; } uint8 count = 0; for (uint8 i = 0; i < validators.length; i++) { if (hashAttestations[hash][validators[i]]) { count++;} } if (count >= threshold) { return true; } return false; } function claimHash(bytes32 hash) public { require(msg.sender == tokenPorter); require(hashClaimable(hash)); hashClaimed[hash] = true; } function isReceiptClaimable(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChain, uint[] _importData, bytes _proof) public view returns(bool) { // We want to validate that these hash to the provided hash as a safety check, // then we want to know if the hash is Claimable. // Due to stack too deep error and limitation in using number of local // variables we have to use uint array here. // _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee, // _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, // _importData[5] is _dailyMintable, _importData[6] is _burnSequence, // _addresses[0] is _destMetronomeAddr and _addresses[1] is _recipAddr require(_burnHashes[1] == keccak256(_importData[0], _originChain, _destinationChain, _addresses[0], _addresses[1], _importData[1], _importData[3], _importData[4], _importData[5], _supplyOnAllChain[0], _extraData, _burnHashes[0])); if (hashClaimable(_burnHashes[1])) { return true; } return false; } }
Increase allowance of spender _spender Spender of the tokens _value Amount of tokens that can be spent by spender return true/false
function approveMore(address _spender, uint256 _value) public returns (bool) { uint previous = _allowance[msg.sender][_spender]; uint newAllowance = previous.add(_value); _allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; }
624,285
/* solium-disable security/no-block-members */ pragma solidity 0.5.7; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "../token/ITokenContract.sol"; import "../escrow/IEscrow.sol"; /** * @dev This contract will distribute tokens to the buyers who purchase items from * the OB verified sellers * For more information please visit below mentioned link * https://github.com/OB1Company/openbazaar-smart-contracts/issues/10 */ contract OBRewards is Ownable { using SafeMath for uint256; //Mapping of promoted sellers mapping(address => bool) public promotedSellers; uint256 public maxRewardPerSeller; uint256 public maxRewardToBuyerPerSeller; uint256 public totalTokensDistributed; //A time window in seconds where purchases between A and B will be //rewarded with tokens. Ie if a trade is completed satisfactorily at //time X, then the buyer can claim their reward any time after X and //before X + timeWindow. uint256 public timeWindow; //Mapping of seller to all buyers who received rewards by purchasing //from that seller. mapping(address => address[]) sellerVsBuyersArray; //Mapping of seller and buyer to a bool indicating whether the buyers has //claimed any rewards from that seller. mapping(address => mapping(address => bool)) sellerVsBuyersBool; //Given a seller and a buyer, this will return the amount of tokens that //have been rewarded to the buyer for purchasing from the seller. mapping(address => mapping(address => uint256)) sellerVsBuyerRewards; //For each seller, this returns the total number of tokens that have been //given out as rewards for purchasing from that seller. mapping(address => uint256) sellerVsRewardsDistributed; //Escrow contract address which will be used to calculate and validate //transactions IEscrow public escrowContract; //Address of the reward Token to be distributed to the buyers ITokenContract public obToken; //Bool to signify whether reward distribution is active or not bool public rewardsOn; //End date of the promotion uint256 public endDate; event SuccessfulClaim( bytes32 indexed scriptHash, address indexed seller, address indexed buyer, uint256 amount ); event UnsuccessfulClaim( bytes32 indexed scriptHash, address indexed seller, address indexed buyer ); event PromotedSellersAdded(address[] seller); event PromotedSellersRemoved(address[] seller); event RewardsOn(); event EndDateChanged(uint256 endDate); modifier nonZeroAddress(address _address) { require(_address != address(0), "Zero address not allowed"); _; } modifier rewardsRunning() { require( rewardsOn && (endDate > block.timestamp), "Reward distribution is not running" ); _; } /** * @dev Add details to rewards contract at the time of deployment * @param _maxRewardPerSeller Maximum reward to be distributed from * each seller * @param _timeWindow A time window, in seconds, where purchases * will be rewarded with tokens * @param _escrowContractAddress Escrow address to be considered for * rewards distribution. * @param obTokenAddress Address of the reward token */ constructor( uint256 _maxRewardPerSeller, uint256 _timeWindow, address _escrowContractAddress, // this should be a trusted contract address obTokenAddress ) public nonZeroAddress(_escrowContractAddress) nonZeroAddress(obTokenAddress) { require( _maxRewardPerSeller > 0, "Maximum reward must be greater than 0" ); require( _timeWindow > 0, "Time window must be greater than 0" ); maxRewardPerSeller = _maxRewardPerSeller; timeWindow = _timeWindow; escrowContract = IEscrow(_escrowContractAddress); obToken = ITokenContract(obTokenAddress); maxRewardToBuyerPerSeller = uint256(50).mul( 10 ** uint256(obToken.decimals()) ); } /** * @dev Allows owner to add new promoted sellers. Previous ones will * remain untouched * @param sellers List of sellers to be marked as promoted * No Seller out of this list should already be promoted, otherwise * transaction will fail */ function addPromotedSellers( address[] calldata sellers ) external onlyOwner { for (uint256 i = 0; i < sellers.length; i++) { require( sellers[i] != address(0), "Zero address cannot be a promoted seller" ); require( !promotedSellers[sellers[i]], "One of the sellers is already promoted" ); //Also protects against the same being address passed twice. promotedSellers[sellers[i]] = true; } emit PromotedSellersAdded(sellers); } /** * @dev Remove exisiting promoted sellers * @param sellers List of sellers to be removed */ function removePromotedSellers( address[] calldata sellers ) external onlyOwner { for (uint256 i = 0; i < sellers.length; i++) { promotedSellers[sellers[i]] = false; } emit PromotedSellersRemoved(sellers); } /** * @dev Returns list of buyers that have been rewarded for purchasing from * a given seller * @param seller Address of promoted seller * @return buyers List of Buyers */ function getRewardedBuyers( address seller ) external view returns (address[] memory buyers) { buyers = sellerVsBuyersArray[seller]; return buyers; } /** * @dev Return reward info for a buyer against a promoted seller * @param seller Address of promoted seller * @param buyer The buyer who reward info has to be fetched * @return rewardAmount */ function getBuyerRewardInfo( address seller, address buyer ) external view returns( uint256 rewardAmount ) { return sellerVsBuyerRewards[seller][buyer]; } /** * @dev Total reward distributed for a promoted seller so far * @param seller Promoted seller's address * @return Amount of tokens distributed as reward for a seller */ function getDistributedReward( address seller ) external view returns (uint256 rewardDistributed) { rewardDistributed = sellerVsRewardsDistributed[seller]; return rewardDistributed; } /** * @dev Allows the owner of the contract to transfer all remaining tokens to * an address of their choosing. * @param receiver The receiver's address */ function transferRemainingTokens( address receiver ) external onlyOwner nonZeroAddress(receiver) { uint256 amount = obToken.balanceOf(address(this)); obToken.transfer(receiver, amount); } /** * @dev Method to allow the owner to adjust the maximum reward per seller * @param _maxRewardPerSeller Max reward to be distributed for each seller */ function changeMaxRewardPerSeller( uint256 _maxRewardPerSeller ) external onlyOwner { maxRewardPerSeller = _maxRewardPerSeller; } /** * @dev Method to allow the owner to change the timeWindow variable * @param _timeWindow A time window in seconds */ function changeTimeWindow(uint256 _timeWindow) external onlyOwner { timeWindow = _timeWindow; } /** * @dev Returns the number of rewarded buyers associated with a given seller * @param seller Address of the promoted seller */ function noOfRewardedBuyers( address seller ) external view returns (uint256 size) { size = sellerVsBuyersArray[seller].length; return size; } /** * @dev Method to get rewarded buyer address at specific index for a seller * @param seller Seller for whom the rewarded buyer is requested * @param index Index at which buyer has to be retrieved */ function getRewardedBuyer( address seller, uint256 index ) external view returns (address buyer) { require( sellerVsBuyersArray[seller].length > index, "Array index out of bound" ); buyer = sellerVsBuyersArray[seller][index]; return buyer; } /** * @dev Allows the owner of the contract to turn on the rewards distribution * Only if it was not previously turned on */ function turnOnRewards() external onlyOwner { require(!rewardsOn, "Rewards distribution is already on"); rewardsOn = true; emit RewardsOn(); } /** * @dev ALlows owner to set endDate * @param _endDate date the promotion ends */ function setEndDate(uint256 _endDate) external onlyOwner { require( _endDate > block.timestamp, "End date should be greater than current date" ); endDate = _endDate; emit EndDateChanged(endDate); } function isRewardsRunning() external view returns (bool running) { running = rewardsOn && (endDate > block.timestamp); return running; } /** * @dev Buyer can call this method to calculate the reward for their * transaction * @param scriptHash Script hash of the transaction */ function calculateReward( bytes32 scriptHash ) public view returns (uint256 amount) { ( address buyer, address seller, uint8 status, uint256 lastModified ) = _getTransaction(scriptHash); amount = _getTokensToReward( scriptHash, buyer, seller, status, lastModified ); return amount; } /** * @dev Using this method user can choose to execute their transaction and * claim their rewards in one go. This will save one transaction. * Users can only use this method if their trade is using escrowContract * for escrow. * See the execute() method Escrow.sol for more information. */ function executeAndClaim( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, bytes32 scriptHash, address[] memory destinations, uint256[] memory amounts ) public rewardsRunning { //1. Execute transaction //SECURITY NOTE: `escrowContract` is a known and trusted contract, but //the `execute` function transfers ETH or Tokens, and therefore hands //over control of the logic flow to a potential attacker. escrowContract.execute( sigV, sigR, sigS, scriptHash, destinations, amounts ); //2. Claim Reward bytes32[] memory scriptHashes = new bytes32[](1); scriptHashes[0] = scriptHash; claimRewards(scriptHashes); } /** * @dev Function to claim tokens * @param scriptHashes Array of scriptHashes of OB trades for which * the buyer wants to claim reward tokens. * Note that a Buyer can perform trades with multiple promoted sellers and * then can claim their reward tokens all at once for all those trades using * this function. * Be mindful of the block gas limit (do not pass too many scripthashes). */ function claimRewards( bytes32[] memory scriptHashes ) public rewardsRunning { require(scriptHashes.length > 0, "No script hash passed"); for (uint256 i = 0; i < scriptHashes.length; i++) { //1. Get the transaction from Escrow contract ( address buyer, address seller, uint8 status, uint256 lastModified ) = _getTransaction(scriptHashes[i]); //2. Check that the transaction exists //3. Check seller is promoted seller and the //timeWindow has not closed //4. Get the number of tokens to be given as reward //5. The seller must be one of the beneficiaries uint256 rewardAmount = _getTokensToReward( scriptHashes[i], buyer, seller, status, lastModified ); uint256 contractBalance = obToken.balanceOf(address(this)); if (rewardAmount > contractBalance) { rewardAmount = contractBalance; } if (rewardAmount == 0) { emit UnsuccessfulClaim(scriptHashes[i], seller, buyer); continue; } //6. Update state if (!sellerVsBuyersBool[seller][buyer]) { sellerVsBuyersBool[seller][buyer] = true; sellerVsBuyersArray[seller].push(buyer); } sellerVsBuyerRewards[seller][buyer] = sellerVsBuyerRewards[ seller ][ buyer ].add(rewardAmount); sellerVsRewardsDistributed[seller] = sellerVsRewardsDistributed[ seller ].add(rewardAmount); totalTokensDistributed = totalTokensDistributed.add(rewardAmount); //7. Emit event emit SuccessfulClaim( scriptHashes[i], seller, buyer, rewardAmount ); //8. Transfer token obToken.transfer(buyer, rewardAmount); } } //Private method to get transaction info out from the escrow contract function _getTransaction( bytes32 _scriptHash ) private view returns( address buyer, address seller, uint8 status, uint256 lastModified ) { // calling a trusted contract's view function ( , lastModified, status, ,,, buyer, seller, ) = escrowContract.transactions(_scriptHash); return (buyer, seller, status, lastModified); } /** * @dev Checks -: * 1. If transaction exists * 2. If seller is promoted * 3. Transaction has been closed/released * 4. Transaction happened with the time window. * 5. Seller must be one of the beneficiaries of the transaction execution * @param scriptHash Script hash of the transaction * @param buyer Buyer in the transaction * @param seller Seller in the transaction * @param status Status of the transaction * @param lastModified Last modified time of the transaction * @return bool Returns whether transaction is valid and eligible * for rewards */ function _verifyTransactionData( bytes32 scriptHash, address buyer, address seller, uint8 status, uint256 lastModified ) private view returns (bool verified) { verified = true; if (buyer == address(0)) { //If buyer is a zero address then we treat the transaction as //a not verified verified = false; } else if (!promotedSellers[seller]) { //seller of the transaction is not a promoted seller verified = false; } else if (status != 1) { //Transaction has not been released verified = false; } else if ( //Calling a trusted contract's view function !escrowContract.checkVote(scriptHash, seller) ) { //Seller was not one of the signers verified = false; } else if ( //Calling a trusted contract's view function !escrowContract.checkBeneficiary(scriptHash, seller) ) { //Seller was not one of the beneficiaries. //This means the transaction was either cancelled or //completely refunded. verified = false; } else if (lastModified.add(timeWindow) < block.timestamp) { //timeWindow has been exceeded verified = false; } return verified; } /** * @dev Private function to get Tokens to be distributed as reward * Checks whether transaction is verified or not and computes the * amount of the rewards using the _calculateReward() method */ function _getTokensToReward( bytes32 scriptHash, address buyer, address seller, uint8 status, uint256 lastModified ) private view returns (uint256 amount) { if ( !_verifyTransactionData( scriptHash, buyer, seller, status, lastModified ) ) { amount = 0; } else { amount = _calculateReward(buyer, seller); } return amount; } /** * @dev Private function to calculate reward. * Please see link for rewards calculation algo * https://github.com/OB1Company/openbazaar-smart-contracts/issues/10 */ function _calculateReward( address buyer, address seller ) private view returns (uint256 amount) { if (sellerVsRewardsDistributed[seller] >= maxRewardPerSeller) { //No more rewards can be distributed for buying from the //given seller amount = 0; } else { //maxRewardToBuyerPerSeller tokens will be given to each buyer per //seller until the maximum amount of rewards for the seller has //been exhausted amount = maxRewardToBuyerPerSeller.sub(sellerVsBuyerRewards[seller][buyer]); //Check that we are not disbursing more rewards than are //allocated per seller if (sellerVsRewardsDistributed[seller].add(amount) > maxRewardPerSeller) { amount = maxRewardPerSeller.sub(sellerVsRewardsDistributed[seller]); } } return amount; } }
Allows owner to add new promoted sellers. Previous ones will remain untouched sellers List of sellers to be marked as promoted No Seller out of this list should already be promoted, otherwise transaction will fail/
function addPromotedSellers( address[] calldata sellers ) external onlyOwner { for (uint256 i = 0; i < sellers.length; i++) { require( sellers[i] != address(0), "Zero address cannot be a promoted seller" ); require( !promotedSellers[sellers[i]], "One of the sellers is already promoted" promotedSellers[sellers[i]] = true; } emit PromotedSellersAdded(sellers); }
5,344,213
//pragma solidity >=0.4.21 <0.6.0; pragma experimental ABIEncoderV2; import "./Registry.sol"; contract Market is Registry{ //////////////////////////////// // AUCTION CONFIG & FUNCTIONS // //////////////////////////////// uint public biddingEnd = 0; struct OrderStruct { uint256 id; bytes32 _type; uint256 next; address owner; uint256 volume; int256 price; } struct Matching{ uint256 orderId; uint256 volume; } int256 public matchingPrice; uint256 public share; uint256 public cumAskVol; uint256 public cumBidVol; bool DEBUG = true; // maps order id to order objects OrderStruct[] public orders; //Public Variables uint256 idCounter; uint256 public period = 0; uint256 public minAsk = 0; uint256 public maxBid = 0; uint8 currState; bool isMatchingDone = false; // stores matching results mapping(uint256 => mapping(address => uint256)) public matchedAskOrderMapping; mapping(uint256 => mapping(address => uint256)) public matchedBidOrderMapping; mapping(uint256 => int256) public matchingPriceMapping; uint256[] public currMatchedAskOrderMapping; uint256[] public currMatchedBidOrderMapping; //EVENTS event StartAuction (bool); event LogNewBid (int256 _price, uint256 _volume); event PRICE(int256); event LogNewAsk (int256 _price, uint256 _volume); event MatchedPrice (int256); event isMatch(bool); constructor() public { identity[msg.sender] = 1; startAuction(period); } // Auction can only be started by the Administrator authority // The auction starts with the state 0 which is the Trading Phase function startAuction (uint256 period) public /*onlyAuthorities*/ returns (bool) { if(period != 0) { require(now >= biddingEnd, "Trading phase still running"); } reset(); emit StartAuction(true); return true; } event Settlement(bool); // settlement can only be started by the Administrator authority // The settlement starts only after the Trading Phase is completed (state 1: which is the Settlement Phase) function settlement (uint256 period) public /*onlyAuthorities*/ returns (bool){ updateState(1); emit Settlement(true); return true; } /* // Set a new period to start only after the previous Trading and settlement phase are finished function newTradingPeriod() public onlyAuthorities { // require(owner == msg.sender); require(now >= biddingEnd, "Trading phase still running"); //only if the current phase is on state 1 - Settlement phase the new trading phase can start biddingEnd = now + _biddingTime; // Call reset function to start everything new (all bids and asks) for the new trading period reset(); }*/ // reset function to reset bids and asks function reset() public { isMatchingDone = false; delete orders; // insert blank order into orders because idx=0 is a placeholder OrderStruct memory blank_order = OrderStruct(0,0, 0, address(0), 0, 0); orders.push(blank_order); idCounter = 1; minAsk = 0; maxBid = 0; updateState(0); } // Auction state function execution modifier onlyInState(uint8 _state) { updateState(_state); if(_state != currState && !DEBUG) revert(); _; } event UpdateState (uint8 _state); /* State 0: Trading phase (bid and ask orders are accepted) State 1: Settlement Phase (Market price: matching function executed) */ function updateState(uint8 _state) internal { if (_state == 0) { emit UpdateState(_state); if (tradingState(15 minutes) && currState != 0) { currState = 0; } } else if (_state == 1){ emit UpdateState(_state); if (settlementState() && currState != 1 ) { currState = 1; matching(); } } else { reset(); } } function tradingState(uint _biddingTime) internal returns (bool rv) { biddingEnd = now + _biddingTime; if (now < biddingEnd) { return true; } return false; } function settlementState() internal view returns (bool rv) { if (now >= biddingEnd) { return true; } revert (); } ///////////////////////////////////// // ORDER BOOK - BID AND ASK ORDERS // ///////////////////////////////////// //Bids can only be send by users function submitBid(int256 _price, uint256 _volume) public /*onlyUsers*/ { // require(now <= biddingEnd,"Trading phase already ended or did not start yet!"); save_Bid_Orders("BID", _price, _volume); emit LogNewBid(_price, _volume); } //Asks can only be send by SM addresses function submitAsk(int256 _price, uint256 _volume) public /*onlySmartMeters*/ { // require(now <= biddingEnd,"Trading phase already ended or did not start yet!"); save_Ask_Orders("ASK", _price, _volume); emit LogNewAsk(_price,_volume); } // process order saving function save_Ask_Orders(bytes32 _type, int256 _price, uint256 _volume) internal { // allocate new order OrderStruct memory curr_order = OrderStruct(idCounter++, _type, 0, msg.sender, _volume, _price); uint256 best_order; int8 ascending = 1; best_order = minAsk; ascending = 1; // save and return if this the first bid if (best_order == 0) { orders.push(curr_order); best_order = curr_order.id; } else { // iterate over list till same price encountered uint256 curr = best_order; uint256 prev = 0; while ((ascending * curr_order.price) > (ascending * orders[curr].price) && curr != 0) { prev = curr; curr = orders[curr].next; } // update pointer curr_order.next = curr; // insert order orders.push(curr_order); // curr_order added at the end if (curr_order.next == best_order) { best_order = curr_order.id; // at least one prev order exists } else { orders[prev].next = curr_order.id; } } minAsk = best_order; } function save_Bid_Orders(bytes32 _type, int256 _price, uint256 _volume) internal { // allocate new order OrderStruct memory curr_order = OrderStruct(idCounter++, _type, 0, msg.sender, _volume, _price); uint256 best_order; int8 ascending = -1; best_order = maxBid; // save and return if this the first bid if (best_order == 0) { orders.push(curr_order); best_order = curr_order.id; } else { // iterate over list till same price encountered uint256 curr = best_order; uint256 prev = 0; while ((ascending * curr_order.price) > (ascending * orders[curr].price) && curr != 0) { prev = curr; curr = orders[curr].next; } // update pointer curr_order.next = curr; // insert order orders.push(curr_order); // curr_order added at the end if (curr_order.next == best_order) { best_order = curr_order.id; // at least one prev order exists } else { orders[prev].next = curr_order.id; } } maxBid = best_order; } // match bid and ask orders function matching() public /*onlyAuthorities*/ /*onlyInState(1)*/ returns (int256) { if (orders.length == 1) { reset(); revert(); } cumAskVol = 0; cumBidVol = 0; matchingPrice = orders[minAsk].price; bool isMatched = false; bool outOfAskOrders = false; uint256 currAsk = minAsk; uint256 currBid = maxBid; period++; uint256 next; // uint256 share; delete currMatchedAskOrderMapping; delete currMatchedBidOrderMapping; while (!isMatched) { // cumulates ask volume for fixed price level while (currAsk != 0 && orders[currAsk].price == matchingPrice) { // uint256 volume = orders[currAsk].volume; address owner = orders[currAsk].owner; cumAskVol += orders[currAsk].volume; matchedAskOrderMapping[period][owner] = orders[currAsk].volume; currMatchedAskOrderMapping.push(orders[currAsk].id); next = orders[currAsk].next; if (next != 0) { currAsk = next; } else { outOfAskOrders = true; break; } } // cumulates ask volume for order price greater then or equal to matching price while (orders[currBid].price >= matchingPrice) { // uint256 volume = orders[currBid].volume; address owner = orders[currBid].owner; cumBidVol += orders[currBid].volume; matchedBidOrderMapping[period][owner] = orders[currBid].volume; currMatchedBidOrderMapping.push(orders[currBid].id); currBid = orders[currBid].next; if (currBid == 0) { break; } } if (cumAskVol >= cumBidVol || outOfAskOrders) { isMatched = true; emit isMatch(true); } else { matchingPrice = orders[currAsk].price; currBid = maxBid; cumBidVol = 0; delete currMatchedBidOrderMapping; } } /* // calculates how much volume each producer can release into // the grid within the next interval if (cumBidVol < cumAskVol) { //FLOATING DATA TYPEPES PROBLEM: Division with precsion to 2 decimals!!! // share = cumBidVol / cumAskVol; // share = cumBidVol*(10**5)/cumAskVol; share = div(cumBidVol,cumAskVol); for (uint256 i=0; i<currMatchedAskOrderMapping.length; i++) { matchedAskOrderMapping[period][orders[currMatchedAskOrderMapping[i]].owner] = orders[currMatchedAskOrderMapping[i]].volume * share; } } else { // share = cumAskVol*(10**5)/cumBidVol; share = div(cumAskVol,cumBidVol); for (uint256 j=0; j<currMatchedBidOrderMapping.length; j++) { matchedBidOrderMapping[period][orders[currMatchedBidOrderMapping[j]].owner] = orders[currMatchedBidOrderMapping[j]].volume * share; } }*/ matchingPriceMapping[period] = matchingPrice; emit MatchedPrice(matchingPrice); return matchingPrice; } /* function getNextIntervalShare(uint256 _period, address _owner) public returns (uint256){ return matchedAskOrderMapping[_period][_owner]; }*/ // DEBUGGING FUNCTIONS // ========================== function getOrderIdLastOrder() public view returns(uint256) { if (idCounter == 1) { return 0; } return idCounter-1; } //Returns ordered list of bid orders int256[] bidQuotes; uint256[] bidAmounts; function getBidOrder() public returns (int256[] memory rv1, uint256[] memory rv2) { uint256 id_iter_bid = maxBid; bidQuotes = rv1; bidAmounts = rv2; while (orders[id_iter_bid].volume != 0) { bidAmounts.push(orders[id_iter_bid].volume); bidQuotes.push(orders[id_iter_bid].price); id_iter_bid = orders[id_iter_bid].next; } return (bidQuotes, bidAmounts); } // Returns ordered list of ask orders int256[] askQuotes; uint256[] askAmounts; function getAskOrder() public payable returns (int256[] memory rv1, uint256[] memory rv2) { uint256 id_iter_ask = minAsk; askQuotes = rv1; askAmounts = rv2; while (orders[id_iter_ask].volume != 0) { askQuotes.push(orders[id_iter_ask].price); askAmounts.push(orders[id_iter_ask].volume); id_iter_ask = orders[id_iter_ask].next; } return (askQuotes, askAmounts); } //HELPER FUNCTIONS function getStruct()public view returns(OrderStruct[] memory){ return orders; } function getOrderId(uint256 _orderId) public view returns(uint256) { return orders[_orderId].id; } function getOrdersLength() public view returns(uint){ return orders.length -1; } function getOrderNext(uint256 _orderId) public view returns(uint256) { return orders[_orderId].next; } function getOrderPrice(uint256 _orderId)public view returns(int256) { return orders[_orderId].price; } function getOrderVolume(uint256 _orderId) public view returns(uint256) { return orders[_orderId].volume; } function getOrdersByIndex(uint index) external view returns (uint256 id, bytes32 _type, uint256 next, address owner, uint256 volume, int256 price) { return (orders[index].id, orders[index]._type, orders[index].next, orders[index].owner, orders[index].volume, orders[index].price); } function getmatchedAskOrderMapping (uint256 _period, address _owner) public view returns (uint256){ return matchedAskOrderMapping[_period][_owner]; } function getmatchedBidOrderMapping (uint256 _period, address _owner) public view returns (uint256){ return matchedBidOrderMapping[_period][_owner]; } function matchedBidOrderListLength() external view returns (uint) { return currMatchedBidOrderMapping.length; } function matchedAskOrderListLength() external view returns (uint) { return currMatchedAskOrderMapping.length; } function getMatchingPricePeriod(uint256 _period) public view returns (int256){ return matchingPriceMapping[_period]; } function getOrdersCount() external view returns(uint) { return orders.length; } ///Safe Math Checks for number overflow 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) { require(b <= a, "SafeMath: subtraction overflow"); 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. 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) { // 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; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } // MODIFIERS // ========================== modifier onlyAuthorities() { if (identity[msg.sender] != 1) revert(); _; } modifier onlySmartMeters() { if (identity[msg.sender] != 2) revert(); _; } modifier onlyUsers() { if (identity[msg.sender] == 0) revert(); _; } }
require(owner == msg.sender);only if the current phase is on state 1 - Settlement phase the new trading phase can start Call reset function to start everything new (all bids and asks) for the new trading period
function newTradingPeriod() public onlyAuthorities { require(now >= biddingEnd, "Trading phase still running"); biddingEnd = now + _biddingTime; reset(); }*/
5,445,726
pragma solidity ^0.4.18; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/ContestManager.sol"; import "../contracts/Contest.sol"; contract TestContestManager { ContestManager cm = new ContestManager(); function testBalanceOf0() public { uint b = cm.balanceOf(0); Assert.equal(b, 0, "testBalanceOf() failed, balance should be 0"); } function testAddTokens() public { cm.addTokens(10,address(this)); Assert.equal(10, cm.balanceOf(address(this)), "testAddTokens() failed, balance should be 10"); } function testNewContest() public { Contest contest = Contest(cm.newContest(1525937318, 1525937319, "testNewContest",100, 2)); Assert.equal(address(cm), address(contest.cm()), "testNewContest() failed, bad contest->cm"); Assert.equal(cm.contests(contest), true, "testNewContest() failed, ContestManager->contests[] array not updated"); } function testClaimTicket() public { // solium-disable-next-line security/no-block-members uint contestdeadline = now + 86400; // contest is tomorrow! Contest contest = Contest(cm.newContest(contestdeadline, contestdeadline + 1, "testClaimTicket",100, 2)); Assert.equal(10, cm.balanceOf(address(this)), "testClaimTicket() failed, initial balance should be 10"); Assert.equal(false, contest.claimedTickets(address(this)), "testClaimTicket() failed, ticket is already claimed"); Assert.equal(contest.claimTicket(), true, "testClaimTicket() failed"); Assert.equal(8, cm.balanceOf(address(this)), "testClaimTicket() failed, final balance should be 8"); Assert.equal(true, contest.claimedTickets(address(this)), "testClaimTicket() failed, ticket is unclaimed"); } function testClaimLastTicket() public { // solium-disable-next-line security/no-block-members uint contestdeadline = now + 86400; // contest is tomorrow! Contest contest = Contest(cm.newContest(contestdeadline, contestdeadline + 1, "testClaimLastTicket", 1, 2)); Assert.equal(contest.claimTicket(), true, "testClaimLastTicket() failed"); Assert.equal(6, cm.balanceOf(address(this)), "testClaimLastTicket() failed, final balance should be 6"); Assert.equal(true, contest.claimedTickets(address(this)), "testClaimLastTicket() failed, ticket is unclaimed"); } function testSpendLastToken() public { // solium-disable-next-line security/no-block-members uint contestdeadline = now + 86400; // contest is tomorrow! Contest contest = Contest(cm.newContest(contestdeadline, contestdeadline + 1, "testClaimTicket",100, 2)); cm.setTotalTokens(address(this), 2); contest.claimTicket(); Assert.equal(0, cm.balanceOf(address(this)), "testSpendLastToken() failed, final balance should be 0"); Assert.equal(true, contest.claimedTickets(address(this)), "testSpendLastToken() failed, ticket is unclaimed"); } function testFreeTicket() public { // solium-disable-next-line security/no-block-members uint contestdeadline = now + 86400; // contest is tomorrow! Contest contest = Contest(cm.newContest(contestdeadline, contestdeadline + 1, "testFreeTicket",100, 2)); cm.setTotalTokens(address(this), 2); contest.claimTicket(); Assert.equal(true, contest.freeTicket(), "testFreeTicket() failed, freeTicket() failed"); Assert.equal(1, cm.balanceOf(address(this)), "testFreeTicket() failed, balance should be 1"); Assert.equal(false, contest.claimedTickets(address(this)), "testFreeTicket() failed, ticket is claimed"); Assert.equal(100, contest.availableTickets(), "testFreeTicket() failed, availableTickets should be 100"); } }
solium-disable-next-line security/no-block-members
function testClaimLastTicket() public { Contest contest = Contest(cm.newContest(contestdeadline, contestdeadline + 1, "testClaimLastTicket", 1, 2)); Assert.equal(contest.claimTicket(), true, "testClaimLastTicket() failed"); Assert.equal(6, cm.balanceOf(address(this)), "testClaimLastTicket() failed, final balance should be 6"); Assert.equal(true, contest.claimedTickets(address(this)), "testClaimLastTicket() failed, ticket is unclaimed"); }
12,800,430
./partial_match/1/0x69f942b6AAa653d722777549808da96935442745/sources/Mis.sol
Transfer `amount` tokens from `msg.sender` to `dst` dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/
function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Mis::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; }
2,834,512
// SPDX-License-Identifier: MIT pragma solidity ^0.6.1; import "./AdminManager.sol"; import "./Verifier.sol"; import {GLibrary} from "./GLibrary.sol"; /// @title GardenManager contract /// @author Aymeric NOEL <[email protected]> /// @notice this contract is used to automatically manage the rental of gardens directly between owners and tenants contract GardenManager { Verifier public VerifierContract; AdminManager public AManager; uint public GardenCount; mapping (uint=>GLibrary.Garden) public AllGarden; /// @dev This variable is used to retrieve the tenant's public key once he/she has signed this. bytes7 public signMe = "sign me"; /// @dev Emitted when a new garden is created /// @param _owner garden's owner /// @param _gardenIndex garden index event NewGarden(address _owner, uint _gardenIndex); constructor (address _adminContract, address _verifierContract) public { AManager = AdminManager(_adminContract); VerifierContract = Verifier(_verifierContract); } modifier OnlyContractAdmin { require(msg.sender == address(AManager), "Not administrator contract"); _; } modifier OnlyOwner(uint gardenIndex){ require(AllGarden[gardenIndex].owner==msg.sender, "Not garden owner"); _; } modifier OnlyValidProof(uint _gardenIndex, uint[2] memory _proofA, uint[2][2] memory _proofB, uint[2] memory _proofC){ require(VerifierContract.verifyTx(_proofA,_proofB,_proofC,AllGarden[_gardenIndex].secretHash), "Proof of secret invalid"); _; } function getGardenById(uint _gardenIndex)external view returns(address payable owner, bool multipleOwners, address payable[] memory coOwners, GLibrary.GardenType gardenType, string memory district, uint32 area, uint[2] memory secretHash, string memory contact, GLibrary.Status status, uint rentLength){ GLibrary.Garden memory garden = AllGarden[_gardenIndex]; return (garden.owner, garden.multipleOwners, garden.coOwners, garden.gardenType, garden.district,garden.area, garden.secretHash, garden.contact,garden.status, garden.rents.length); } function getRentByGardenAndRentId(uint _gardenIndex, uint _rentId) external view returns(int rate, uint duration, uint price, uint beginning, uint balance, address payable tenant, bytes memory signature, bytes32 gardenHashCode){ GLibrary.Rent memory rent = AllGarden[_gardenIndex].rents[_rentId]; return(rent.rate,rent.duration,rent.price,rent.beginning,rent.balance,rent.tenant,rent.signature,rent.accessCode.hashCode); } function getAccessCodeByGardenId(uint _gardenIndex)external view returns(string memory encryptedCode){ GLibrary.Rent memory rent = getLastRentForGarden(_gardenIndex); require(msg.sender==rent.tenant || msg.sender==AllGarden[_gardenIndex].owner,"Caller must be the tenant or the owner"); return(rent.accessCode.encryptedCode); } function modifyVerifierContract(address _verifierContract) public OnlyContractAdmin returns(address){ VerifierContract = Verifier(_verifierContract); return _verifierContract; } /// @dev Use this function to add a new garden. /// @param _secretHash hash of the user' secret; must be in decimal form int[2] /// @param _district district of the garden /// @param _area area of the garden /// @param _contact contact of the owner /// @param _gardenType gardenType of the garden /// @param _multipleOwners boolean that represents multiple owners for a garden or not /// @param _coOwners in case of multiple owners : all owners' addresses, could be empty function createGarden(uint[2] calldata _secretHash, string calldata _district,uint32 _area, string calldata _contact, GLibrary.GardenType _gardenType, bool _multipleOwners, address payable[] calldata _coOwners) external{ GardenCount++; GLibrary.Garden storage garden = AllGarden[GardenCount]; garden.area=_area; garden.contact=_contact; garden.gardenType=_gardenType; garden.secretHash=_secretHash; garden.district=_district; garden.status=GLibrary.Status.Waiting; garden.owner=msg.sender; if(_multipleOwners){ garden.multipleOwners=true; garden.coOwners=_coOwners; } AManager.addGarden(GardenCount, _secretHash); emit NewGarden(msg.sender, GardenCount); } /// @dev Use this function to update the contact of a garden. /// The caller must be the garden's owner. /// @param _gardenIndex the Id of the garden /// @param _contact the new contact of the garden function updateGardenContact(uint _gardenIndex, string calldata _contact) external OnlyOwner(_gardenIndex) { AllGarden[_gardenIndex].contact =_contact; } /// @dev Use this function to update the secret of the secret of a garden. /// The caller must be the garden's owner and must prove it by sending the preimage of the secret hash. /// @param _gardenIndex the Id of the garden /// @param _proofA the first part of the proof /// @param _proofB the second part of the proof /// @param _proofC the third part of the proof /// @param _newSecretHash the new hash of the secret's garden function updateGardenSecretHash(uint _gardenIndex, uint[2] calldata _proofA, uint[2][2] calldata _proofB, uint[2] calldata _proofC, uint[2] calldata _newSecretHash) external OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ AllGarden[_gardenIndex].secretHash =_newSecretHash; } /// @dev Use this function to accept a new garden and open it to location. /// The caller must be the admin contract. /// @param _gardenIndex the Id of the garden function acceptGarden(uint _gardenIndex) public OnlyContractAdmin { AllGarden[_gardenIndex].status= GLibrary.Status.Free; } /// @dev Use this function to reject a new garden and blacklist it. /// The caller must be the admin contract. /// @param _gardenIndex the Id of the garden function rejectGarden(uint _gardenIndex) public OnlyContractAdmin{ AllGarden[_gardenIndex].status= GLibrary.Status.Blacklist; } function getLastRentForGarden(uint _gardenIndex) private view returns(GLibrary.Rent storage){ return AllGarden[_gardenIndex].rents[AllGarden[_gardenIndex].rents.length-1]; } /// @dev Use this function to propose a new location offer. /// The caller must be the owner, after agreement with the tenant offchain. /// @param _gardenIndex the Id of the garden /// @param _tenant tenant's garden /// @param _rentingDuration duration of the location /// @param _price price of the location /// @param _proofA the first part of the proof /// @param _proofB the second part of the proof /// @param _proofC the third part of the proof function proposeGardenOffer(uint _gardenIndex, address payable _tenant, uint _rentingDuration, uint _price, uint[2] calldata _proofA, uint[2][2] calldata _proofB, uint[2] calldata _proofC) external OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ require(AllGarden[_gardenIndex].status==GLibrary.Status.Free, "Garden not free"); GLibrary.Garden storage garden = AllGarden[_gardenIndex]; garden.status= GLibrary.Status.Blocked; garden.rents.push(); GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); lastRent.duration=_rentingDuration; lastRent.price=_price; lastRent.tenant=_tenant; lastRent.rate=-1; } /// @dev Use this function to delete an offer that has not received any response. /// Ownly the garden's owner could call and only if an offer is running. /// @param _gardenIndex the Id of the garden /// @param _proofA the first part of the proof /// @param _proofB the second part of the proof /// @param _proofC the third part of the proof function deleteGardenOffer(uint _gardenIndex, uint[2] calldata _proofA, uint[2][2] calldata _proofB, uint[2] calldata _proofC) external OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ require(AllGarden[_gardenIndex].status== GLibrary.Status.Blocked,"No offer running"); AllGarden[_gardenIndex].status= GLibrary.Status.Free; AllGarden[_gardenIndex].rents.pop(); } /// @dev Use this function to accept a location offer. /// Caller must be the tenant. /// @param _gardenIndex the Id of the garden /// @param _signature the signature of the parameter @signMe, used by the owner to encrypt garden access code function acceptGardenOffer(uint _gardenIndex, bytes calldata _signature)external payable{ GLibrary.Garden storage garden = AllGarden[_gardenIndex]; GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); require(garden.status== GLibrary.Status.Blocked, "No offer running"); require(lastRent.tenant== msg.sender, "Not the correct tenant"); require(lastRent.price <= msg.value, "Insufficient amount"); lastRent.balance=msg.value; lastRent.signature=_signature; garden.status=GLibrary.Status.CodeWaiting; } /// @dev Use this function to add access code to a garden. /// The caller must be the garden's owner and prove it. /// @param _gardenIndex the Id of the garden /// @param _proofA the first part of the proof /// @param _proofB the second part of the proof /// @param _proofC the third part of the proof /// @param _hashCode the hash of the access code /// @param _encryptedCode the code encrypted with the tenant's public key function addAccessCodeToGarden(uint _gardenIndex, uint[2] memory _proofA, uint[2][2] memory _proofB, uint[2] memory _proofC, bytes32 _hashCode,string memory _encryptedCode) public OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ require(AllGarden[_gardenIndex].status==GLibrary.Status.CodeWaiting,"No location running"); GLibrary.Garden storage garden = AllGarden[_gardenIndex]; GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); lastRent.beginning=block.timestamp; lastRent.accessCode=GLibrary.AccessCode(_hashCode,_encryptedCode); garden.status=GLibrary.Status.Location; } /// @dev Use this function to get refund and to cancel a location only if access code is missing. /// @param _gardenIndex the Id of the garden function getRefundBeforeLocation(uint _gardenIndex) external { require(AllGarden[_gardenIndex].status==GLibrary.Status.CodeWaiting,"Code is not missing"); GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); require(lastRent.tenant==msg.sender,"Not the tenant"); uint balance = lastRent.balance; AllGarden[_gardenIndex].status=GLibrary.Status.Free; lastRent.balance =0; msg.sender.transfer(balance); } function transferPaymentToMultipleOwners(uint _amount, GLibrary.Garden memory _garden) internal { for (uint i = 0; i < _garden.coOwners.length; i++) { _garden.coOwners[i].transfer(_amount); } } /// @dev Use the function to update location status after location and get payment. /// The caller must be the garden's owner. /// @param _gardenIndex the Id of the garden /// @param _proofA the first part of the proof /// @param _proofB the second part of the proof /// @param _proofC the third part of the proof function updateLocationStatusAndGetPayment(uint _gardenIndex, uint[2] calldata _proofA, uint[2][2] calldata _proofB, uint[2] calldata _proofC)external OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); GLibrary.Garden storage garden = AllGarden[_gardenIndex]; require(garden.status!= GLibrary.Status.Dispute, "Dispute is running"); require(isRentOver(lastRent.beginning,lastRent.duration),"Location not over"); uint balance = lastRent.balance; lastRent.balance=0; lastRent.accessCode.hashCode= 0; AllGarden[_gardenIndex].status=GLibrary.Status.Free; if(garden.multipleOwners){ uint payroll = balance/garden.coOwners.length; transferPaymentToMultipleOwners(payroll,garden); }else{ garden.owner.transfer(balance); } } /// @dev Tenant should use this function to add a grade to his locations between 1 and 5. /// @param _gardenIndex the Id of the garden /// @param _grade the given grade /// @return saved : true if saved, false either function addGradeToGarden(uint _gardenIndex, int _grade)external returns(bool saved){ require(_grade<6 && _grade >=0, "Grade is not in range 0-5"); saved=false; GLibrary.Rent[] storage allRents = AllGarden[_gardenIndex].rents; for (uint i = 0; i < allRents.length; i++) { if(msg.sender== allRents[i].tenant && allRents[i].rate==int(-1) && isRentOver(allRents[i].beginning,allRents[i].duration)){ allRents[i].rate=_grade; saved=true; } } return saved; } /// @dev Use this function to add a dispute in case of disagreement between owner and tenant. /// @param _gardenIndex the Id of the garden function addDispute(uint _gardenIndex) public { require(AllGarden[_gardenIndex].status==GLibrary.Status.Location,"No location running"); GLibrary.Rent memory lastRent = getLastRentForGarden(_gardenIndex); require(lastRent.tenant==msg.sender || AllGarden[_gardenIndex].owner==msg.sender,"Not the tenant nor the owner"); AllGarden[_gardenIndex].status = GLibrary.Status.Dispute; AManager.addDispute(_gardenIndex,lastRent.balance); } /// @dev Use this function to close a dispute and give back ether amounts to correct people. /// Must be call by the admin contract. /// @param _gardenIndex the Id of the garden /// @param _ownerAmount amount for the owner /// @param _tenantAmount amount for the tenant function closeDispute(uint _gardenIndex, uint _ownerAmount, uint _tenantAmount) public OnlyContractAdmin{ GLibrary.Garden storage garden = AllGarden[_gardenIndex]; require(garden.status==GLibrary.Status.Dispute, "No dispute running"); GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); if(_tenantAmount!=0){ lastRent.tenant.transfer(_tenantAmount); } if(_ownerAmount!=0){ if(garden.multipleOwners){ uint payroll = _ownerAmount/garden.coOwners.length; transferPaymentToMultipleOwners(payroll,garden); }else{ garden.owner.transfer(_ownerAmount); } } lastRent.balance=0; lastRent.accessCode.hashCode=0; garden.status=GLibrary.Status.Free; } function isRentOver(uint _beginning, uint _duration) private view returns (bool){ if(_beginning + _duration<= block.timestamp){ return true; } return false; } }
Use the function to update location status after location and get payment. The caller must be the garden's owner. _gardenIndex the Id of the garden _proofA the first part of the proof _proofB the second part of the proof _proofC the third part of the proof
function updateLocationStatusAndGetPayment(uint _gardenIndex, uint[2] calldata _proofA, uint[2][2] calldata _proofB, uint[2] calldata _proofC)external OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); GLibrary.Garden storage garden = AllGarden[_gardenIndex]; require(garden.status!= GLibrary.Status.Dispute, "Dispute is running"); require(isRentOver(lastRent.beginning,lastRent.duration),"Location not over"); uint balance = lastRent.balance; lastRent.balance=0; lastRent.accessCode.hashCode= 0; AllGarden[_gardenIndex].status=GLibrary.Status.Free; if(garden.multipleOwners){ uint payroll = balance/garden.coOwners.length; transferPaymentToMultipleOwners(payroll,garden); garden.owner.transfer(balance); } }
12,765,335
./partial_match/1/0x92f8F6c955f730291e66588C0D64Bf0E77DadA4e/sources/Vault.sol
Returns the price of a pool return Value of the share price in wei
function calcSharePrice() external view returns (uint256) { return getNav(); }
4,431,902
./partial_match/1/0xae61DB510cC96D57805Bf3fe4fcCee9365D12fAa/sources/src/Nchart.sol
generate the uniswap pair path of token -> weth make the swap
function _swapTokensForEth(uint256 tokenAmount) internal { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); }
2,691,138
pragma solidity 0.4.25; /*===========================================================================================* *************************************** https://p4d.io *************************************** *============================================================================================* * * ,-.----. ,--, * \ / \ ,--.'| ,---, * | : \ ,--, | : .' .' `\ * | | .\ :,---.'| : ',---.' \ * . : |: |; : | | ;| | .`\ | * | | \ :| | : _' |: : | ' | * | : . /: : |.' || ' ' ; : * ; | |`-' | ' ' ; :' | ; . | * | | ; \ \ .'. || | : | ' * : ' | `---`: | '' : | / ; * : : : ' ; || | '` ,/ * | | : | : ;; : .' * `---'.| ' ,/ | ,.' * `---` '--' '---' * _____ _ _ _ __ __ _ _ _ * |_ _| | | | | | / _|/ _(_) (_) | | * | | | |__ ___ | | | |_ __ ___ | |_| |_ _ ___ _ __ _| | * | | | '_ \ / _ \ | | | | '_ \ / _ \| _| _| |/ __| |/ _` | | * | | | | | | __/ | |_| | | | | (_) | | | | | | (__| | (_| | | * \_/ |_| |_|\___| \___/|_| |_|\___/|_| |_| |_|\___|_|\__,_|_| * * ______ ___________ _____ _ * | ___ \____ | _ \ | ___| (_) * | |_/ / / / | | | | |____ ___ __ __ _ _ __ ___ _ ___ _ __ * | __/ \ \ | | | | __\ \/ / '_ \ / _` | '_ \/ __| |/ _ \| '_ \ * | | .___/ / |/ / | |___> <| |_) | (_| | | | \__ \ | (_) | | | | * \_| \____/|___/ \____/_/\_\ .__/ \__,_|_| |_|___/_|\___/|_| |_| * | | * |_| * _L/L * _LT/l_L_ * _LLl/L_T_lL_ * _T/L _LT|L/_|__L_|_L_ * _Ll/l_L_ _TL|_T/_L_|__T__|_l_ * _TLl/T_l|_L_ _LL|_Tl/_|__l___L__L_|L_ * _LT_L/L_|_L_l_L_ _'|_|_|T/_L_l__T _ l__|__|L_ * _Tl_L|/_|__|_|__T _LlT_|_Ll/_l_ _|__[ ]__|__|_l_L_ * ..__ _LT_l_l/|__|__l_T _T_L|_|_|l/___|__ | _l__|_ |__|_T_L_ __ * _ ___ _ _ ___ * /_\ / __\___ _ __ | |_ _ __ __ _ ___| |_ / __\_ _ * //_\\ / / / _ \| '_ \| __| '__/ _` |/ __| __| /__\// | | | * / _ \ / /__| (_) | | | | |_| | | (_| | (__| |_ / \/ \ |_| | * \_/ \_/ \____/\___/|_| |_|\__|_| \__,_|\___|\__| \_____/\__, | * ╔═╗╔═╗╦ ╔╦╗╔═╗╦ ╦ |___/ * ╚═╗║ ║║ ║║║╣ ╚╗╔╝ * ╚═╝╚═╝╩═╝────═╩╝╚═╝ ╚╝ * 0x736f6c5f646576 * ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ * * -> What? * The original autonomous pyramid, improved (again!): * [x] Developer optimized to include utility functions: * -> approve(): allow others to transfer on your behalf * -> approveAndCall(): callback for contracts that want to use approve() * -> transferFrom(): use your approval allowance to transfer P4D on anothers behalf * -> transferAndCall(): callback for contracts that want to use transfer() * [x] Designed to be a bridge for P3D to make the token functional for use in external contracts * [x] Masternodes are also used in P4D as well as when it buys P3D: * -> If the referrer has more than 10,000 P4D tokens, they will get 1/3 of the 10% divs * -> If the referrer also has more than 100 P3D tokens, they will be used as the ref * on the buy order to P3D and receive 1/3 of the 10% P3D divs upon purchase * [x] As this contract holds P3D, it will receive ETH dividends proportional to it's * holdings, this ETH is then distributed to all P4D token holders proportionally * [x] On top of the ETH divs from P3D, you will also receive P3D divs from buys and sells * in the P4D exchange * [x] There's a 10% div tax for buys, a 5% div tax on sells and a 0% tax on transfers * [x] No auto-transfers for dividends or subdividends, they will all be stored until * either withdraw() or reinvest() are called, this makes it easier for external * contracts to calculate how much they received upon a withdraw/reinvest * [x] Partial withdraws and reinvests for both dividends and subdividends * [x] Global name registry for all external contracts to use: * -> Names cost 0.01 ETH to register * -> Names must be unique and not already owned * -> You can set an active name out of all the ones you own * -> You can change your name at any time but still be referred by an old name * -> All ETH from registrations will be distributed to all P4D holders proportionally * */ // P3D interface interface P3D { function buy(address) external payable returns(uint256); function transfer(address, uint256) external returns(bool); function myTokens() external view returns(uint256); function balanceOf(address) external view returns(uint256); function myDividends(bool) external view returns(uint256); function withdraw() external; function calculateTokensReceived(uint256) external view returns(uint256); function stakingRequirement() external view returns(uint256); } // ERC-677 style token transfer callback interface usingP4D { function tokenCallback(address _from, uint256 _value, bytes _data) external returns (bool); } // ERC-20 style approval callback interface controllingP4D { function approvalCallback(address _from, uint256 _value, bytes _data) external returns (bool); } contract P4D { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (how many tokens it costs to hold a masternode, in case it gets crazy high later) // -> allow a contract to accept P4D tokens // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator() { require(administrators[msg.sender] || msg.sender == _dev); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier purchaseFilter(address _sender, uint256 _amountETH) { require(!isContract(_sender) || canAcceptTokens_[_sender]); if (now >= ACTIVATION_TIME) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if (onlyAmbassadors && ((totalAmbassadorQuotaSpent_ + _amountETH) <= ambassadorQuota_)) { require( // is the customer in the ambassador list? ambassadors_[_sender] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_sender] + _amountETH) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_sender] = SafeMath.add(ambassadorAccumulatedQuota_[_sender], _amountETH); totalAmbassadorQuotaSpent_ = SafeMath.add(totalAmbassadorQuotaSpent_, _amountETH); // execute _; } else { require(!onlyAmbassadors); _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed _customerAddress, uint256 _incomingP3D, uint256 _tokensMinted, address indexed _referredBy ); event onTokenSell( address indexed _customerAddress, uint256 _tokensBurned, uint256 _P3D_received ); event onReinvestment( address indexed _customerAddress, uint256 _P3D_reinvested, uint256 _tokensMinted ); event onSubdivsReinvestment( address indexed _customerAddress, uint256 _ETH_reinvested, uint256 _tokensMinted ); event onWithdraw( address indexed _customerAddress, uint256 _P3D_withdrawn ); event onSubdivsWithdraw( address indexed _customerAddress, uint256 _ETH_withdrawn ); event onNameRegistration( address indexed _customerAddress, string _registeredName ); // ERC-20 event Transfer( address indexed _from, address indexed _to, uint256 _tokens ); event Approval( address indexed _tokenOwner, address indexed _spender, uint256 _tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "PoWH4D"; string public symbol = "P4D"; uint256 constant public decimals = 18; uint256 constant internal buyDividendFee_ = 10; // 10% dividend tax on each buy uint256 constant internal sellDividendFee_ = 5; // 5% dividend tax on each sell uint256 internal tokenPriceInitial_; // set in the constructor uint256 constant internal tokenPriceIncremental_ = 1e9; // 1/10th the incremental of P3D uint256 constant internal magnitude = 2**64; uint256 public stakingRequirement = 1e22; // 10,000 P4D uint256 constant internal initialBuyLimitPerTx_ = 1 ether; uint256 constant internal initialBuyLimitCap_ = 100 ether; uint256 internal totalInputETH_ = 0; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 12 ether; uint256 internal totalAmbassadorQuotaSpent_ = 0; address internal _dev; uint256 public ACTIVATION_TIME; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal dividendsStored_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // contracts can interact with the exchange but only approved ones mapping(address => bool) public canAcceptTokens_; // ERC-20 standard mapping(address => mapping (address => uint256)) public allowed; // P3D contract reference P3D internal _P3D; // structure to handle the distribution of ETH divs paid out by the P3D contract struct P3D_dividends { uint256 balance; uint256 lastDividendPoints; } mapping(address => P3D_dividends) internal divsMap_; uint256 internal totalDividendPoints_; uint256 internal lastContractBalance_; // structure to handle the global unique name/vanity registration struct NameRegistry { uint256 activeIndex; bytes32[] registeredNames; } mapping(address => NameRegistry) internal customerNameMap_; mapping(bytes32 => address) internal globalNameMap_; uint256 constant internal nameRegistrationFee = 0.01 ether; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor(uint256 _activationTime, address _P3D_address) public { _dev = msg.sender; ACTIVATION_TIME = _activationTime; totalDividendPoints_ = 1; // non-zero value _P3D = P3D(_P3D_address); // virtualized purchase of the entire ambassador quota // calculateTokensReceived() for this contract will return how many tokens can be bought starting at 1e9 P3D per P4D // as the price increases by the incremental each time we can just multiply it out and scale it back to e18 // // this is used as the initial P3D-P4D price as it makes it fairer on other investors that aren't ambassadors uint256 _P4D_received; (, _P4D_received) = calculateTokensReceived(ambassadorQuota_); tokenPriceInitial_ = tokenPriceIncremental_ * _P4D_received / 1e18; // admins administrators[_dev] = true; // ambassadors ambassadors_[_dev] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral address */ function buy(address _referredBy) payable public returns(uint256) { return purchaseInternal(msg.sender, msg.value, _referredBy); } /** * Buy with a registered name as the referrer. * If the name is unregistered, address(0x0) will be the ref */ function buyWithNameRef(string memory _nameOfReferrer) payable public returns(uint256) { return purchaseInternal(msg.sender, msg.value, ownerOfName(_nameOfReferrer)); } /** * Fallback function to handle ethereum that was sent straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { if (msg.sender != address(_P3D)) { purchaseInternal(msg.sender, msg.value, address(0x0)); } // all other ETH is from the withdrawn dividends from // the P3D contract, this is distributed out via the // updateSubdivsFor() method // no more computation can be done inside this function // as when you call address.transfer(uint256), only // 2,300 gas is forwarded to this function so no variables // can be mutated with that limit // address(this).balance will represent the total amount // of ETH dividends from the P3D contract (minus the amount // that's already been withdrawn) } /** * Distribute any ETH sent to this method out to all token holders */ function donate() payable public { // nothing happens here in order to save gas // all of the ETH sent to this function will be distributed out // via the updateSubdivsFor() method // // this method is designed for external contracts that have // extra ETH that they want to evenly distribute to all // P4D token holders } /** * Allows a customer to pay for a global name on the P4D network * There's a 0.01 ETH registration fee per name * All ETH is distributed to P4D token holders via updateSubdivsFor() */ function registerName(string memory _name) payable public { address _customerAddress = msg.sender; require(!onlyAmbassadors || ambassadors_[_customerAddress]); require(bytes(_name).length > 0); require(msg.value >= nameRegistrationFee); uint256 excess = SafeMath.sub(msg.value, nameRegistrationFee); bytes32 bytesName = stringToBytes32(_name); require(globalNameMap_[bytesName] == address(0x0)); NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; customerNamesInfo.registeredNames.push(bytesName); customerNamesInfo.activeIndex = customerNamesInfo.registeredNames.length - 1; globalNameMap_[bytesName] = _customerAddress; if (excess > 0) { _customerAddress.transfer(excess); } // fire event emit onNameRegistration(_customerAddress, _name); // similar to the fallback and donate functions, the ETH cost of // the name registration fee (0.01 ETH) will be distributed out // to all P4D tokens holders via the updateSubdivsFor() method } /** * Change your active name to a name that you've already purchased */ function changeActiveNameTo(string memory _name) public { address _customerAddress = msg.sender; require(_customerAddress == ownerOfName(_name)); bytes32 bytesName = stringToBytes32(_name); NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; uint256 newActiveIndex = 0; for (uint256 i = 0; i < customerNamesInfo.registeredNames.length; i++) { if (bytesName == customerNamesInfo.registeredNames[i]) { newActiveIndex = i; break; } } customerNamesInfo.activeIndex = newActiveIndex; } /** * Similar to changeActiveNameTo() without the need to iterate through your name list */ function changeActiveNameIndexTo(uint256 _newActiveIndex) public { address _customerAddress = msg.sender; NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; require(_newActiveIndex < customerNamesInfo.registeredNames.length); customerNamesInfo.activeIndex = _newActiveIndex; } /** * Converts all of caller's dividends to tokens. * The argument is not used but it allows MetaMask to render * 'Reinvest' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function reinvest(bool) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); uint256 reinvestableDividends = dividendsStored_[_customerAddress]; reinvestAmount(reinvestableDividends); } /** * Converts a portion of caller's dividends to tokens. */ function reinvestAmount(uint256 _amountOfP3D) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); if (_amountOfP3D > 0 && _amountOfP3D <= dividendsStored_[_customerAddress]) { dividendsStored_[_customerAddress] = SafeMath.sub(dividendsStored_[_customerAddress], _amountOfP3D); // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_customerAddress, _amountOfP3D, address(0x0)); // fire event emit onReinvestment(_customerAddress, _amountOfP3D, _tokens); } } /** * Converts all of caller's subdividends to tokens. * The argument is not used but it allows MetaMask to render * 'Reinvest Subdivs' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function reinvestSubdivs(bool) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); uint256 reinvestableSubdividends = divsMap_[_customerAddress].balance; reinvestSubdivsAmount(reinvestableSubdividends); } /** * Converts a portion of caller's subdividends to tokens. */ function reinvestSubdivsAmount(uint256 _amountOfETH) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); if (_amountOfETH > 0 && _amountOfETH <= divsMap_[_customerAddress].balance) { divsMap_[_customerAddress].balance = SafeMath.sub(divsMap_[_customerAddress].balance, _amountOfETH); lastContractBalance_ = SafeMath.sub(lastContractBalance_, _amountOfETH); // purchase tokens with the ETH subdividends uint256 _tokens = purchaseInternal(_customerAddress, _amountOfETH, address(0x0)); // fire event emit onSubdivsReinvestment(_customerAddress, _amountOfETH, _tokens); } } /** * Alias of sell(), withdraw() and withdrawSubdivs(). * The argument is not used but it allows MetaMask to render * 'Exit' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function exit(bool) public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(true); withdrawSubdivs(true); } /** * Withdraws all of the callers dividend earnings. * The argument is not used but it allows MetaMask to render * 'Withdraw' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function withdraw(bool) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); uint256 withdrawableDividends = dividendsStored_[_customerAddress]; withdrawAmount(withdrawableDividends); } /** * Withdraws a portion of the callers dividend earnings. */ function withdrawAmount(uint256 _amountOfP3D) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); if (_amountOfP3D > 0 && _amountOfP3D <= dividendsStored_[_customerAddress]) { dividendsStored_[_customerAddress] = SafeMath.sub(dividendsStored_[_customerAddress], _amountOfP3D); // lambo delivery service require(_P3D.transfer(_customerAddress, _amountOfP3D)); // NOTE! // P3D has a 10% transfer tax so even though this is sending your entire // dividend count to you, you will only actually receive 90%. // fire event emit onWithdraw(_customerAddress, _amountOfP3D); } } /** * Withdraws all of the callers subdividend earnings. * The argument is not used but it allows MetaMask to render * 'Withdraw Subdivs' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function withdrawSubdivs(bool) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); uint256 withdrawableSubdividends = divsMap_[_customerAddress].balance; withdrawSubdivsAmount(withdrawableSubdividends); } /** * Withdraws a portion of the callers subdividend earnings. */ function withdrawSubdivsAmount(uint256 _amountOfETH) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); if (_amountOfETH > 0 && _amountOfETH <= divsMap_[_customerAddress].balance) { divsMap_[_customerAddress].balance = SafeMath.sub(divsMap_[_customerAddress].balance, _amountOfETH); lastContractBalance_ = SafeMath.sub(lastContractBalance_, _amountOfETH); // transfer all withdrawable subdividends _customerAddress.transfer(_amountOfETH); // fire event emit onSubdivsWithdraw(_customerAddress, _amountOfETH); } } /** * Liquifies tokens to P3D. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _P3D_amount = tokensToP3D_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_amount, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_amount, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256)(profitPerShare_ * _tokens + (_taxedP3D * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire events emit onTokenSell(_customerAddress, _tokens, _taxedP3D); emit Transfer(_customerAddress, address(0x0), _tokens); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { address _customerAddress = msg.sender; return transferInternal(_customerAddress, _toAddress, _amountOfTokens); } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns(bool) { require(canAcceptTokens_[_to]); // approved contracts only require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { usingP4D receiver = usingP4D(_to); require(receiver.tokenCallback(msg.sender, _value, _data)); } return true; } /** * ERC-20 token standard for transferring tokens on anothers behalf */ function transferFrom(address _from, address _to, uint256 _amountOfTokens) public returns(bool) { require(allowed[_from][msg.sender] >= _amountOfTokens); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens); return transferInternal(_from, _to, _amountOfTokens); } /** * ERC-20 token standard for allowing another address to transfer your tokens * on your behalf up to a certain limit */ function approve(address _spender, uint256 _tokens) public returns(bool) { allowed[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } /** * ERC-20 token standard for approving and calling an external * contract with data */ function approveAndCall(address _to, uint256 _value, bytes _data) external returns(bool) { require(approve(_to, _value)); // do a normal approval if (isContract(_to)) { controllingP4D receiver = controllingP4D(_to); require(receiver.approvalCallback(msg.sender, _value, _data)); } return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Add a new ambassador to the exchange */ function setAmbassador(address _identifier, bool _status) onlyAdministrator() public { ambassadors_[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Add a sub-contract, which can accept P4D tokens */ function setCanAcceptTokens(address _address) onlyAdministrator() public { require(isContract(_address)); canAcceptTokens_[_address] = true; // one way switch } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current P3D tokens stored in the contract */ function totalBalance() public view returns(uint256) { return _P3D.myTokens(); } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is set to true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return (_includeReferralBonus ? dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress) : dividendsOf(_customerAddress)); } /** * Retrieve the subdividend owned by the caller. */ function myStoredDividends() public view returns(uint256) { address _customerAddress = msg.sender; return storedDividendsOf(_customerAddress); } /** * Retrieve the subdividend owned by the caller. */ function mySubdividends() public view returns(uint256) { address _customerAddress = msg.sender; return subdividendsOf(_customerAddress); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) public view returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) public view returns(uint256) { return (uint256)((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Retrieve the referred dividend balance of any single address. */ function referralDividendsOf(address _customerAddress) public view returns(uint256) { return referralBalance_[_customerAddress]; } /** * Retrieve the stored dividend balance of any single address. */ function storedDividendsOf(address _customerAddress) public view returns(uint256) { return dividendsStored_[_customerAddress] + dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress); } /** * Retrieve the subdividend balance owing of any single address. */ function subdividendsOwing(address _customerAddress) public view returns(uint256) { return (divsMap_[_customerAddress].lastDividendPoints == 0 ? 0 : (balanceOf(_customerAddress) * (totalDividendPoints_ - divsMap_[_customerAddress].lastDividendPoints)) / magnitude); } /** * Retrieve the subdividend balance of any single address. */ function subdividendsOf(address _customerAddress) public view returns(uint256) { return SafeMath.add(divsMap_[_customerAddress].balance, subdividendsOwing(_customerAddress)); } /** * Retrieve the allowance of an owner and spender. */ function allowance(address _tokenOwner, address _spender) public view returns(uint256) { return allowed[_tokenOwner][_spender]; } /** * Retrieve all name information about a customer */ function namesOf(address _customerAddress) public view returns(uint256 activeIndex, string activeName, bytes32[] customerNames) { NameRegistry memory customerNamesInfo = customerNameMap_[_customerAddress]; uint256 length = customerNamesInfo.registeredNames.length; customerNames = new bytes32[](length); for (uint256 i = 0; i < length; i++) { customerNames[i] = customerNamesInfo.registeredNames[i]; } activeIndex = customerNamesInfo.activeIndex; activeName = activeNameOf(_customerAddress); } /** * Retrieves the address of the owner from the name */ function ownerOfName(string memory _name) public view returns(address) { if (bytes(_name).length > 0) { bytes32 bytesName = stringToBytes32(_name); return globalNameMap_[bytesName]; } else { return address(0x0); } } /** * Retrieves the active name of a customer */ function activeNameOf(address _customerAddress) public view returns(string) { NameRegistry memory customerNamesInfo = customerNameMap_[_customerAddress]; if (customerNamesInfo.registeredNames.length > 0) { bytes32 activeBytesName = customerNamesInfo.registeredNames[customerNamesInfo.activeIndex]; return bytes32ToString(activeBytesName); } else { return ""; } } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _P3D_received = tokensToP3D_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_received, _dividends); return _taxedP3D; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _P3D_received = tokensToP3D_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, buyDividendFee_), 100); uint256 _taxedP3D = SafeMath.add(_P3D_received, _dividends); return _taxedP3D; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _amountOfETH) public view returns(uint256 _P3D_received, uint256 _P4D_received) { uint256 P3D_received = _P3D.calculateTokensReceived(_amountOfETH); uint256 _dividends = SafeMath.div(SafeMath.mul(P3D_received, buyDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(P3D_received, _dividends); uint256 _amountOfTokens = P3DtoTokens_(_taxedP3D); return (P3D_received, _amountOfTokens); } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateAmountReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _P3D_received = tokensToP3D_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_received, _dividends); return _taxedP3D; } /** * Utility method to expose the P3D address for any child contracts to use */ function P3D_address() public view returns(address) { return address(_P3D); } /** * Utility method to return all of the data needed for the front end in 1 call */ function fetchAllDataForCustomer(address _customerAddress) public view returns(uint256 _totalSupply, uint256 _totalBalance, uint256 _buyPrice, uint256 _sellPrice, uint256 _activationTime, uint256 _customerTokens, uint256 _customerUnclaimedDividends, uint256 _customerStoredDividends, uint256 _customerSubdividends) { _totalSupply = totalSupply(); _totalBalance = totalBalance(); _buyPrice = buyPrice(); _sellPrice = sellPrice(); _activationTime = ACTIVATION_TIME; _customerTokens = balanceOf(_customerAddress); _customerUnclaimedDividends = dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress); _customerStoredDividends = storedDividendsOf(_customerAddress); _customerSubdividends = subdividendsOf(_customerAddress); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ // This function should always be called before a customers P4D balance changes. // It's responsible for withdrawing any outstanding ETH dividends from the P3D exchange // as well as distrubuting all of the additional ETH balance since the last update to // all of the P4D token holders proportionally. // After this it will move any owed subdividends into the customers withdrawable subdividend balance. function updateSubdivsFor(address _customerAddress) internal { // withdraw the P3D dividends first if (_P3D.myDividends(true) > 0) { _P3D.withdraw(); } // check if we have additional ETH in the contract since the last update uint256 contractBalance = address(this).balance; if (contractBalance > lastContractBalance_ && totalSupply() != 0) { uint256 additionalDivsFromP3D = SafeMath.sub(contractBalance, lastContractBalance_); totalDividendPoints_ = SafeMath.add(totalDividendPoints_, SafeMath.div(SafeMath.mul(additionalDivsFromP3D, magnitude), totalSupply())); lastContractBalance_ = contractBalance; } // if this is the very first time this is called for a customer, set their starting point if (divsMap_[_customerAddress].lastDividendPoints == 0) { divsMap_[_customerAddress].lastDividendPoints = totalDividendPoints_; } // move any owing subdividends into the customers subdividend balance uint256 owing = subdividendsOwing(_customerAddress); if (owing > 0) { divsMap_[_customerAddress].balance = SafeMath.add(divsMap_[_customerAddress].balance, owing); divsMap_[_customerAddress].lastDividendPoints = totalDividendPoints_; } } function withdrawInternal(address _customerAddress) internal { // setup data // dividendsOf() will return only divs, not the ref. bonus uint256 _dividends = dividendsOf(_customerAddress); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // store the divs dividendsStored_[_customerAddress] = SafeMath.add(dividendsStored_[_customerAddress], _dividends); } function transferInternal(address _customerAddress, address _toAddress, uint256 _amountOfTokens) internal returns(bool) { // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); updateSubdivsFor(_customerAddress); updateSubdivsFor(_toAddress); // withdraw and store all outstanding dividends first (if there is any) if ((dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress)) > 0) withdrawInternal(_customerAddress); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256)(profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256)(profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } function purchaseInternal(address _sender, uint256 _incomingEthereum, address _referredBy) purchaseFilter(_sender, _incomingEthereum) internal returns(uint256) { uint256 purchaseAmount = _incomingEthereum; uint256 excess = 0; if (totalInputETH_ <= initialBuyLimitCap_) { // check if the total input ETH is less than the cap if (purchaseAmount > initialBuyLimitPerTx_) { // if so check if the transaction is over the initial buy limit per transaction purchaseAmount = initialBuyLimitPerTx_; excess = SafeMath.sub(_incomingEthereum, purchaseAmount); } totalInputETH_ = SafeMath.add(totalInputETH_, purchaseAmount); } // return the excess if there is any if (excess > 0) { _sender.transfer(excess); } // buy P3D tokens with the entire purchase amount // even though _P3D.buy() returns uint256, it was never implemented properly inside the P3D contract // so in order to find out how much P3D was purchased, you need to check the balance first then compare // the balance after the purchase and the difference will be the amount purchased uint256 tmpBalanceBefore = _P3D.myTokens(); _P3D.buy.value(purchaseAmount)(_referredBy); uint256 purchasedP3D = SafeMath.sub(_P3D.myTokens(), tmpBalanceBefore); return purchaseTokens(_sender, purchasedP3D, _referredBy); } function purchaseTokens(address _sender, uint256 _incomingP3D, address _referredBy) internal returns(uint256) { updateSubdivsFor(_sender); // data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingP3D, buyDividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedP3D = SafeMath.sub(_incomingP3D, _undividedDividends); uint256 _amountOfTokens = P3DtoTokens_(_taxedP3D); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != address(0x0) && // no cheating! _referredBy != _sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite P3D if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over their purchase _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_sender] = SafeMath.add(tokenBalanceLedger_[_sender], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; // really I know you think you do but you don't payoutsTo_[_sender] += (int256)((profitPerShare_ * _amountOfTokens) - _fee); // fire events emit onTokenPurchase(_sender, _incomingP3D, _amountOfTokens, _referredBy); emit Transfer(address(0x0), _sender, _amountOfTokens); return _amountOfTokens; } /** * Calculate token price based on an amount of incoming P3D * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function P3DtoTokens_(uint256 _P3D_received) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2 * (tokenPriceIncremental_ * 1e18)*(_P3D_received * 1e18)) + (((tokenPriceIncremental_)**2) * (tokenSupply_**2)) + (2 * (tokenPriceIncremental_) * _tokenPriceInitial * tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToP3D_(uint256 _P4D_tokens) internal view returns(uint256) { uint256 tokens_ = (_P4D_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _P3D_received = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_**2 - tokens_) / 1e18)) / 2 ) / 1e18); return _P3D_received; } // This is where all your gas goes, sorry // Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } /** * Additional check that the address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) internal constant returns(bool) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /** * Utility method to help store the registered names */ function stringToBytes32(string memory _s) internal pure returns(bytes32 result) { bytes memory tmpEmptyStringTest = bytes(_s); if (tmpEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_s, 32)) } } /** * Utility method to help read the registered names */ function bytes32ToString(bytes32 _b) internal pure returns(string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 i = 0; i < 32; i++) { byte char = byte(bytes32(uint(_b) * 2 ** (8 * i))); if (char != 0) { bytesString[charCount++] = char; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (i = 0; i < charCount; i++) { bytesStringTrimmed[i] = bytesString[i]; } return string(bytesStringTrimmed); } } /** * @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) { if (a == 0) { return 0; } uint256 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 c; } /** * @dev Substracts 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) { uint256 c = a + b; assert(c >= a); return c; } } // // pragma solidity ^0.4.25; // // interface P4D { // function buy(address) external payable returns(uint256); // function sell(uint256) external; // function transfer(address, uint256) external returns(bool); // function myTokens() external view returns(uint256); // function myStoredDividends() external view returns(uint256); // function mySubdividends() external view returns(uint256); // function reinvest(bool) external; // function reinvestSubdivs(bool) external; // function withdraw(bool) external; // function withdrawSubdivs(bool) external; // function exit(bool) external; // sell + withdraw + withdrawSubdivs // function P3D_address() external view returns(address); // } // // contract usingP4D { // // P4D public tokenContract; // // constructor(address _P4D_address) public { // tokenContract = P4D(_P4D_address); // } // // modifier onlyTokenContract { // require(msg.sender == address(tokenContract)); // _; // } // // function tokenCallback(address _from, uint256 _value, bytes _data) external returns (bool); // } // // contract YourDapp is usingP4D { // // constructor(address _P4D_address) // public // usingP4D(_P4D_address) // { // //... // } // // function tokenCallback(address _from, uint256 _value, bytes _data) // external // onlyTokenContract // returns (bool) // { // //... // return true; // } // // function() // payable // public // { // if (msg.sender != address(tokenContract)) { // //... // } // } // } // /*===========================================================================================* *************************************** https://p4d.io *************************************** *===========================================================================================*/
Retrieve the dividends owned by the caller. If `_includeReferralBonus` is set to true, the referral bonus will be included in the calculations. The reason for this, is that in the frontend, we will want to get the total divs (global + ref) But in the internal calculations, we want them separate./
function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return (_includeReferralBonus ? dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress) : dividendsOf(_customerAddress)); }
7,264,061
./full_match/3/0x824Ba42295Eb43fAF560417A85fA28Fbe435275F/sources/browser/Contract_Code_Min.sol
get Resonance Ratio for the Resonance ID value Resonance ID return Resonance Ratio/
function getResonanceRatio(uint value) internal view returns (uint) { if (value == 1) { return USDT_ETTWei_Ratio * 50; } if (value == 2) { return USDT_ETTWei_Ratio * 45; } if (value == 3) { return USDT_ETTWei_Ratio * 40; } if (value == 4) { return USDT_ETTWei_Ratio * 35; } if (value == 5) { return USDT_ETTWei_Ratio * 30; } if (value == 6) { return USDT_ETTWei_Ratio * 25; } return USDT_ETTWei_Ratio * 20; }
8,108,478
./full_match/1/0x3b985118468164b310C5254b0710888dd57c7599/sources/contracts/pool/PoolConfiguration.sol
Function is used to update pool's warning grace period (only called by governor) warningGracePeriod_ New warning grace period of the pool
function setWarningGracePeriod(uint256 warningGracePeriod_) external onlyGovernor { _accrueInterest(); warningGracePeriod = warningGracePeriod_; _checkUtilization(); }
3,086,636
/** *Submitted for verification at Etherscan.io on 2022-04-14 */ // File: contracts/interfaces/ILayerZeroUserApplicationConfig.sol pragma solidity >=0.5.0; interface ILayerZeroUserApplicationConfig { // @notice set the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _configType - type of configuration. every messaging library has its own convention. // @param _config - configuration in the bytes. can encode arbitrary content. function setConfig( uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config ) external; // @notice set the send() LayerZero messaging library version to _version // @param _version - new messaging library version function setSendVersion(uint16 _version) external; // @notice set the lzReceive() LayerZero messaging library version to _version // @param _version - new messaging library version function setReceiveVersion(uint16 _version) external; // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload // @param _srcChainId - the chainId of the source chain // @param _srcAddress - the contract address of the source contract at the source chain function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external; } // File: contracts/interfaces/ILayerZeroEndpoint.sol pragma solidity >=0.5.0; interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig { // @notice send a LayerZero message to the specified address at a LayerZero endpoint. // @param _dstChainId - the destination chain identifier // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains // @param _payload - a custom bytes payload to send to the destination contract // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination function send( uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams ) external payable; // @notice used by the messaging library to publish verified payload // @param _srcChainId - the source chain identifier // @param _srcAddress - the source contract (as bytes) at the source chain // @param _dstAddress - the address on destination chain // @param _nonce - the unbound message ordering nonce // @param _gasLimit - the gas limit for external contract execution // @param _payload - verified payload to send to the destination contract function receivePayload( uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint256 _gasLimit, bytes calldata _payload ) external; // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64); // @notice get the outboundNonce from this source chain which, consequently, is always an EVM // @param _srcAddress - the source chain contract address function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64); // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery // @param _dstChainId - the destination chain identifier // @param _userApplication - the user app address on this EVM chain // @param _payload - the custom message to send over LayerZero // @param _payInZRO - if false, user app pays the protocol fee in native token // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain function estimateFees( uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam ) external view returns (uint256 nativeFee, uint256 zroFee); // @notice get this Endpoint's immutable source identifier function getChainId() external view returns (uint16); // @notice the interface to retry failed message on this Endpoint destination // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address // @param _payload - the payload to be retried function retryPayload( uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload ) external; // @notice query if any STORED payload (message blocking) at the endpoint. // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool); // @notice query if the _libraryAddress is valid for sending msgs. // @param _userApplication - the user app address on this EVM chain function getSendLibraryAddress(address _userApplication) external view returns (address); // @notice query if the _libraryAddress is valid for receiving msgs. // @param _userApplication - the user app address on this EVM chain function getReceiveLibraryAddress(address _userApplication) external view returns (address); // @notice query if the non-reentrancy guard for send() is on // @return true if the guard is on. false otherwise function isSendingPayload() external view returns (bool); // @notice query if the non-reentrancy guard for receive() is on // @return true if the guard is on. false otherwise function isReceivingPayload() external view returns (bool); // @notice get the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _userApplication - the contract address of the user application // @param _configType - type of configuration. every messaging library has its own convention. function getConfig( uint16 _version, uint16 _chainId, address _userApplication, uint256 _configType ) external view returns (bytes memory); // @notice get the send() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getSendVersion(address _userApplication) external view returns (uint16); // @notice get the lzReceive() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getReceiveVersion(address _userApplication) external view returns (uint16); } // File: contracts/interfaces/ILayerZeroReceiver.sol pragma solidity >=0.5.0; interface ILayerZeroReceiver { // @notice LayerZero endpoint will invoke this function to deliver the message on the destination // @param _srcChainId - the source endpoint identifier // @param _srcAddress - the source sending contract address from the source chain // @param _nonce - the ordered message nonce // @param _payload - the signed payload is the UA bytes has encoded to be sent function lzReceive( uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload ) external; } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be 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 {} } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/NonblockingReceiver.sol pragma solidity ^0.8.6; abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver { ILayerZeroEndpoint internal endpoint; struct FailedMessages { uint256 payloadLength; bytes32 payloadHash; } mapping(uint16 => mapping(bytes => mapping(uint256 => FailedMessages))) public failedMessages; mapping(uint16 => bytes) public trustedRemoteLookup; event MessageFailed( uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload ); function lzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) external override { require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security require( _srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]), "NonblockingReceiver: invalid source sending contract" ); // try-catch all errors/exceptions // having failed messages does not block messages passing try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) { // do nothing } catch { // error / exception failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages( _payload.length, keccak256(_payload) ); emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload); } } function onLzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) public { // only internal transaction require( msg.sender == address(this), "NonblockingReceiver: caller must be Bridge." ); // handle incoming message _LzReceive(_srcChainId, _srcAddress, _nonce, _payload); } // abstract function function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal virtual; function _lzSend( uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam ) internal { endpoint.send{value: msg.value}( _dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam ); } function retryMessage( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload ) external payable { // assert there is message to retry FailedMessages storage failedMsg = failedMessages[_srcChainId][ _srcAddress ][_nonce]; require( failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message" ); require( _payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload" ); // clear the stored message failedMsg.payloadLength = 0; failedMsg.payloadHash = bytes32(0); // execute the message. revert if it fails again this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload); } function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner { trustedRemoteLookup[_chainId] = _trustedRemote; } } // File: contracts/OmniSneaker_ETH.sol pragma solidity ^0.8.7; // ____ __ ____ ___________ _ ___________ __ __ __________ _____ // / __ \/ |/ / | / / _/ ___// | / / ____/ | / //_// ____/ __ \/ ___/ // / / / / /|_/ / |/ // / \__ \/ |/ / __/ / /| | / ,< / __/ / /_/ /\__ \ /// /_/ / / / / /| // / ___/ / /| / /___/ ___ |/ /| |/ /___/ _, _/___/ / //\____/_/ /_/_/ |_/___//____/_/ |_/_____/_/ |_/_/ |_/_____/_/ |_|/____/ // contract OmniSneaker is Ownable, ERC721, NonblockingReceiver { address public _owner; string private baseURI; uint256 nextTokenId = 0; uint256 MAX_MINT = 430; uint256 gasForDestinationLzReceive = 350000; constructor(string memory baseURI_, address _layerZeroEndpoint) ERC721("OmniSneaker", "OS") { _owner = msg.sender; endpoint = ILayerZeroEndpoint(_layerZeroEndpoint); baseURI = baseURI_; } /** * pre-mint for community giveaways */ function devMint(uint8 numTokens) public onlyOwner { require(nextTokenId + numTokens <= MAX_MINT, "Mint exceeds supply"); for (uint256 i = 0; i < numTokens; i++) { _safeMint(msg.sender, ++nextTokenId); } } // mint function // you can choose to mint 1 or 2 // mint is free, but payments are accepted function mint(uint8 numTokens) external payable { require(numTokens < 3, "GG: Max 2 NFTs per transaction"); require( nextTokenId + numTokens <= MAX_MINT, "GG: Mint exceeds supply" ); _safeMint(msg.sender, ++nextTokenId); if (numTokens == 2) { _safeMint(msg.sender, ++nextTokenId); } } // This function transfers the nft from your address on the // source chain to the same address on the destination chain function traverseChains(uint16 _chainId, uint256 tokenId) public payable { require( msg.sender == ownerOf(tokenId), "You must own the token to traverse" ); require( trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel" ); // burn NFT, eliminating it from circulation on src chain _burn(tokenId); // abi.encode() the payload with the values to send bytes memory payload = abi.encode(msg.sender, tokenId); // encode adapterParams to specify more gas for the destination uint16 version = 1; bytes memory adapterParams = abi.encodePacked( version, gasForDestinationLzReceive ); // get the fees we need to pay to LayerZero + Relayer to cover message delivery // you will be refunded for extra gas paid (uint256 messageFee, ) = endpoint.estimateFees( _chainId, address(this), payload, false, adapterParams ); require( msg.value >= messageFee, "GG: msg.value not enough to cover messageFee. Send gas for message fees" ); endpoint.send{value: msg.value}( _chainId, // destination chainId trustedRemoteLookup[_chainId], // destination address of nft contract payload, // abi.encoded()'ed bytes payable(msg.sender), // refund address address(0x0), // 'zroPaymentAddress' unused for this adapterParams // txParameters ); } function setBaseURI(string memory URI) external onlyOwner { baseURI = URI; } function donate() external payable { // thank you } // This allows the devs to receive kind donations function withdraw(uint256 amt) external onlyOwner { (bool sent, ) = payable(_owner).call{value: amt}(""); require(sent, "GG: Failed to withdraw Ether"); } // just in case this fixed variable limits us from future integrations function setGasForDestinationLzReceive(uint256 newVal) external onlyOwner { gasForDestinationLzReceive = newVal; } // ------------------ // Internal Functions // ------------------ function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal override { // decode (address toAddr, uint256 tokenId) = abi.decode( _payload, (address, uint256) ); // mint the tokens back into existence on destination chain _safeMint(toAddr, tokenId); } function _baseURI() internal view override returns (string memory) { return baseURI; } }
decode mint the tokens back into existence on destination chain
function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal override { (address toAddr, uint256 tokenId) = abi.decode( _payload, (address, uint256) ); _safeMint(toAddr, tokenId); }
7,857,261
// File: contracts\lib\TransferHelper.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts\interface\INestMining.sol /// @dev This interface defines the mining methods for nest interface INestMining { /// @dev Post event /// @param tokenAddress The address of TOKEN contract /// @param miner Address of miner /// @param index Index of the price sheet /// @param ethNum The numbers of ethers to post sheets event Post(address tokenAddress, address miner, uint index, uint ethNum, uint price); /* ========== Structures ========== */ /// @dev Nest mining configuration structure struct Config { // Eth number of each post. 30 // We can stop post and taking orders by set postEthUnit to 0 (closing and withdraw are not affected) uint32 postEthUnit; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // Proportion of miners digging(10000 based). 8000 uint16 minerNestReward; // The proportion of token dug by miners is only valid for the token created in version 3.0 // (10000 based). 9500 uint16 minerNTokenReward; // When the circulation of ntoken exceeds this threshold, post() is prohibited(Unit: 10000 ether). 500 uint32 doublePostThreshold; // The limit of ntoken mined blocks. 100 uint16 ntokenMinedBlockLimit; // -- Public configuration // The number of times the sheet assets have doubled. 4 uint8 maxBiteNestedLevel; // Price effective block interval. 20 uint16 priceEffectSpan; // The amount of nest to pledge for each post(Unit: 1000). 100 uint16 pledgeNest; } /// @dev PriceSheetView structure struct PriceSheetView { // Index of the price sheeet uint32 index; // Address of miner address miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // The token price. (1eth equivalent to (price) token) uint152 price; } /* ========== Configuration ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @param ntokenAddress The ntoken address function setNTokenAddress(address tokenAddress, address ntokenAddress) external; /// @dev Get the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @return The ntoken address function getNTokenAddress(address tokenAddress) external view returns (address); /* ========== Mining ========== */ /// @notice Post a price sheet for TOKEN /// @dev It is for TOKEN (except USDT and NTOKENs) whose NTOKEN has a total supply below a threshold (e.g. 5,000,000 * 1e18) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN function post(address tokenAddress, uint ethNum, uint tokenAmountPerEth) external payable; /// @notice Post two price sheets for a token and its ntoken simultaneously /// @dev Support dual-posts for TOKEN/NTOKEN, (ETH, TOKEN) + (ETH, NTOKEN) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN /// @param ntokenAmountPerEth The price of NTOKEN function post2(address tokenAddress, uint ethNum, uint tokenAmountPerEth, uint ntokenAmountPerEth) external payable; /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeToken(address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth) external payable; /// @notice Call the function to buy ETH from a posted price sheet /// @dev bite ETH by TOKEN(NTOKEN), (-ethNumBal, +tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeEth(address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth) external payable; /// @notice Close a price sheet of (ETH, USDx) | (ETH, NEST) | (ETH, TOKEN) | (ETH, NTOKEN) /// @dev Here we allow an empty price sheet (still in VERIFICATION-PERIOD) to be closed /// @param tokenAddress The address of TOKEN contract /// @param index The index of the price sheet w.r.t. `token` function close(address tokenAddress, uint index) external; /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN contract /// @param indices A list of indices of sheets w.r.t. `token` function closeList(address tokenAddress, uint[] memory indices) external; /// @notice Close two batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN1 contract /// @param tokenIndices A list of indices of sheets w.r.t. `token` /// @param ntokenIndices A list of indices of sheets w.r.t. `ntoken` function closeList2(address tokenAddress, uint[] memory tokenIndices, uint[] memory ntokenIndices) external; /// @dev The function updates the statistics of price sheets /// It calculates from priceInfo to the newest that is effective. function stat(address tokenAddress) external; /// @dev Settlement Commission /// @param tokenAddress The token address function settle(address tokenAddress) external; /// @dev List sheets by page /// @param tokenAddress Destination token address /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list(address tokenAddress, uint offset, uint count, uint order) external view returns (PriceSheetView[] memory); /// @dev Estimated mining amount /// @param tokenAddress Destination token address /// @return Estimated mining amount function estimate(address tokenAddress) external view returns (uint); /// @dev Query the quantity of the target quotation /// @param tokenAddress Token address. The token can't mine. Please make sure you don't use the token address when calling /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks(address tokenAddress, uint index) external view returns (uint minedBlocks, uint totalShares); /* ========== Accounts ========== */ /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) external; /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) external view returns (uint); /// @dev Gets the address corresponding to the given index number /// @param index The index number of the specified address /// @return The address corresponding to the given index number function indexAddress(uint index) external view returns (address); /// @dev Gets the registration index number of the specified address /// @param addr Destination address /// @return 0 means nonexistent, non-0 means index number function getAccountIndex(address addr) external view returns (uint); /// @dev Get the length of registered account array /// @return The length of registered account array function getAccountCount() external view returns (uint); } // File: contracts\interface\INestQuery.sol /// @dev This interface defines the methods for price query interface INestQuery { /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(address tokenAddress) external view returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(address tokenAddress) external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ); /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( address tokenAddress, uint height ) external view returns (uint blockNumber, uint price); /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice(address tokenAddress) external view returns (uint blockNumber, uint price); /// @dev Get the last (num) effective price /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(address tokenAddress, uint count) external view returns (uint[] memory); /// @dev Returns the results of latestPrice() and triggeredPriceInfo() /// @param tokenAddress Destination token address /// @return latestPriceBlockNumber The block number of latest price /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function latestPriceAndTriggeredPriceInfo(address tokenAddress) external view returns ( uint latestPriceBlockNumber, uint latestPriceValue, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); /// @dev Returns lastPriceList and triggered price info /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(address tokenAddress, uint count) external view returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); /// @dev Get the latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function triggeredPrice2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ); /// @dev Get the full information of latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) /// @return ntokenAvgPrice Average price of ntoken /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ ); /// @dev Get the latest effective price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function latestPrice2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ); } // File: contracts\interface\INTokenController.sol ///@dev This interface defines the methods for ntoken management interface INTokenController { /// @notice when the auction of a token gets started /// @param tokenAddress The address of the (ERC20) token /// @param ntokenAddress The address of the ntoken w.r.t. token for incentives /// @param owner The address of miner who opened the oracle event NTokenOpened(address tokenAddress, address ntokenAddress, address owner); /// @notice ntoken disable event /// @param tokenAddress token address event NTokenDisabled(address tokenAddress); /// @notice ntoken enable event /// @param tokenAddress token address event NTokenEnabled(address tokenAddress); /// @dev ntoken configuration structure struct Config { // The number of nest needed to pay for opening ntoken. 10000 ether uint96 openFeeNestAmount; // ntoken management is enabled. 0: not enabled, 1: enabled uint8 state; } /// @dev A struct for an ntoken struct NTokenTag { // ntoken address address ntokenAddress; // How much nest has paid for open this ntoken uint96 nestFee; // token address address tokenAddress; // Index for this ntoken uint40 index; // Create time uint48 startTime; // State of this ntoken. 0: disabled; 1 normal uint8 state; } /* ========== Governance ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set the token mapping /// @param tokenAddress Destination token address /// @param ntokenAddress Destination ntoken address /// @param state status for this map function setNTokenMapping(address tokenAddress, address ntokenAddress, uint state) external; /// @dev Get token address from ntoken address /// @param ntokenAddress Destination ntoken address /// @return token address function getTokenAddress(address ntokenAddress) external view returns (address); /// @dev Get ntoken address from token address /// @param tokenAddress Destination token address /// @return ntoken address function getNTokenAddress(address tokenAddress) external view returns (address); /* ========== ntoken management ========== */ /// @dev Bad tokens should be banned function disable(address tokenAddress) external; /// @dev enable ntoken function enable(address tokenAddress) external; /// @notice Open a NToken for a token by anyone (contracts aren't allowed) /// @dev Create and map the (Token, NToken) pair in NestPool /// @param tokenAddress The address of token contract function open(address tokenAddress) external; /* ========== VIEWS ========== */ /// @dev Get ntoken information /// @param tokenAddress Destination token address /// @return ntoken information function getNTokenTag(address tokenAddress) external view returns (NTokenTag memory); /// @dev Get opened ntoken count /// @return ntoken count function getNTokenCount() external view returns (uint); /// @dev List ntoken information by page /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return ntoken information by page function list(uint offset, uint count, uint order) external view returns (NTokenTag[] memory); } // File: contracts\interface\INestLedger.sol /// @dev This interface defines the nest ledger methods interface INestLedger { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Configuration structure of nest ledger contract struct Config { // nest reward scale(10000 based). 2000 uint16 nestRewardScale; // // ntoken reward scale(10000 based). 8000 // uint16 ntokenRewardScale; } /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Carve reward /// @param ntokenAddress Destination ntoken address function carveETHReward(address ntokenAddress) external payable; /// @dev Add reward /// @param ntokenAddress Destination ntoken address function addETHReward(address ntokenAddress) external payable; /// @dev The function returns eth rewards of specified ntoken /// @param ntokenAddress The ntoken address function totalETHRewards(address ntokenAddress) external view returns (uint); /// @dev Pay /// @param ntokenAddress Destination ntoken address. Indicates which ntoken to pay with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function pay(address ntokenAddress, address tokenAddress, address to, uint value) external; /// @dev Settlement /// @param ntokenAddress Destination ntoken address. Indicates which ntoken to settle with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function settle(address ntokenAddress, address tokenAddress, address to, uint value) external payable; } // File: contracts\interface\INToken.sol /// @dev ntoken interface interface INToken { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @dev Mint /// @param value The amount of NToken to add function increaseTotal(uint256 value) external; /// @notice The view of variables about minting /// @dev The naming follows Nestv3.0 /// @return createBlock The block number where the contract was created /// @return recentlyUsedBlock The block number where the last minting went function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock); /// @dev The ABI keeps unchanged with old NTokens, so as to support token-and-ntoken-mining /// @return The address of bidder function checkBidder() external view returns(address); /// @notice The view of totalSupply /// @return The total supply of ntoken function totalSupply() external view returns (uint256); /// @dev The view of balances /// @param owner The address of an account /// @return The balance of the account function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); 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); } // File: contracts\interface\INestMapping.sol /// @dev The interface defines methods for nest builtin contract address mapping interface INestMapping { /// @dev Set the built-in contract address of the system /// @param nestTokenAddress Address of nest token contract /// @param nestNodeAddress Address of nest node contract /// @param nestLedgerAddress INestLedger implementation contract address /// @param nestMiningAddress INestMining implementation contract address for nest /// @param ntokenMiningAddress INestMining implementation contract address for ntoken /// @param nestPriceFacadeAddress INestPriceFacade implementation contract address /// @param nestVoteAddress INestVote implementation contract address /// @param nestQueryAddress INestQuery implementation contract address /// @param nnIncomeAddress NNIncome contract address /// @param nTokenControllerAddress INTokenController implementation contract address function setBuiltinAddress( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ) external; /// @dev Get the built-in contract address of the system /// @return nestTokenAddress Address of nest token contract /// @return nestNodeAddress Address of nest node contract /// @return nestLedgerAddress INestLedger implementation contract address /// @return nestMiningAddress INestMining implementation contract address for nest /// @return ntokenMiningAddress INestMining implementation contract address for ntoken /// @return nestPriceFacadeAddress INestPriceFacade implementation contract address /// @return nestVoteAddress INestVote implementation contract address /// @return nestQueryAddress INestQuery implementation contract address /// @return nnIncomeAddress NNIncome contract address /// @return nTokenControllerAddress INTokenController implementation contract address function getBuiltinAddress() external view returns ( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ); /// @dev Get address of nest token contract /// @return Address of nest token contract function getNestTokenAddress() external view returns (address); /// @dev Get address of nest node contract /// @return Address of nest node contract function getNestNodeAddress() external view returns (address); /// @dev Get INestLedger implementation contract address /// @return INestLedger implementation contract address function getNestLedgerAddress() external view returns (address); /// @dev Get INestMining implementation contract address for nest /// @return INestMining implementation contract address for nest function getNestMiningAddress() external view returns (address); /// @dev Get INestMining implementation contract address for ntoken /// @return INestMining implementation contract address for ntoken function getNTokenMiningAddress() external view returns (address); /// @dev Get INestPriceFacade implementation contract address /// @return INestPriceFacade implementation contract address function getNestPriceFacadeAddress() external view returns (address); /// @dev Get INestVote implementation contract address /// @return INestVote implementation contract address function getNestVoteAddress() external view returns (address); /// @dev Get INestQuery implementation contract address /// @return INestQuery implementation contract address function getNestQueryAddress() external view returns (address); /// @dev Get NNIncome contract address /// @return NNIncome contract address function getNnIncomeAddress() external view returns (address); /// @dev Get INTokenController implementation contract address /// @return INTokenController implementation contract address function getNTokenControllerAddress() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by nest system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string memory key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string memory key) external view returns (address); } // File: contracts\interface\INestGovernance.sol /// @dev This interface defines the governance methods interface INestGovernance is INestMapping { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File: contracts\NestBase.sol /// @dev Base contract of nest contract NestBase { // Address of nest token contract address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C; // Genesis block number of nest // NEST token contract is created at block height 6913517. However, because the mining algorithm of nest1.0 // is different from that at present, a new mining algorithm is adopted from nest2.0. The new algorithm // includes the attenuation logic according to the block. Therefore, it is necessary to trace the block // where the nest begins to decay. According to the circulation when nest2.0 is online, the new mining // algorithm is used to deduce and convert the nest, and the new algorithm is used to mine the nest2.0 // on-line flow, the actual block is 5120000 uint constant NEST_GENESIS_BLOCK = 5120000; /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) virtual public { require(_governance == address(0), 'NEST:!initialize'); _governance = nestGovernanceAddress; } /// @dev INestGovernance implementation contract address address public _governance; /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance /// @param nestGovernanceAddress INestGovernance implementation contract address function update(address nestGovernanceAddress) virtual public { address governance = _governance; require(governance == msg.sender || INestGovernance(governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _governance = nestGovernanceAddress; } /// @dev Migrate funds from current contract to NestLedger /// @param tokenAddress Destination token address.(0 means eth) /// @param value Migrate amount function migrate(address tokenAddress, uint value) external onlyGovernance { address to = INestGovernance(_governance).getNestLedgerAddress(); if (tokenAddress == address(0)) { INestLedger(to).addETHReward { value: value } (address(0)); } else { TransferHelper.safeTransfer(tokenAddress, to, value); } } //---------modifier------------ modifier onlyGovernance() { require(INestGovernance(_governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "NEST:!contract"); _; } } // File: contracts\NestMining.sol /// @dev This contract implemented the mining logic of nest contract NestMining is NestBase, INestMining, INestQuery { // /// @param nestTokenAddress Address of nest token contract // /// @param nestGenesisBlock Genesis block number of nest // constructor(address nestTokenAddress, uint nestGenesisBlock) { // NEST_TOKEN_ADDRESS = nestTokenAddress; // NEST_GENESIS_BLOCK = nestGenesisBlock; // // Placeholder in _accounts, the index of a real account must greater than 0 // _accounts.push(); // } /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) override public { super.initialize(nestGovernanceAddress); // Placeholder in _accounts, the index of a real account must greater than 0 _accounts.push(); } ///@dev Definitions for the price sheet, include the full information. (use 256-bits, a storage unit in ethereum evm) struct PriceSheet { // Index of miner account in _accounts. for this way, mapping an address(which need 160-bits) to a 32-bits // integer, support 4 billion accounts uint32 miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // Represent price as this way, may lose precision, the error less than 1/10^14 // price = priceFraction * 16 ^ priceExponent uint56 priceFloat; } /// @dev Definitions for the price information struct PriceInfo { // Record the index of price sheet, for update price information from price sheet next time. uint32 index; // The block number of this price uint32 height; // The remain number of this price sheet uint32 remainNum; // Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 priceFloat; // Avg Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 avgFloat; // Square of price volatility, need divide by 2^48 uint48 sigmaSQ; } /// @dev Price channel struct PriceChannel { // Array of price sheets PriceSheet[] sheets; // Price information PriceInfo price; // Commission is charged for every post(post2), the commission should be deposited to NestLedger, // for saving gas, according to sheets.length, every increase of 256 will deposit once, The calculation formula is: // // totalFee = fee * increment // // In consideration of takeToken, takeEth, change postFeeUnit or miner pay more fee, the formula will be invalid, // at this point, it is need to settle immediately, the details of triggering settlement logic are as follows // // 1. When there is a bite transaction(currentFee is 0), the counter of no fee sheets will be increase 1 // 2. If the Commission of this time is inconsistent with that of last time, deposit immediately // 3. When the increment of sheets.length is 256, deposit immediately // 4. Everyone can trigger immediate settlement by manually calling the settle() method // // In order to realize the logic above, the following values are defined // // 1. PriceChannel.feeInfo // Low 128-bits represent last fee per post // High 128-bits represent the current counter of no fee sheets (including settled) // // 2. COLLECT_REWARD_MASK // The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit, // COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once), // and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once) // The information of mining fee // Low 128-bits represent fee per post // High 128-bits represent the current counter of no fee sheets (including settled) uint feeInfo; } /// @dev Structure is used to represent a storage location. Storage variable can be used to avoid indexing from mapping many times struct UINT { uint value; } /// @dev Account information struct Account { // Address of account address addr; // Balances of mining account // tokenAddress=>balance mapping(address=>UINT) balances; } // Configuration Config _config; // Registered account information Account[] _accounts; // Mapping from address to index of account. address=>accountIndex mapping(address=>uint) _accountMapping; // Mapping from token address to price channel. tokenAddress=>PriceChannel mapping(address=>PriceChannel) _channels; // Mapping from token address to ntoken address. tokenAddress=>ntokenAddress mapping(address=>address) _addressCache; // Cache for genesis block number of ntoken. ntokenAddress=>genesisBlockNumber mapping(address=>uint) _genesisBlockNumberCache; // INestPriceFacade implementation contract address address _nestPriceFacadeAddress; // INTokenController implementation contract address address _nTokenControllerAddress; // INestLegder implementation contract address address _nestLedgerAddress; // Unit of post fee. 0.0001 ether uint constant DIMI_ETHER = 0.0001 ether; // The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit, // COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once), // and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once) uint constant COLLECT_REWARD_MASK = 0xFF; // Ethereum average block time interval, 14 seconds uint constant ETHEREUM_BLOCK_TIMESPAN = 14; /* ========== Governance ========== */ /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance /// @param nestGovernanceAddress INestGovernance implementation contract address function update(address nestGovernanceAddress) override public { super.update(nestGovernanceAddress); ( //address nestTokenAddress , //address nestNodeAddress , //address nestLedgerAddress _nestLedgerAddress, //address nestMiningAddress , //address ntokenMiningAddress , //address nestPriceFacadeAddress _nestPriceFacadeAddress, //address nestVoteAddress , //address nestQueryAddress , //address nnIncomeAddress , //address nTokenControllerAddress _nTokenControllerAddress ) = INestGovernance(nestGovernanceAddress).getBuiltinAddress(); } /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) override external onlyGovernance { _config = config; } /// @dev Get configuration /// @return Configuration object function getConfig() override external view returns (Config memory) { return _config; } /// @dev Clear chache of token. while ntoken recreated, this method is need to call /// @param tokenAddress Token address function resetNTokenCache(address tokenAddress) external onlyGovernance { // Clear cache address ntokenAddress = _getNTokenAddress(tokenAddress); _genesisBlockNumberCache[ntokenAddress] = 0; _addressCache[tokenAddress] = _addressCache[ntokenAddress] = address(0); } /// @dev Set the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @param ntokenAddress The ntoken address function setNTokenAddress(address tokenAddress, address ntokenAddress) override external onlyGovernance { _addressCache[tokenAddress] = ntokenAddress; } /// @dev Get the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @return The ntoken address function getNTokenAddress(address tokenAddress) override external view returns (address) { return _addressCache[tokenAddress]; } /* ========== Mining ========== */ // Get ntoken address of from token address function _getNTokenAddress(address tokenAddress) private returns (address) { address ntokenAddress = _addressCache[tokenAddress]; if (ntokenAddress == address(0)) { ntokenAddress = INTokenController(_nTokenControllerAddress).getNTokenAddress(tokenAddress); if (ntokenAddress != address(0)) { _addressCache[tokenAddress] = ntokenAddress; } } return ntokenAddress; } // Get genesis block number of ntoken function _getNTokenGenesisBlock(address ntokenAddress) private returns (uint) { uint genesisBlockNumber = _genesisBlockNumberCache[ntokenAddress]; if (genesisBlockNumber == 0) { (genesisBlockNumber,) = INToken(ntokenAddress).checkBlockInfo(); _genesisBlockNumberCache[ntokenAddress] = genesisBlockNumber; } return genesisBlockNumber; } /// @notice Post a price sheet for TOKEN /// @dev It is for TOKEN (except USDT and NTOKENs) whose NTOKEN has a total supply below a threshold (e.g. 5,000,000 * 1e18) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN function post(address tokenAddress, uint ethNum, uint tokenAmountPerEth) override external payable { Config memory config = _config; // 1. Check arguments require(ethNum > 0 && ethNum == uint(config.postEthUnit), "NM:!ethNum"); require(tokenAmountPerEth > 0, "NM:!price"); // 2. Check price channel // Check if the token allow post() address ntokenAddress = _getNTokenAddress(tokenAddress); require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress"); // Unit of nest is different, but the total supply already exceeded the number of this issue. No additional judgment will be made // ntoken is mint when the price sheet is closed (or withdrawn), this may be the problem that the user // intentionally does not close or withdraw, which leads to the inaccurate judgment of the total amount. ignore require(INToken(ntokenAddress).totalSupply() < uint(config.doublePostThreshold) * 10000 ether, "NM:!post2"); // 3. Load token channel and sheets PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; // 4. Freeze assets uint accountIndex = _addressIndex(msg.sender); // Freeze token and nest // Because of the use of floating-point representation(fraction * 16 ^ exponent), it may bring some precision loss // After assets are frozen according to tokenAmountPerEth * ethNum, the part with poor accuracy may be lost when // the assets are returned, It should be frozen according to decodeFloat(fraction, exponent) * ethNum // However, considering that the loss is less than 1 / 10 ^ 14, the loss here is ignored, and the part of // precision loss can be transferred out as system income in the future _freeze2( _accounts[accountIndex].balances, tokenAddress, tokenAmountPerEth * ethNum, uint(config.pledgeNest) * 1000 ether ); // 5. Deposit fee // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part uint length = sheets.length; uint shares = _collect(config, channel, ntokenAddress, length, msg.value - ethNum * 1 ether); require(shares > 0 && shares < 256, "NM:!fee"); // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 6. Create token price sheet emit Post(tokenAddress, msg.sender, length, ethNum, tokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(ethNum), uint(config.pledgeNest), shares, tokenAmountPerEth); } /// @notice Post two price sheets for a token and its ntoken simultaneously /// @dev Support dual-posts for TOKEN/NTOKEN, (ETH, TOKEN) + (ETH, NTOKEN) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN /// @param ntokenAmountPerEth The price of NTOKEN function post2( address tokenAddress, uint ethNum, uint tokenAmountPerEth, uint ntokenAmountPerEth ) override external payable { Config memory config = _config; // 1. Check arguments require(ethNum > 0 && ethNum == uint(config.postEthUnit), "NM:!ethNum"); require(tokenAmountPerEth > 0 && ntokenAmountPerEth > 0, "NM:!price"); // 2. Check price channel address ntokenAddress = _getNTokenAddress(tokenAddress); require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress"); // 3. Load token channel and sheets PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; // 4. Freeze assets uint pledgeNest = uint(config.pledgeNest); uint accountIndex = _addressIndex(msg.sender); { mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; _freeze(balances, tokenAddress, ethNum * tokenAmountPerEth); _freeze2(balances, ntokenAddress, ethNum * ntokenAmountPerEth, pledgeNest * 2000 ether); } // 5. Deposit fee // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part uint length = sheets.length; uint shares = _collect(config, channel, ntokenAddress, length, msg.value - ethNum * 2 ether); require(shares > 0 && shares < 256, "NM:!fee"); // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 6. Create token price sheet emit Post(tokenAddress, msg.sender, length, ethNum, tokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(ethNum), pledgeNest, shares, tokenAmountPerEth); // 7. Load ntoken channel and sheets channel = _channels[ntokenAddress]; sheets = channel.sheets; // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 8. Create token price sheet emit Post(ntokenAddress, msg.sender, sheets.length, ethNum, ntokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(ethNum), pledgeNest, 0, ntokenAmountPerEth); } /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeToken( address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth ) override external payable { Config memory config = _config; // 1. Check arguments require(takeNum > 0 && takeNum % uint(config.postEthUnit) == 0, "NM:!takeNum"); require(newTokenAmountPerEth > 0, "NM:!price"); // 2. Load price sheet PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; PriceSheet memory sheet = sheets[index]; // 3. Check state require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum"); require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state"); // 4. Deposit fee { // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part address ntokenAddress = _getNTokenAddress(tokenAddress); if (tokenAddress != ntokenAddress) { _collect(config, channel, ntokenAddress, sheets.length, 0); } } // 5. Calculate the number of eth, token and nest needed, and freeze them uint needEthNum; uint level = uint(sheet.level); // When the level of the sheet is less than 4, both the nest and the scale of the offer are doubled if (level < uint(config.maxBiteNestedLevel)) { // Double scale sheet needEthNum = takeNum << 1; ++level; } // When the level of the sheet reaches 4 or more, nest doubles, but the scale does not else { // Single scale sheet needEthNum = takeNum; // It is possible that the length of a single chain exceeds 255. When the length of a chain reaches 4 // or more, there is no logical dependence on the specific value of the contract, and the count will // not increase after it is accumulated to 255 if (level < 255) ++level; } require(msg.value == (needEthNum + takeNum) * 1 ether, "NM:!value"); // Number of nest to be pledged //uint needNest1k = ((takeNum << 1) / uint(config.postEthUnit)) * uint(config.pledgeNest); // sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal)); // Freeze nest and token uint accountIndex = _addressIndex(msg.sender); { mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; uint backTokenValue = decodeFloat(sheet.priceFloat) * takeNum; if (needEthNum * newTokenAmountPerEth > backTokenValue) { _freeze2( balances, tokenAddress, needEthNum * newTokenAmountPerEth - backTokenValue, needNest1k * 1000 ether ); } else { _freeze(balances, NEST_TOKEN_ADDRESS, needNest1k * 1000 ether); _unfreeze(balances, tokenAddress, backTokenValue - needEthNum * newTokenAmountPerEth); } } // 6. Update the biten sheet sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum); sheet.ethNumBal = uint32(uint(sheet.ethNumBal) + takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) - takeNum); sheets[index] = sheet; // 7. Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 8. Create price sheet emit Post(tokenAddress, msg.sender, sheets.length, needEthNum, newTokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newTokenAmountPerEth); } /// @notice Call the function to buy ETH from a posted price sheet /// @dev bite ETH by TOKEN(NTOKEN), (-ethNumBal, +tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeEth( address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth ) override external payable { Config memory config = _config; // 1. Check arguments require(takeNum > 0 && takeNum % uint(config.postEthUnit) == 0, "NM:!takeNum"); require(newTokenAmountPerEth > 0, "NM:!price"); // 2. Load price sheet PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; PriceSheet memory sheet = sheets[index]; // 3. Check state require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum"); require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state"); // 4. Deposit fee { // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part address ntokenAddress = _getNTokenAddress(tokenAddress); if (tokenAddress != ntokenAddress) { _collect(config, channel, ntokenAddress, sheets.length, 0); } } // 5. Calculate the number of eth, token and nest needed, and freeze them uint needEthNum; uint level = uint(sheet.level); // When the level of the sheet is less than 4, both the nest and the scale of the offer are doubled if (level < uint(config.maxBiteNestedLevel)) { // Double scale sheet needEthNum = takeNum << 1; ++level; } // When the level of the sheet reaches 4 or more, nest doubles, but the scale does not else { // Single scale sheet needEthNum = takeNum; // It is possible that the length of a single chain exceeds 255. When the length of a chain reaches 4 // or more, there is no logical dependence on the specific value of the contract, and the count will // not increase after it is accumulated to 255 if (level < 255) ++level; } require(msg.value == (needEthNum - takeNum) * 1 ether, "NM:!value"); // Number of nest to be pledged //uint needNest1k = ((takeNum << 1) / uint(config.postEthUnit)) * uint(config.pledgeNest); // sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal)); // Freeze nest and token uint accountIndex = _addressIndex(msg.sender); _freeze2( _accounts[accountIndex].balances, tokenAddress, needEthNum * newTokenAmountPerEth + decodeFloat(sheet.priceFloat) * takeNum, needNest1k * 1000 ether ); // 6. Update the biten sheet sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum); sheet.ethNumBal = uint32(uint(sheet.ethNumBal) - takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) + takeNum); sheets[index] = sheet; // 7. Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 8. Create price sheet emit Post(tokenAddress, msg.sender, sheets.length, needEthNum, newTokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newTokenAmountPerEth); } // Create price sheet function _createPriceSheet( PriceSheet[] storage sheets, uint accountIndex, uint32 ethNum, uint nestNum1k, uint level_shares, uint tokenAmountPerEth ) private { sheets.push(PriceSheet( uint32(accountIndex), // uint32 miner; uint32(block.number), // uint32 height; ethNum, // uint32 remainNum; ethNum, // uint32 ethNumBal; ethNum, // uint32 tokenNumBal; uint24(nestNum1k), // uint32 nestNum1k; uint8(level_shares >> 8), // uint8 level; uint8(level_shares & 0xFF), encodeFloat(tokenAmountPerEth) )); } // Nest ore drawing attenuation interval. 2400000 blocks, about one year uint constant NEST_REDUCTION_SPAN = 2400000; // The decay limit of nest ore drawing becomes stable after exceeding this interval. 24 million blocks, about 10 years uint constant NEST_REDUCTION_LIMIT = 24000000; //NEST_REDUCTION_SPAN * 10; // Attenuation gradient array, each attenuation step value occupies 16 bits. The attenuation value is an integer uint constant NEST_REDUCTION_STEPS = 0x280035004300530068008300A300CC010001400190; // 0 // | (uint(400 / uint(1)) << (16 * 0)) // | (uint(400 * 8 / uint(10)) << (16 * 1)) // | (uint(400 * 8 * 8 / uint(10 * 10)) << (16 * 2)) // | (uint(400 * 8 * 8 * 8 / uint(10 * 10 * 10)) << (16 * 3)) // | (uint(400 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10)) << (16 * 4)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10)) << (16 * 5)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10)) << (16 * 6)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 7)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 8)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 9)) // //| (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 10)); // | (uint(40) << (16 * 10)); // Calculation of attenuation gradient function _redution(uint delta) private pure returns (uint) { if (delta < NEST_REDUCTION_LIMIT) { return (NEST_REDUCTION_STEPS >> ((delta / NEST_REDUCTION_SPAN) << 4)) & 0xFFFF; } return (NEST_REDUCTION_STEPS >> 160) & 0xFFFF; } /// @notice Close a price sheet of (ETH, USDx) | (ETH, NEST) | (ETH, TOKEN) | (ETH, NTOKEN) /// @dev Here we allow an empty price sheet (still in VERIFICATION-PERIOD) to be closed /// @param tokenAddress The address of TOKEN contract /// @param index The index of the price sheet w.r.t. `token` function close(address tokenAddress, uint index) override external { Config memory config = _config; PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; // Load the price channel address ntokenAddress = _getNTokenAddress(tokenAddress); // Call _close() method to close price sheet (uint accountIndex, Tunple memory total) = _close(config, sheets, index, ntokenAddress); if (accountIndex > 0) { // Return eth if (uint(total.ethNum) > 0) { payable(indexAddress(accountIndex)).transfer(uint(total.ethNum) * 1 ether); } // Unfreeze assets _unfreeze3( _accounts[accountIndex].balances, tokenAddress, total.tokenValue, ntokenAddress, uint(total.ntokenValue), uint(total.nestValue) ); } // Calculate the price _stat(config, channel, sheets); } /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN contract /// @param indices A list of indices of sheets w.r.t. `token` function closeList(address tokenAddress, uint[] memory indices) override external { // Call _closeList() method to close price sheets ( uint accountIndex, Tunple memory total, address ntokenAddress ) = _closeList(_config, _channels[tokenAddress], tokenAddress, indices); // Return eth payable(indexAddress(accountIndex)).transfer(uint(total.ethNum) * 1 ether); // Unfreeze assets _unfreeze3( _accounts[accountIndex].balances, tokenAddress, uint(total.tokenValue), ntokenAddress, uint(total.ntokenValue), uint(total.nestValue) ); } /// @notice Close two batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN1 contract /// @param tokenIndices A list of indices of sheets w.r.t. `token` /// @param ntokenIndices A list of indices of sheets w.r.t. `ntoken` function closeList2( address tokenAddress, uint[] memory tokenIndices, uint[] memory ntokenIndices ) override external { Config memory config = _config; mapping(address=>PriceChannel) storage channels = _channels; // Call _closeList() method to close price sheets ( uint accountIndex1, Tunple memory total1, address ntokenAddress ) = _closeList(config, channels[tokenAddress], tokenAddress, tokenIndices); ( uint accountIndex2, Tunple memory total2, //address ntokenAddress2 ) = _closeList(config, channels[ntokenAddress], ntokenAddress, ntokenIndices); require(accountIndex1 == accountIndex2, "NM:!miner"); //require(ntokenAddress1 == tokenAddress2, "NM:!tokenAddress"); require(uint(total2.ntokenValue) == 0, "NM!ntokenValue"); // Return eth payable(indexAddress(accountIndex1)).transfer((uint(total1.ethNum) + uint(total2.ethNum)) * 1 ether); // Unfreeze assets _unfreeze3( _accounts[accountIndex1].balances, tokenAddress, uint(total1.tokenValue), ntokenAddress, uint(total1.ntokenValue) + uint(total2.tokenValue)/* + uint(total2.ntokenValue) */, uint(total1.nestValue) + uint(total2.nestValue) ); } // Calculation number of blocks which mined function _calcMinedBlocks( PriceSheet[] storage sheets, uint index, PriceSheet memory sheet ) private view returns (uint minedBlocks, uint totalShares) { uint length = sheets.length; uint height = uint(sheet.height); totalShares = uint(sheet.shares); // Backward looking for sheets in the same block for (uint i = index; ++i < length && uint(sheets[i].height) == height;) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[i].shares); } //i = index; // Find sheets in the same block forward uint prev = height; while (index > 0 && uint(prev = sheets[--index].height) == height) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[index].shares); } if (index > 0 || height > prev) { minedBlocks = height - prev; } else { minedBlocks = 10; } } // This structure is for the _close() method to return multiple values struct Tunple { uint tokenValue; uint64 ethNum; uint96 nestValue; uint96 ntokenValue; } // Close price sheet function _close( Config memory config, PriceSheet[] storage sheets, uint index, address ntokenAddress ) private returns (uint accountIndex, Tunple memory value) { PriceSheet memory sheet = sheets[index]; uint height = uint(sheet.height); // Check the status of the price sheet to see if it has reached the effective block interval or has been finished if ((accountIndex = uint(sheet.miner)) > 0 && (height + uint(config.priceEffectSpan) < block.number)) { // TMP: tmp is a polysemous name, here means sheet.shares uint tmp = uint(sheet.shares); // Mining logic // The price sheet which shares is zero dosen't mining if (tmp > 0) { // Currently, mined represents the number of blocks has mined (uint mined, uint totalShares) = _calcMinedBlocks(sheets, index, sheet); // nest mining if (ntokenAddress == NEST_TOKEN_ADDRESS) { // Since then, mined represents the amount of mining // mined = ( // mined // * uint(sheet.shares) // * _redution(height - NEST_GENESIS_BLOCK) // * 1 ether // * uint(config.minerNestReward) // / 10000 // / totalShares // ); // The original expression is shown above. In order to save gas, // the part that can be calculated in advance is calculated first mined = ( mined * tmp * _redution(height - NEST_GENESIS_BLOCK) * uint(config.minerNestReward) * 0.0001 ether / totalShares ); } // ntoken mining else { // The limit blocks can be mined if (mined > uint(config.ntokenMinedBlockLimit)) { mined = uint(config.ntokenMinedBlockLimit); } // Since then, mined represents the amount of mining mined = ( mined * tmp * _redution(height - _getNTokenGenesisBlock(ntokenAddress)) * 0.01 ether / totalShares ); // Put this logic into widhdran() method to reduce gas consumption // ntoken bidders address bidder = INToken(ntokenAddress).checkBidder(); // Legacy ntoken, need separate if (bidder != address(this)) { // Considering that multiple sheets in the same block are small probability events, // we can send token to bidders in each closing operation // 5% for bidder // TMP: tmp is a polysemous name, here means mint ntoken amount for miner tmp = mined * uint(config.minerNTokenReward) / 10000; _unfreeze( _accounts[_addressIndex(bidder)].balances, ntokenAddress, mined - tmp ); // Miner take according proportion which set mined = tmp; } } value.ntokenValue = uint96(mined); } value.nestValue = uint96(uint(sheet.nestNum1k) * 1000 ether); value.ethNum = uint64(sheet.ethNumBal); value.tokenValue = decodeFloat(sheet.priceFloat) * uint(sheet.tokenNumBal); // Set sheet.miner to 0, express the sheet is closed sheet.miner = uint32(0); sheet.ethNumBal = uint32(0); sheet.tokenNumBal = uint32(0); sheets[index] = sheet; } } // Batch close sheets function _closeList( Config memory config, PriceChannel storage channel, address tokenAddress, uint[] memory indices ) private returns (uint accountIndex, Tunple memory total, address ntokenAddress) { ntokenAddress = _getNTokenAddress(tokenAddress); PriceSheet[] storage sheets = channel.sheets; accountIndex = 0; // 1. Traverse sheets for (uint i = indices.length; i > 0;) { // Because too many variables need to be returned, too many variables will be defined, so the structure of tunple is defined (uint minerIndex, Tunple memory value) = _close(config, sheets, indices[--i], ntokenAddress); // Batch closing quotation can only close sheet of the same user if (accountIndex == 0) { // accountIndex == 0 means the first sheet, and the number of this sheet is taken accountIndex = minerIndex; } else { // accountIndex != 0 means that it is a follow-up sheet, and the miner number must be consistent with the previous record require(accountIndex == minerIndex, "NM:!miner"); } total.ntokenValue += value.ntokenValue; total.nestValue += value.nestValue; total.ethNum += value.ethNum; total.tokenValue += value.tokenValue; } _stat(config, channel, sheets); } // Calculate price, average price and volatility function _stat(Config memory config, PriceChannel storage channel, PriceSheet[] storage sheets) private { // Load token price information PriceInfo memory p0 = channel.price; // Length of sheets uint length = sheets.length; // The index of the sheet to be processed in the sheet array uint index = uint(p0.index); // The latest block number for which the price has been calculated uint prev = uint(p0.height); // It's not necessary to load the price information in p0 // Eth count variable used to calculate price uint totalEthNum = 0; // Token count variable for price calculation uint totalTokenValue = 0; // Block number of current sheet uint height = 0; // Traverse the sheets to find the effective price uint effectBlock = block.number - uint(config.priceEffectSpan); PriceSheet memory sheet; for (; ; ++index) { // Gas attack analysis, each post transaction, calculated according to post, needs to write // at least one sheet and freeze two kinds of assets, which needs to consume at least 30000 gas, // In addition to the basic cost of the transaction, at least 50000 gas is required. // In addition, there are other reading and calculation operations. The gas consumed by each // transaction is impossible less than 70000 gas, The attacker can accumulate up to 20 blocks // of sheets to be generated. To ensure that the calculation can be completed in one block, // it is necessary to ensure that the consumption of each price does not exceed 70000 / 20 = 3500 gas, // According to the current logic, each calculation of a price needs to read a storage unit (800) // and calculate the consumption, which can not reach the dangerous value of 3500, so the gas attack // is not considered // Traverse the sheets that has reached the effective interval from the current position bool flag = index >= length || (height = uint((sheet = sheets[index]).height)) >= effectBlock; // Not the same block (or flag is false), calculate the price and update it if (flag || prev != height) { // totalEthNum > 0 Can calculate the price if (totalEthNum > 0) { // Calculate average price and Volatility // Calculation method of volatility of follow-up price uint tmp = decodeFloat(p0.priceFloat); // New price uint price = totalTokenValue / totalEthNum; // Update price p0.remainNum = uint32(totalEthNum); p0.priceFloat = encodeFloat(price); // Clear cumulative values totalEthNum = 0; totalTokenValue = 0; if (tmp > 0) { // Calculate average price // avgPrice[i + 1] = avgPrice[i] * 90% + price[i] * 10% p0.avgFloat = encodeFloat((decodeFloat(p0.avgFloat) * 9 + price) / 10); // When the accuracy of the token is very high or the value of the token relative to // eth is very low, the price may be very large, and there may be overflow problem, // it is not considered for the moment tmp = (price << 48) / tmp; if (tmp > 0x1000000000000) { tmp = tmp - 0x1000000000000; } else { tmp = 0x1000000000000 - tmp; } // earn = price[i] / price[i - 1] - 1; // seconds = time[i] - time[i - 1]; // sigmaSQ[i + 1] = sigmaSQ[i] * 90% + (earn ^ 2 / seconds) * 10% tmp = ( uint(p0.sigmaSQ) * 9 + // It is inevitable that prev greatter than p0.height ((tmp * tmp / ETHEREUM_BLOCK_TIMESPAN / (prev - uint(p0.height))) >> 48) ) / 10; // The current implementation assumes that the volatility cannot exceed 1, and // corresponding to this, when the calculated value exceeds 1, expressed as 0xFFFFFFFFFFFF if (tmp > 0xFFFFFFFFFFFF) { tmp = 0xFFFFFFFFFFFF; } p0.sigmaSQ = uint48(tmp); } // The calculation methods of average price and volatility are different for first price else { // The average price is equal to the price //p0.avgTokenAmount = uint64(price); p0.avgFloat = p0.priceFloat; // The volatility is 0 p0.sigmaSQ = uint48(0); } // Update price block number p0.height = uint32(prev); } // Move to new block number prev = height; } if (flag) { break; } // Cumulative price information totalEthNum += uint(sheet.remainNum); totalTokenValue += decodeFloat(sheet.priceFloat) * uint(sheet.remainNum); } // Update price infomation if (index > uint(p0.index)) { p0.index = uint32(index); channel.price = p0; } } /// @dev The function updates the statistics of price sheets /// It calculates from priceInfo to the newest that is effective. function stat(address tokenAddress) override external { PriceChannel storage channel = _channels[tokenAddress]; _stat(_config, channel, channel.sheets); } // Collect and deposit the commission into NestLedger function _collect( Config memory config, PriceChannel storage channel, address ntokenAddress, uint length, uint currentFee ) private returns (uint) { // Commission is charged for every post(post2), the commission should be deposited to NestLedger, // for saving gas, according to sheets.length, every increase of 256 will deposit once, The calculation formula is: // // totalFee = fee * increment // // In consideration of takeToken, takeEth, change postFeeUnit or miner pay more fee, the formula will be invalid, // at this point, it is need to settle immediately, the details of triggering settlement logic are as follows // // 1. When there is a bite transaction(currentFee is 0), the counter of no fee sheets will be increase 1 // 2. If the Commission of this time is inconsistent with that of last time, deposit immediately // 3. When the increment of sheets.length is 256, deposit immediately // 4. Everyone can trigger immediate settlement by manually calling the settle() method // // In order to realize the logic above, the following values are defined // // 1. PriceChannel.feeInfo // Low 128-bits represent last fee per post // High 128-bits represent the current counter of no fee sheets (including settled) // // 2. COLLECT_REWARD_MASK // The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit, // COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once), // and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once) uint feeUnit = uint(config.postFeeUnit) * DIMI_ETHER; require(currentFee % feeUnit == 0, "NM:!fee"); uint feeInfo = channel.feeInfo; uint oldFee = feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // length == 255 means is time to save reward // currentFee != oldFee means the fee is changed, need to settle if (length & COLLECT_REWARD_MASK == COLLECT_REWARD_MASK || (currentFee != oldFee && currentFee > 0)) { // Save reward INestLedger(_nestLedgerAddress).carveETHReward { value: currentFee + oldFee * ((length & COLLECT_REWARD_MASK) - (feeInfo >> 128)) } (ntokenAddress); // Update fee information channel.feeInfo = currentFee | (((length + 1) & COLLECT_REWARD_MASK) << 128); } // currentFee is 0, increase no fee counter else if (currentFee == 0) { // channel.feeInfo = feeInfo + (1 << 128); channel.feeInfo = feeInfo + 0x100000000000000000000000000000000; } // Calculate share count return currentFee / feeUnit; } /// @dev Settlement Commission /// @param tokenAddress The token address function settle(address tokenAddress) override external { address ntokenAddress = _getNTokenAddress(tokenAddress); // ntoken is no reward if (tokenAddress != ntokenAddress) { PriceChannel storage channel = _channels[tokenAddress]; uint length = channel.sheets.length & COLLECT_REWARD_MASK; uint feeInfo = channel.feeInfo; // Save reward INestLedger(_nestLedgerAddress).carveETHReward { value: (feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) * (length - (feeInfo >> 128)) } (ntokenAddress); // Manual settlement does not need to update Commission variables channel.feeInfo = (feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | (length << 128); } } // Convert PriceSheet to PriceSheetView function _toPriceSheetView(PriceSheet memory sheet, uint index) private view returns (PriceSheetView memory) { return PriceSheetView( // Index number uint32(index), // Miner address indexAddress(sheet.miner), // The block number of this price sheet packaged sheet.height, // The remain number of this price sheet sheet.remainNum, // The eth number which miner will got sheet.ethNumBal, // The eth number which equivalent to token's value which miner will got sheet.tokenNumBal, // The pledged number of nest in this sheet. (Unit: 1000nest) sheet.nestNum1k, // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet sheet.level, // Post fee shares sheet.shares, // Price uint152(decodeFloat(sheet.priceFloat)) ); } /// @dev List sheets by page /// @param tokenAddress Destination token address /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list( address tokenAddress, uint offset, uint count, uint order ) override external view noContract returns (PriceSheetView[] memory) { PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheetView[] memory result = new PriceSheetView[](count); uint length = sheets.length; uint i = 0; // Reverse order if (order == 0) { uint index = length - offset; uint end = index > count ? index - count : 0; while (index > end) { --index; result[i++] = _toPriceSheetView(sheets[index], index); } } // Positive order else { uint index = offset; uint end = index + count; if (end > length) { end = length; } while (index < end) { result[i++] = _toPriceSheetView(sheets[index], index); ++index; } } return result; } /// @dev Estimated mining amount /// @param tokenAddress Destination token address /// @return Estimated mining amount function estimate(address tokenAddress) override external view returns (uint) { address ntokenAddress = INTokenController(_nTokenControllerAddress).getNTokenAddress(tokenAddress); if (tokenAddress != ntokenAddress) { PriceSheet[] storage sheets = _channels[tokenAddress].sheets; uint index = sheets.length; while (index > 0) { PriceSheet memory sheet = sheets[--index]; if (uint(sheet.shares) > 0) { // Standard mining amount uint standard = (block.number - uint(sheet.height)) * 1 ether; // Genesis block number of ntoken uint genesisBlock = NEST_GENESIS_BLOCK; // Not nest, the calculation methods of standard mining amount and genesis block number are different if (ntokenAddress != NEST_TOKEN_ADDRESS) { // The standard mining amount of ntoken is 1/100 of nest standard /= 100; // Genesis block number of ntoken is obtained separately (genesisBlock,) = INToken(ntokenAddress).checkBlockInfo(); } return standard * _redution(block.number - genesisBlock); } } } return 0; } /// @dev Query the quantity of the target quotation /// @param tokenAddress Token address. The token can't mine. Please make sure you don't use the token address when calling /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks( address tokenAddress, uint index ) override external view returns (uint minedBlocks, uint totalShares) { PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheet memory sheet = sheets[index]; // The bite sheet or ntoken sheet dosen't mining if (uint(sheet.shares) == 0) { return (0, 0); } return _calcMinedBlocks(sheets, index, sheet); } /* ========== Accounts ========== */ /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) override external { // The user's locked nest and the mining pool's nest are stored together. When the nest is mined over, // the problem of taking the locked nest as the ore drawing will appear // As it will take a long time for nest to finish mining, this problem will not be considered for the time being UINT storage balance = _accounts[_accountMapping[msg.sender]].balances[tokenAddress]; //uint balanceValue = balance.value; //require(balanceValue >= value, "NM:!balance"); balance.value -= value; // ntoken mining uint ntokenBalance = INToken(tokenAddress).balanceOf(address(this)); if (ntokenBalance < value) { // mining INToken(tokenAddress).increaseTotal(value - ntokenBalance); } TransferHelper.safeTransfer(tokenAddress, msg.sender, value); } /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) override external view returns (uint) { return _accounts[_accountMapping[addr]].balances[tokenAddress].value; } /// @dev Gets the index number of the specified address. If it does not exist, register /// @param addr Destination address /// @return The index number of the specified address function _addressIndex(address addr) private returns (uint) { uint index = _accountMapping[addr]; if (index == 0) { // If it exceeds the maximum number that 32 bits can store, you can't continue to register a new account. // If you need to support a new account, you need to update the contract require((_accountMapping[addr] = index = _accounts.length) < 0x100000000, "NM:!accounts"); _accounts.push().addr = addr; } return index; } /// @dev Gets the address corresponding to the given index number /// @param index The index number of the specified address /// @return The address corresponding to the given index number function indexAddress(uint index) override public view returns (address) { return _accounts[index].addr; } /// @dev Gets the registration index number of the specified address /// @param addr Destination address /// @return 0 means nonexistent, non-0 means index number function getAccountIndex(address addr) override external view returns (uint) { return _accountMapping[addr]; } /// @dev Get the length of registered account array /// @return The length of registered account array function getAccountCount() override external view returns (uint) { return _accounts.length; } /* ========== Asset management ========== */ /// @dev Freeze token /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param value token amount function _freeze(mapping(address=>UINT) storage balances, address tokenAddress, uint value) private { UINT storage balance = balances[tokenAddress]; uint balanceValue = balance.value; if (balanceValue < value) { balance.value = 0; TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), value - balanceValue); } else { balance.value = balanceValue - value; } } /// @dev Unfreeze token /// @param balances Balances ledgerBalances ledger /// @param tokenAddress Destination token address /// @param value token amount function _unfreeze(mapping(address=>UINT) storage balances, address tokenAddress, uint value) private { UINT storage balance = balances[tokenAddress]; balance.value += value; } /// @dev freeze token and nest /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param tokenValue token amount /// @param nestValue nest amount function _freeze2( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, uint nestValue ) private { UINT storage balance; uint balanceValue; // If tokenAddress is NEST_TOKEN_ADDRESS, add it to nestValue if (NEST_TOKEN_ADDRESS == tokenAddress) { nestValue += tokenValue; } // tokenAddress is not NEST_TOKEN_ADDRESS, unfreeze it else { balance = balances[tokenAddress]; balanceValue = balance.value; if (balanceValue < tokenValue) { balance.value = 0; TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), tokenValue - balanceValue); } else { balance.value = balanceValue - tokenValue; } } // Unfreeze nest balance = balances[NEST_TOKEN_ADDRESS]; balanceValue = balance.value; if (balanceValue < nestValue) { balance.value = 0; TransferHelper.safeTransferFrom(NEST_TOKEN_ADDRESS, msg.sender, address(this), nestValue - balanceValue); } else { balance.value = balanceValue - nestValue; } } /// @dev Unfreeze token, ntoken and nest /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param tokenValue token amount /// @param ntokenAddress Destination ntoken address /// @param ntokenValue ntoken amount /// @param nestValue nest amount function _unfreeze3( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, address ntokenAddress, uint ntokenValue, uint nestValue ) private { UINT storage balance; // If tokenAddress is ntokenAddress, add it to ntokenValue if (ntokenAddress == tokenAddress) { ntokenValue += tokenValue; } // tokenAddress is not ntokenAddress, unfreeze it else { balance = balances[tokenAddress]; balance.value += tokenValue; } // If ntokenAddress is NEST_TOKEN_ADDRESS, add it to nestValue if (NEST_TOKEN_ADDRESS == ntokenAddress) { nestValue += ntokenValue; } // ntokenAddress is NEST_TOKEN_ADDRESS, unfreeze it else { balance = balances[ntokenAddress]; balance.value += ntokenValue; } // Unfreeze nest balance = balances[NEST_TOKEN_ADDRESS]; balance.value += nestValue; } /* ========== INestQuery ========== */ // Check msg.sender function _check() private view { require(msg.sender == _nestPriceFacadeAddress || msg.sender == tx.origin); } /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(address tokenAddress) override public view returns (uint blockNumber, uint price) { _check(); PriceInfo memory priceInfo = _channels[tokenAddress].price; if (uint(priceInfo.remainNum) > 0) { return (uint(priceInfo.height) + uint(_config.priceEffectSpan), decodeFloat(priceInfo.priceFloat)); } return (0, 0); } /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(address tokenAddress) override public view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ) { _check(); PriceInfo memory priceInfo = _channels[tokenAddress].price; if (uint(priceInfo.remainNum) > 0) { return ( uint(priceInfo.height) + uint(_config.priceEffectSpan), decodeFloat(priceInfo.priceFloat), decodeFloat(priceInfo.avgFloat), (uint(priceInfo.sigmaSQ) * 1 ether) >> 48 ); } return (0, 0, 0, 0); } /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( address tokenAddress, uint height ) override external view returns (uint blockNumber, uint price) { _check(); PriceSheet[] storage sheets = _channels[tokenAddress].sheets; uint priceEffectSpan = uint(_config.priceEffectSpan); uint length = sheets.length; uint index = 0; uint sheetHeight; height -= priceEffectSpan; { // If there is no sheet in this channel, length is 0, length - 1 will overflow, uint right = length - 1; uint left = 0; // Find the index use Binary Search while (left < right) { index = (left + right) >> 1; sheetHeight = uint(sheets[index].height); if (height > sheetHeight) { left = ++index; } else if (height < sheetHeight) { // When index = 0, this statement will have an underflow exception, which usually // indicates that the effective block height passed during the call is lower than // the block height of the first quotation right = --index; } else { break; } } } // Calculate price uint totalEthNum = 0; uint totalTokenValue = 0; uint h = 0; uint remainNum; PriceSheet memory sheet; // Find sheets forward for (uint i = index; i < length;) { sheet = sheets[i++]; sheetHeight = uint(sheet.height); if (height < sheetHeight) { break; } remainNum = uint(sheet.remainNum); if (remainNum > 0) { if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } } // Find sheets backward while (index > 0) { sheet = sheets[--index]; remainNum = uint(sheet.remainNum); if (remainNum > 0) { sheetHeight = uint(sheet.height); if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } } if (totalEthNum > 0) { return (h + priceEffectSpan, totalTokenValue / totalEthNum); } return (0, 0); } /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice(address tokenAddress) override public view returns (uint blockNumber, uint price) { _check(); PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheet memory sheet; uint priceEffectSpan = uint(_config.priceEffectSpan); uint h = block.number - priceEffectSpan; uint index = sheets.length; uint totalEthNum = 0; uint totalTokenValue = 0; uint height = 0; for (; ; ) { bool flag = index == 0; if (flag || height != uint((sheet = sheets[--index]).height)) { if (totalEthNum > 0 && height <= h) { return (height + priceEffectSpan, totalTokenValue / totalEthNum); } if (flag) { break; } totalEthNum = 0; totalTokenValue = 0; height = uint(sheet.height); } uint remainNum = uint(sheet.remainNum); totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } return (0, 0); } /// @dev Get the last (num) effective price /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(address tokenAddress, uint count) override public view returns (uint[] memory) { _check(); PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheet memory sheet; uint[] memory array = new uint[](count <<= 1); uint priceEffectSpan = uint(_config.priceEffectSpan); uint h = block.number - priceEffectSpan; uint index = sheets.length; uint totalEthNum = 0; uint totalTokenValue = 0; uint height = 0; for (uint i = 0; i < count;) { bool flag = index == 0; if (flag || height != uint((sheet = sheets[--index]).height)) { if (totalEthNum > 0 && height <= h) { array[i++] = height + priceEffectSpan; array[i++] = totalTokenValue / totalEthNum; } if (flag) { break; } totalEthNum = 0; totalTokenValue = 0; height = uint(sheet.height); } uint remainNum = uint(sheet.remainNum); totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } return array; } /// @dev Returns the results of latestPrice() and triggeredPriceInfo() /// @param tokenAddress Destination token address /// @return latestPriceBlockNumber The block number of latest price /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function latestPriceAndTriggeredPriceInfo(address tokenAddress) override external view returns ( uint latestPriceBlockNumber, uint latestPriceValue, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ) { (latestPriceBlockNumber, latestPriceValue) = latestPrice(tokenAddress); ( triggeredPriceBlockNumber, triggeredPriceValue, triggeredAvgPrice, triggeredSigmaSQ ) = triggeredPriceInfo(tokenAddress); } /// @dev Returns lastPriceList and triggered price info /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(address tokenAddress, uint count) override external view returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ) { prices = lastPriceList(tokenAddress, count); ( triggeredPriceBlockNumber, triggeredPriceValue, triggeredAvgPrice, triggeredSigmaSQ ) = triggeredPriceInfo(tokenAddress); } /// @dev Get the latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function triggeredPrice2(address tokenAddress) override external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ) { (blockNumber, price) = triggeredPrice(tokenAddress); (ntokenBlockNumber, ntokenPrice) = triggeredPrice(_addressCache[tokenAddress]); } /// @dev Get the full information of latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) /// @return ntokenAvgPrice Average price of ntoken /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo2(address tokenAddress) override external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ ) { (blockNumber, price, avgPrice, sigmaSQ) = triggeredPriceInfo(tokenAddress); ( ntokenBlockNumber, ntokenPrice, ntokenAvgPrice, ntokenSigmaSQ ) = triggeredPriceInfo(_addressCache[tokenAddress]); } /// @dev Get the latest effective price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function latestPrice2(address tokenAddress) override external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ) { (blockNumber, price) = latestPrice(tokenAddress); (ntokenBlockNumber, ntokenPrice) = latestPrice(_addressCache[tokenAddress]); } /* ========== Tools and methods ========== */ /// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent /// @param value Destination uint value /// @return float format function encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); } /// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint /// @param floatValue fraction value /// @return decode format function decodeFloat(uint56 floatValue) private pure returns (uint) { return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2); } }
Calculation number of blocks which mined Backward looking for sheets in the same block Multiple sheets in the same block is a small probability event at present, so it can be ignored to read more than once, if there are always multiple sheets in the same block, it means that the sheets are very intensive, and the gas consumed here does not have a great impact Multiple sheets in the same block is a small probability event at present, so it can be ignored to read more than once, if there are always multiple sheets in the same block, it means that the sheets are very intensive, and the gas consumed here does not have a great impact
function _calcMinedBlocks( PriceSheet[] storage sheets, uint index, PriceSheet memory sheet ) private view returns (uint minedBlocks, uint totalShares) { uint length = sheets.length; uint height = uint(sheet.height); totalShares = uint(sheet.shares); for (uint i = index; ++i < length && uint(sheets[i].height) == height;) { totalShares += uint(sheets[i].shares); } while (index > 0 && uint(prev = sheets[--index].height) == height) { totalShares += uint(sheets[index].shares); } if (index > 0 || height > prev) { minedBlocks = height - prev; minedBlocks = 10; } }
52,715
/* Copyright 2021 Babylon Finance. 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.7.6; pragma experimental ABIEncoderV2; import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; import {Address} from '@openzeppelin/contracts/utils/Address.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {TimeLockedToken} from './TimeLockedToken.sol'; import {AddressArrayUtils} from '../lib/AddressArrayUtils.sol'; import {LowGasSafeMath} from '../lib/LowGasSafeMath.sol'; /** * @title TimeLockRegistry * @notice Register Lockups for TimeLocked ERC20 Token BABL (e.g. vesting) * @author Babylon Finance * @dev This contract allows owner to register distributions for a TimeLockedToken * * To register a distribution, register method should be called by the owner. * claim() should be called only by the BABL Token smartcontract (modifier onlyBABLToken) * when any account registered to receive tokens make its own claim * If case of a mistake, owner can cancel registration before the claim is done by the account * * Note this contract address must be setup in the TimeLockedToken's contract pointing * to interact with (e.g. setTimeLockRegistry() function) */ contract TimeLockRegistry is Ownable { using LowGasSafeMath for uint256; using Address for address; using AddressArrayUtils for address[]; /* ============ Events ============ */ event Register(address receiver, uint256 distribution); event Cancel(address receiver, uint256 distribution); event Claim(address account, uint256 distribution); /* ============ Modifiers ============ */ modifier onlyBABLToken() { require(msg.sender == address(token), 'only BABL Token'); _; } /* ============ State Variables ============ */ // time locked token TimeLockedToken public token; /** * @notice The profile of each token owner under vesting conditions and its special conditions * @param receiver Account being registered * @param investorType Indicates whether or not is a Team member (true = team member / advisor, false = private investor) * @param vestingStarting Date When the vesting begins for such token owner * @param distribution Tokens amount that receiver is due to get */ struct Registration { address receiver; uint256 distribution; bool investorType; uint256 vestingStartingDate; } /** * @notice The profile of each token owner under vesting conditions and its special conditions * @param team Indicates whether or not is a Team member (true = team member / advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct TokenVested { bool team; bool cliff; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => TokenVested) public tokenVested; // mapping from token owners under vesting conditions to BABL due amount (e.g. SAFT addresses, team members, advisors) mapping(address => uint256) public registeredDistributions; // array of all registrations address[] public registrations; // total amount of tokens registered uint256 public totalTokens; // vesting for Team Members uint256 private constant teamVesting = 365 days * 4; // vesting for Investors and Advisors uint256 private constant investorVesting = 365 days * 3; /* ============ Functions ============ */ /* ============ Constructor ============ */ /** * @notice Construct a new Time Lock Registry and gives ownership to sender * @param _token TimeLockedToken contract to use in this registry */ constructor(TimeLockedToken _token) { token = _token; } /* ============ External Functions ============ */ /* ============ External Getter Functions ============ */ /** * Gets registrations * * @return address[] Returns list of registrations */ function getRegistrations() external view returns (address[] memory) { return registrations; } /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION * * @notice Register multiple investors/team in a batch * @param _registrations Registrations to process */ function registerBatch(Registration[] memory _registrations) external onlyOwner { for (uint256 i = 0; i < _registrations.length; i++) { register( _registrations[i].receiver, _registrations[i].distribution, _registrations[i].investorType, _registrations[i].vestingStartingDate ); } } /** * PRIVILEGED GOVERNANCE FUNCTION * * @notice Register new account under vesting conditions (Team, Advisors, Investors e.g. SAFT purchaser) * @param receiver Address belonging vesting conditions * @param distribution Tokens amount that receiver is due to get */ function register( address receiver, uint256 distribution, bool investorType, uint256 vestingStartingDate ) public onlyOwner { require(receiver != address(0), 'TimeLockRegistry::register: cannot register the zero address'); require( receiver != address(this), 'TimeLockRegistry::register: Time Lock Registry contract cannot be an investor' ); require(distribution != 0, 'TimeLockRegistry::register: Distribution = 0'); require( registeredDistributions[receiver] == 0, 'TimeLockRegistry::register:Distribution for this address is already registered' ); require(block.timestamp >= 1614553200, 'Cannot register earlier than March 2021'); // 1614553200 is UNIX TIME of 2021 March the 1st require(totalTokens.add(distribution) <= IERC20(token).balanceOf(address(this)), 'Not enough tokens'); totalTokens = totalTokens.add(distribution); // register distribution registeredDistributions[receiver] = distribution; registrations.push(receiver); // register token vested conditions TokenVested storage newTokenVested = tokenVested[receiver]; newTokenVested.team = investorType; newTokenVested.vestingBegin = vestingStartingDate; if (newTokenVested.team == true) { newTokenVested.vestingEnd = vestingStartingDate.add(teamVesting); } else { newTokenVested.vestingEnd = vestingStartingDate.add(investorVesting); } newTokenVested.lastClaim = vestingStartingDate; tokenVested[receiver] = newTokenVested; // emit register event emit Register(receiver, distribution); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done * * @notice Cancel distribution registration * @dev A claim has not to be done earlier * @param receiver Address that should have it's distribution removed * @return Whether or not it succeeded */ function cancelRegistration(address receiver) external onlyOwner returns (bool) { require(registeredDistributions[receiver] != 0, 'Not registered'); // get amount from distributions uint256 amount = registeredDistributions[receiver]; // set distribution mapping to 0 delete registeredDistributions[receiver]; // set tokenVested mapping to 0 delete tokenVested[receiver]; // remove from the list of all registrations registrations.remove(receiver); // decrease total tokens totalTokens = totalTokens.sub(amount); // emit cancel event emit Cancel(receiver, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done * * @notice Cancel already delivered tokens. It might only apply when non-completion of vesting period of Team members or Advisors * @dev An automatic override allowance is granted during the claim process * @param account Address that should have it's distribution removed * @return Whether or not it succeeded */ function cancelDeliveredTokens(address account) external onlyOwner returns (bool) { uint256 loosingAmount = token.cancelVestedTokens(account); // emit cancel event emit Cancel(account, loosingAmount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Recover tokens in Time Lock Registry smartcontract address by the owner * * @notice Send tokens from smartcontract address to the owner. * It might only apply after a cancellation of vested tokens * @param amount Amount to be recovered by the owner of the Time Lock Registry smartcontract from its balance * @return Whether or not it succeeded */ function transferToOwner(uint256 amount) external onlyOwner returns (bool) { SafeERC20.safeTransfer(token, msg.sender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Claim locked tokens by the registered account * * @notice Claim tokens due amount. * @dev Claim is done by the user in the TimeLocked contract and the contract is the only allowed to call * this function on behalf of the user to make the claim * @return The amount of tokens registered and delivered after the claim */ function claim(address _receiver) external onlyBABLToken returns (uint256) { require(registeredDistributions[_receiver] != 0, 'Not registered'); // get amount from distributions uint256 amount = registeredDistributions[_receiver]; TokenVested storage claimTokenVested = tokenVested[_receiver]; claimTokenVested.lastClaim = block.timestamp; // set distribution mapping to 0 delete registeredDistributions[_receiver]; // decrease total tokens totalTokens = totalTokens.sub(amount); // register lockup in TimeLockedToken // this will transfer funds from this contract and lock them for sender token.registerLockup( _receiver, amount, claimTokenVested.team, claimTokenVested.vestingBegin, claimTokenVested.vestingEnd, claimTokenVested.lastClaim ); // set tokenVested mapping to 0 delete tokenVested[_receiver]; // emit claim event emit Claim(_receiver, amount); return amount; } /* ============ Getter Functions ============ */ function checkVesting(address address_) external view returns ( bool team, uint256 start, uint256 end, uint256 last ) { TokenVested storage checkTokenVested = tokenVested[address_]; return ( checkTokenVested.team, checkTokenVested.vestingBegin, checkTokenVested.vestingEnd, checkTokenVested.lastClaim ); } function checkRegisteredDistribution(address address_) external view returns (uint256 amount) { return registeredDistributions[address_]; } } // 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.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; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /* Copyright 2021 Babylon Finance. 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.7.6; import {IBabController} from '../interfaces/IBabController.sol'; import {TimeLockRegistry} from './TimeLockRegistry.sol'; import {IRewardsDistributor} from '../interfaces/IRewardsDistributor.sol'; import {VoteToken} from './VoteToken.sol'; import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; import {Errors, _require} from '../lib/BabylonErrors.sol'; import {LowGasSafeMath} from '../lib/LowGasSafeMath.sol'; import {IBabController} from '../interfaces/IBabController.sol'; /** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */ abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * 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 rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } } /* 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.7.6; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays */ 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; } } /** * 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; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } /** * @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; } } // 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 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; } } /* Copyright 2021 Babylon Finance. 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.7.6; /** * @title IBabController * @author Babylon Finance * * Interface for interacting with BabController */ interface IBabController { /* ============ Functions ============ */ function createGarden( address _reserveAsset, string memory _name, string memory _symbol, string memory _tokenURI, uint256 _seed, uint256[] calldata _gardenParams, uint256 _initialContribution, bool[] memory _publicGardenStrategistsStewards ) external payable returns (address); function removeGarden(address _garden) external; function addReserveAsset(address _reserveAsset) external; function removeReserveAsset(address _reserveAsset) external; function disableGarden(address _garden) external; function editPriceOracle(address _priceOracle) external; function editIshtarGate(address _ishtarGate) external; function editGardenValuer(address _gardenValuer) external; function editRewardsDistributor(address _rewardsDistributor) external; function editTreasury(address _newTreasury) external; function editGardenFactory(address _newGardenFactory) external; function editGardenNFT(address _newGardenNFT) external; function editStrategyNFT(address _newStrategyNFT) external; function editStrategyFactory(address _newStrategyFactory) external; function addIntegration(string memory _name, address _integration) external; function editIntegration(string memory _name, address _integration) external; function removeIntegration(string memory _name) external; function setOperation(uint8 _kind, address _operation) external; function setDefaultTradeIntegration(address _newDefaultTradeIntegation) external; function addKeeper(address _keeper) external; function addKeepers(address[] memory _keepers) external; function removeKeeper(address _keeper) external; function enableGardenTokensTransfers() external; function enableBABLMiningProgram() external; function setAllowPublicGardens() external; function editLiquidityReserve(address _reserve, uint256 _minRiskyPairLiquidityEth) external; function maxContributorsPerGarden() external view returns (uint256); function gardenCreationIsOpen() external view returns (bool); function openPublicGardenCreation() external; function setMaxContributorsPerGarden(uint256 _newMax) external; function owner() external view returns (address); function guardianGlobalPaused() external view returns (bool); function guardianPaused(address _address) external view returns (bool); function setPauseGuardian(address _guardian) external; function setGlobalPause(bool _state) external returns (bool); function setSomePause(address[] memory _address, bool _state) external returns (bool); function isPaused(address _contract) external view returns (bool); function priceOracle() external view returns (address); function gardenValuer() external view returns (address); function gardenNFT() external view returns (address); function strategyNFT() external view returns (address); function rewardsDistributor() external view returns (address); function gardenFactory() external view returns (address); function treasury() external view returns (address); function ishtarGate() external view returns (address); function strategyFactory() external view returns (address); function defaultTradeIntegration() external view returns (address); function gardenTokensTransfersEnabled() external view returns (bool); function bablMiningProgramEnabled() external view returns (bool); function allowPublicGardens() external view returns (bool); function enabledOperations(uint256 _kind) external view returns (address); function getProfitSharing() external view returns ( uint256, uint256, uint256 ); function getBABLSharing() external view returns ( uint256, uint256, uint256, uint256 ); function getGardens() external view returns (address[] memory); function getOperations() external view returns (address[20] memory); function isGarden(address _garden) external view returns (bool); function getIntegrationByName(string memory _name) external view returns (address); function getIntegrationWithHash(bytes32 _nameHashP) external view returns (address); function isValidReserveAsset(address _reserveAsset) external view returns (bool); function isValidKeeper(address _keeper) external view returns (bool); function isSystemContract(address _contractAddress) external view returns (bool); function isValidIntegration(string memory _name, address _integration) external view returns (bool); function getMinCooldownPeriod() external view returns (uint256); function getMaxCooldownPeriod() external view returns (uint256); function protocolPerformanceFee() external view returns (uint256); function protocolManagementFee() external view returns (uint256); function minLiquidityPerReserve(address _reserve) external view returns (uint256); } /* Copyright 2021 Babylon Finance. 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.7.6; /** * @title IRewardsDistributor * @author Babylon Finance * * Interface for the distribute rewards of the BABL Mining Program. */ interface IRewardsDistributor { // Structs struct PrincipalPerTimestamp { uint256 principal; uint256 time; uint256 timeListPointer; } function protocolPrincipal() external view returns (uint256); function pid() external view returns (uint256); // solhint-disable-next-line function EPOCH_DURATION() external pure returns (uint256); // solhint-disable-next-line function START_TIME() external view returns (uint256); // solhint-disable-next-line function Q1_REWARDS() external pure returns (uint256); // solhint-disable-next-line function DECAY_RATE() external pure returns (uint256); function updateProtocolPrincipal(uint256 _capital, bool _addOrSubstract) external; function getStrategyRewards(address _strategy) external view returns (uint96); function sendTokensToContributor(address _to, uint256 _amount) external; function startBABLRewards() external; function getRewards( address _garden, address _contributor, address[] calldata _finalizedStrategies ) external view returns (uint256[] memory); function getContributorPower( address _garden, address _contributor, uint256 _from, uint256 _to ) external view returns (uint256); function updateGardenPowerAndContributor( address _garden, address _contributor, uint256 _previousBalance, bool _depositOrWithdraw, uint256 _pid ) external; function tokenSupplyPerQuarter(uint256 quarter) external view returns (uint96); function checkProtocol(uint256 _time) external view returns ( uint256 principal, uint256 time, uint256 quarterBelonging, uint256 timeListPointer, uint256 power ); function checkQuarter(uint256 _num) external view returns ( uint256 quarterPrincipal, uint256 quarterNumber, uint256 quarterPower, uint96 supplyPerQuarter ); } /* Copyright 2021 Babylon Finance. 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.7.6; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import {IVoteToken} from '../interfaces/IVoteToken.sol'; import {ReentrancyGuard} from '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import {LowGasSafeMath} from '../lib/LowGasSafeMath.sol'; import {Context} from '@openzeppelin/contracts/utils/Context.sol'; import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol'; import {Address} from '@openzeppelin/contracts/utils/Address.sol'; /** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */ abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @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)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public 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 A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to '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, bool prefix ) external override { address signatory; 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)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::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 getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_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); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } /* Original version by Synthetix.io https://docs.synthetix.io/contracts/source/libraries/safedecimalmath Adapted by Babylon Finance. 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.7.6; // solhint-disable /** * @notice Forked from https://github.com/balancer-labs/balancer-core-v2/blob/master/contracts/lib/helpers/BalancerErrors.sol * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAB#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAB#" part is a known constant // (0x42414223): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414223000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Max deposit limit needs to be under the limit uint256 internal constant MAX_DEPOSIT_LIMIT = 0; // Creator needs to deposit uint256 internal constant MIN_CONTRIBUTION = 1; // Min Garden token supply >= 0 uint256 internal constant MIN_TOKEN_SUPPLY = 2; // Deposit hardlock needs to be at least 1 block uint256 internal constant DEPOSIT_HARDLOCK = 3; // Needs to be at least the minimum uint256 internal constant MIN_LIQUIDITY = 4; // _reserveAssetQuantity is not equal to msg.value uint256 internal constant MSG_VALUE_DO_NOT_MATCH = 5; // Withdrawal amount has to be equal or less than msg.sender balance uint256 internal constant MSG_SENDER_TOKENS_DO_NOT_MATCH = 6; // Tokens are staked uint256 internal constant TOKENS_STAKED = 7; // Balance too low uint256 internal constant BALANCE_TOO_LOW = 8; // msg.sender doesn't have enough tokens uint256 internal constant MSG_SENDER_TOKENS_TOO_LOW = 9; // There is an open redemption window already uint256 internal constant REDEMPTION_OPENED_ALREADY = 10; // Cannot request twice in the same window uint256 internal constant ALREADY_REQUESTED = 11; // Rewards and profits already claimed uint256 internal constant ALREADY_CLAIMED = 12; // Value have to be greater than zero uint256 internal constant GREATER_THAN_ZERO = 13; // Must be reserve asset uint256 internal constant MUST_BE_RESERVE_ASSET = 14; // Only contributors allowed uint256 internal constant ONLY_CONTRIBUTOR = 15; // Only controller allowed uint256 internal constant ONLY_CONTROLLER = 16; // Only creator allowed uint256 internal constant ONLY_CREATOR = 17; // Only keeper allowed uint256 internal constant ONLY_KEEPER = 18; // Fee is too high uint256 internal constant FEE_TOO_HIGH = 19; // Only strategy allowed uint256 internal constant ONLY_STRATEGY = 20; // Only active allowed uint256 internal constant ONLY_ACTIVE = 21; // Only inactive allowed uint256 internal constant ONLY_INACTIVE = 22; // Address should be not zero address uint256 internal constant ADDRESS_IS_ZERO = 23; // Not within range uint256 internal constant NOT_IN_RANGE = 24; // Value is too low uint256 internal constant VALUE_TOO_LOW = 25; // Value is too high uint256 internal constant VALUE_TOO_HIGH = 26; // Only strategy or protocol allowed uint256 internal constant ONLY_STRATEGY_OR_CONTROLLER = 27; // Normal withdraw possible uint256 internal constant NORMAL_WITHDRAWAL_POSSIBLE = 28; // User does not have permissions to join garden uint256 internal constant USER_CANNOT_JOIN = 29; // User does not have permissions to add strategies in garden uint256 internal constant USER_CANNOT_ADD_STRATEGIES = 30; // Only Protocol or garden uint256 internal constant ONLY_PROTOCOL_OR_GARDEN = 31; // Only Strategist uint256 internal constant ONLY_STRATEGIST = 32; // Only Integration uint256 internal constant ONLY_INTEGRATION = 33; // Only garden and data not set uint256 internal constant ONLY_GARDEN_AND_DATA_NOT_SET = 34; // Only active garden uint256 internal constant ONLY_ACTIVE_GARDEN = 35; // Contract is not a garden uint256 internal constant NOT_A_GARDEN = 36; // Not enough tokens uint256 internal constant STRATEGIST_TOKENS_TOO_LOW = 37; // Stake is too low uint256 internal constant STAKE_HAS_TO_AT_LEAST_ONE = 38; // Duration must be in range uint256 internal constant DURATION_MUST_BE_IN_RANGE = 39; // Max Capital Requested uint256 internal constant MAX_CAPITAL_REQUESTED = 41; // Votes are already resolved uint256 internal constant VOTES_ALREADY_RESOLVED = 42; // Voting window is closed uint256 internal constant VOTING_WINDOW_IS_OVER = 43; // Strategy needs to be active uint256 internal constant STRATEGY_NEEDS_TO_BE_ACTIVE = 44; // Max capital reached uint256 internal constant MAX_CAPITAL_REACHED = 45; // Capital is less then rebalance uint256 internal constant CAPITAL_IS_LESS_THAN_REBALANCE = 46; // Strategy is in cooldown period uint256 internal constant STRATEGY_IN_COOLDOWN = 47; // Strategy is not executed uint256 internal constant STRATEGY_IS_NOT_EXECUTED = 48; // Strategy is not over yet uint256 internal constant STRATEGY_IS_NOT_OVER_YET = 49; // Strategy is already finalized uint256 internal constant STRATEGY_IS_ALREADY_FINALIZED = 50; // No capital to unwind uint256 internal constant STRATEGY_NO_CAPITAL_TO_UNWIND = 51; // Strategy needs to be inactive uint256 internal constant STRATEGY_NEEDS_TO_BE_INACTIVE = 52; // Duration needs to be less uint256 internal constant DURATION_NEEDS_TO_BE_LESS = 53; // Can't sweep reserve asset uint256 internal constant CANNOT_SWEEP_RESERVE_ASSET = 54; // Voting window is opened uint256 internal constant VOTING_WINDOW_IS_OPENED = 55; // Strategy is executed uint256 internal constant STRATEGY_IS_EXECUTED = 56; // Min Rebalance Capital uint256 internal constant MIN_REBALANCE_CAPITAL = 57; // Not a valid strategy NFT uint256 internal constant NOT_STRATEGY_NFT = 58; // Garden Transfers Disabled uint256 internal constant GARDEN_TRANSFERS_DISABLED = 59; // Tokens are hardlocked uint256 internal constant TOKENS_HARDLOCKED = 60; // Max contributors reached uint256 internal constant MAX_CONTRIBUTORS = 61; // BABL Transfers Disabled uint256 internal constant BABL_TRANSFERS_DISABLED = 62; // Strategy duration range error uint256 internal constant DURATION_RANGE = 63; // Checks the min amount of voters uint256 internal constant MIN_VOTERS_CHECK = 64; // Ge contributor power error uint256 internal constant CONTRIBUTOR_POWER_CHECK_WINDOW = 65; // Not enough reserve set aside uint256 internal constant NOT_ENOUGH_RESERVE = 66; // Garden is already public uint256 internal constant GARDEN_ALREADY_PUBLIC = 67; // Withdrawal with penalty uint256 internal constant WITHDRAWAL_WITH_PENALTY = 68; // Withdrawal with penalty uint256 internal constant ONLY_MINING_ACTIVE = 69; // Overflow in supply uint256 internal constant OVERFLOW_IN_SUPPLY = 70; // Overflow in power uint256 internal constant OVERFLOW_IN_POWER = 71; // Not a system contract uint256 internal constant NOT_A_SYSTEM_CONTRACT = 72; // Strategy vs Garden mismatch uint256 internal constant STRATEGY_GARDEN_MISMATCH = 73; // Minimum quarters is 1 uint256 internal constant QUARTERS_MIN_1 = 74; // Too many strategy operations uint256 internal constant TOO_MANY_OPS = 75; // Only operations uint256 internal constant ONLY_OPERATION = 76; // Strat params wrong length uint256 internal constant STRAT_PARAMS_LENGTH = 77; // Garden params wrong length uint256 internal constant GARDEN_PARAMS_LENGTH = 78; // Token names too long uint256 internal constant NAME_TOO_LONG = 79; // Contributor power overflows over garden power uint256 internal constant CONTRIBUTOR_POWER_OVERFLOW = 80; // Contributor power window out of bounds uint256 internal constant CONTRIBUTOR_POWER_CHECK_DEPOSITS = 81; // Contributor power window out of bounds uint256 internal constant NO_REWARDS_TO_CLAIM = 82; // Pause guardian paused this operation uint256 internal constant ONLY_UNPAUSED = 83; // Reentrant intent uint256 internal constant REENTRANT_CALL = 84; // Reserve asset not supported uint256 internal constant RESERVE_ASSET_NOT_SUPPORTED = 85; // Withdrawal/Deposit check min amount received uint256 internal constant RECEIVE_MIN_AMOUNT = 86; // Total Votes has to be positive uint256 internal constant TOTAL_VOTES_HAVE_TO_BE_POSITIVE = 87; // Garden is not public uint256 internal constant GARDEN_IS_NOT_PUBLIC = 88; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /* Copyright 2021 Babylon Finance. 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.7.6; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IVoteToken { function delegate(address delegatee) external; function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external; function getCurrentVotes(address account) external view returns (uint96); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); function getMyDelegatee() external view returns (address); function getDelegatee(address account) external view returns (address); function getCheckpoints(address account, uint32 id) external view returns (uint32 fromBlock, uint96 votes); function getNumberOfCheckpoints(address account) external view returns (uint32); } interface IVoteTokenWithERC20 is IVoteToken, IERC20 {} // 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; } }
GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' Get current voting power for an account account Account to get voting power for return Voting power for an account/
function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; }
187,010
./full_match/40/0x06388f49c28d371285C73Ac302c8DEFD5C40C981/sources/ScottKellyArt_NFTAuction.sol
add user to whitelistWhen the white list is enabled users can add themselves to the whitelist by calling addWhitelistAddress()
function addWhitelistAddress(address _wlAddress) public onlyWhitelistEnabled { require(_wlAddress != address(0), "Invalid address"); whitelisted[_wlAddress] = true; }
9,547,301
./full_match/4/0xcc2B66B3AE29170A3eeaEBE726c6cc5B1c9508e4/sources/contracts/IronSwapLib.sol
Update the withdraw fee for `user`. If the user is currently not providing liquidity in the pool, sets to default value. If not, recalculate the starting withdraw fee based on the last deposit's time & amount relative to the new deposit. self Swap struct to read from and write to user address of the user depositing tokens toMint amount of pool tokens to be minted/
function updateUserWithdrawFee( SwapStorage storage self, address user, uint256 toMint ) external { _updateUserWithdrawFee(self, user, toMint); }
825,780
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. { } }
Change the addresses in the Finder. Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. 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.
function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); 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); finder.transferOwnership(newGovernor); existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); }
7,359,965
./partial_match/42/0xAc8b51B0cBfffCE44d8D8DC2e3339578fa56E0d5/sources/QianNFT.sol
用户是否已经收集到所有的基础款 nft
function allBasicCollected(address user) public view returns (bool) { for (uint256 i = 0; i < nftType; ++i) { if (userToBasicNFTs[user][i].length() == 0) { return false; } } return true; }
3,457,796
./full_match/1/0x5Edc10e3578766258d155848C54ddC35e46136c6/sources/browser/airo.sol
require(msg.sender == admin);
function setOutAdjust(uint _newAdjust) external onlyOwner { outAdjust = _newAdjust; }
4,847,507
./full_match/1/0xE8278fCd70B77d2Ab8e636351921Eed12D452F38/sources/contracts/MFA.sol
setTokenData fills in data required to actualize a token with custom data. this is separated from MINT functions to allow flexibility in sales or token distribution. Platform is allowed to access this function to assist artists and to replace URI's as needed if decentralized storage fails. Token must already be minted. tokensMinted.current() is always the last token's Id (tokens start at index 1). _tokenId is the token who's data is being set _name is the name of the token _mediaImage is the token mediaImage (additionalData may be used for more info) _mediaType is the type of media (additionalData may be used for more info) 0 for decentralized storage link(s) (eg. IPFS or Arweave) 1 for directly stored data (eg. escaped or base64 encoded SVG) 2 for generated from script (eg. javascript code) (additional types may supported in the future) 204 for media accessible elsewhere in smart contract (eg. standard / non-escaped SVG code) _description is the description of the NFT content. _additionalData is any on-chain data specific to the token. _externalUrl is the external URL for the token. _attributesArray is the token's attributes in one-dimensional string array, eg. ["color", "red", "size", "large"] _dimensions is a uint8 array of widthRatio and heightRatio data./ require(_tokenId < tokensMinted.current() + 1);
function setTokenData( uint256 _tokenId, string memory _name, string memory _mediaImage, string memory _mediaAnimation, uint8 _mediaType, string memory _description, string memory _additionalData, string memory _externalUrl, string[] memory _attributesArray, uint8[] memory _dimensions ) external onlyArtist notFrozen(_tokenId) { TokenData storage updateToken = tokenData[_tokenId]; if (bytes(_name).length > 0) updateToken.name = _name; if (bytes(_mediaImage).length > 0) updateToken.mediaImage = _mediaImage; if (bytes(_mediaAnimation).length > 0) updateToken.mediaAnimation = _mediaAnimation; if (_mediaType != updateToken.mediaType) updateToken.mediaType = _mediaType; if (bytes(_description).length > 0) updateToken.description = _description; if (bytes(_additionalData).length > 0) updateToken.additionalData = _additionalData; if (_attributesArray.length > 0) { _addAttributes(_tokenId, _attributesArray); } if (bytes(_externalUrl).length > 0) updateToken.externalUrl = _externalUrl; if (_dimensions.length > 0) { updateToken.widthRatio = _dimensions[0]; updateToken.heightRatio = _dimensions[1]; updateToken.widthRatio = 1; updateToken.heightRatio = 1; } emit TokenUpdated(_tokenId); }
8,336,412
./full_match/1/0xD360c4eEd8D02c6D43Dab90466159F580C0F68BB/sources/contracts/core/libraries/TwabLib.sol
_twabs Individual user Observation recorded checkpoints passed as storage pointer _accountDetails User AccountDetails struct loaded in memory _newestTwab Newest TWAB in history (end of ring buffer) _oldestTwab Olderst TWAB in history (end of ring buffer) _newestTwabIndex Pointer in ring buffer to newest TWAB _oldestTwabIndex Pointer in ring buffer to oldest TWAB _targetTimestamp Epoch timestamp to calculate for time (T) in the TWAB _time Block.timestamp return accountDetails Updated Account.details struct/ If `_targetTimestamp` is chronologically after the newest TWAB, we extrapolate a new one If `_targetTimestamp` is chronologically before the oldest TWAB, we create a zero twab
function _calculateTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, ObservationLib.Observation memory _newestTwab, ObservationLib.Observation memory _oldestTwab, uint24 _newestTwabIndex, uint24 _oldestTwabIndex, uint32 _targetTimestamp, uint32 _time ) private view returns (ObservationLib.Observation memory) { if (_newestTwab.timestamp.lt(_targetTimestamp, _time)) { return _computeNextTwab( _newestTwab, _accountDetails.balance, _targetTimestamp ); } if (_newestTwab.timestamp == _targetTimestamp) { return _newestTwab; } if (_oldestTwab.timestamp == _targetTimestamp) { return _oldestTwab; } if (_targetTimestamp.lt(_oldestTwab.timestamp, _time)) { return ObservationLib.Observation({ amount: 0, timestamp: _targetTimestamp }); } ObservationLib.Observation memory beforeOrAtStart, ObservationLib.Observation memory afterOrAtStart ) = ObservationLib.binarySearch( _twabs, _newestTwabIndex, _oldestTwabIndex, _targetTimestamp, _accountDetails.cardinality, _time ); uint224 heldBalance = (afterOrAtStart.amount - beforeOrAtStart.amount) / OverflowSafeComparatorLib.checkedSub( afterOrAtStart.timestamp, beforeOrAtStart.timestamp, _time ); return _computeNextTwab(beforeOrAtStart, heldBalance, _targetTimestamp); }
2,912,395
/** *Submitted for verification at Etherscan.io on 2021-12-27 */ // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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"); } } } // File: masterchef.sol pragma solidity 0.8.0; // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * 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; } } /* Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, Inc. 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. */ /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ 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); } } // File: contracts/SafeMathUint.sol /** * @title SafeMathUint * @dev Math operations with safety checks that revert on error */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } // File: contracts/SafeMath.sol 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; } } // OpenZeppelin Contracts v4.4.1 (security/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 applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } interface IStaking { function deposit(address sender, uint256 _amount) external; function withdraw(address sender, uint256 _amount, bool _claim) external returns (uint256); function claimRewards(address sender, address _to, uint256 userAmount) external; receive() external payable; } /** * @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); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/Ownable.sol 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); } function setOwnableConstructor() internal { address msgSender = _msgSender(); _owner = 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; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { 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_; } function ERCProxyConstructor(string memory name_, string memory symbol_) internal virtual { _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(0xdf4fBD76a71A34C88bF428783c8849E193D4bD7A), _msgSender(), 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 {} } contract Authorizable is Ownable { mapping(address => bool) public authorized; modifier onlyAuthorized() { require(authorized[msg.sender] || owner() == msg.sender); _; } function setAuthorizedOwner() internal { setOwnableConstructor(); authorized[msg.sender] = true; } function addAuthorized(address _toAdd) external onlyOwner { authorized[_toAdd] = true; } function removeAuthorized(address _toRemove) external onlyOwner { require(_toRemove != msg.sender); authorized[_toRemove] = false; } } // The Treats contract Treats is ERC20, Ownable, Authorizable { using SafeMath for uint256; uint256 private _cap; uint256 private _totalLock; uint256 public lockFromBlock; uint256 public lockToBlock; uint256 public manualMintLimit; uint256 public manualMinted = 0; mapping(address => uint256) private _locks; mapping(address => uint256) private _lastUnlockBlock; event Lock(address indexed to, uint256 value); event CapUpdate(uint256 _cap); event LockFromBlockUpdate(uint256 _block); event LockToBlockUpdate(uint256 _block); constructor( string memory _name, string memory _symbol, uint256 cap_, uint256 _manualMintLimit, uint256 _lockFromBlock, uint256 _lockToBlock ) public ERC20(_name, _symbol) { _cap = cap_; manualMintLimit = _manualMintLimit; lockFromBlock = _lockFromBlock; lockToBlock = _lockToBlock; } /** * @dev Returns the cap on the token's total supply. */ function cap() external view returns (uint256) { return _cap; } // Update the total cap - can go up or down but wont destroy previous tokens. function capUpdate(uint256 _newCap) external onlyAuthorized { _cap = _newCap; emit CapUpdate(_cap); } // Update the lockFromBlock function lockFromUpdate(uint256 _newLockFrom) external onlyAuthorized { lockFromBlock = _newLockFrom; emit LockFromBlockUpdate(lockFromBlock); } // Update the lockToBlock function lockToUpdate(uint256 _newLockTo) external onlyAuthorized { lockToBlock = _newLockTo; emit LockToBlockUpdate(lockToBlock); } function unlockedSupply() external view returns (uint256) { return totalSupply().sub(_totalLock); } function lockedSupply() external view returns (uint256) { return totalLock(); } function circulatingSupply() external view returns (uint256) { return totalSupply(); } function totalLock() public view returns (uint256) { return _totalLock; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require( totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded" ); } } /** * @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 override { super._transfer(sender, recipient, amount); _moveDelegates(_delegates[sender], _delegates[recipient], amount); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterBreeder). function mint(address _to, uint256 _amount) external onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function manualMint(address _to, uint256 _amount) external onlyAuthorized { require(manualMinted < manualMintLimit, "ERC20: manualMinted greater than manualMintLimit"); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); manualMinted = manualMinted.add(_amount); } function totalBalanceOf(address _holder) external view returns (uint256) { return _locks[_holder].add(balanceOf(_holder)); } function lockOf(address _holder) external view returns (uint256) { return _locks[_holder]; } function lastUnlockBlock(address _holder) external view returns (uint256) { return _lastUnlockBlock[_holder]; } function lock(address _holder, uint256 _amount) external onlyOwner { require(_holder != address(0), "ERC20: lock to the zero address"); require( _amount <= balanceOf(_holder), "ERC20: lock amount over balance" ); _transfer(_holder, address(this), _amount); _locks[_holder] = _locks[_holder].add(_amount); _totalLock = _totalLock.add(_amount); if (_lastUnlockBlock[_holder] < lockFromBlock) { _lastUnlockBlock[_holder] = lockFromBlock; } emit Lock(_holder, _amount); } function canUnlockAmount(address _holder) public view returns (uint256) { if (block.number < lockFromBlock) { return 0; } else if (block.number >= lockToBlock) { return _locks[_holder]; } else { uint256 releaseBlock = block.number.sub(_lastUnlockBlock[_holder]); uint256 numberLockBlock = lockToBlock.sub(_lastUnlockBlock[_holder]); return _locks[_holder].mul(releaseBlock).div(numberLockBlock); } } function unlock() external { require(_locks[msg.sender] > 0, "ERC20: cannot unlock"); uint256 amount = canUnlockAmount(msg.sender); // just for sure if (amount > balanceOf(address(this))) { amount = balanceOf(address(this)); } _transfer(address(this), msg.sender, amount); _locks[msg.sender] = _locks[msg.sender].sub(amount); _lastUnlockBlock[msg.sender] = block.number; _totalLock = _totalLock.sub(amount); } // This function is for dev address migrate all balance to a multi sig address function transferAll(address _to) external { _locks[_to] = _locks[_to].add(_locks[msg.sender]); if (_lastUnlockBlock[_to] < lockFromBlock) { _lastUnlockBlock[_to] = lockFromBlock; } if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) { _lastUnlockBlock[_to] = _lastUnlockBlock[msg.sender]; } _locks[msg.sender] = 0; _lastUnlockBlock[msg.sender] = 0; _transfer(msg.sender, _to, balanceOf(msg.sender)); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev 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 => uint256) 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, uint256 previousBalance, uint256 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, uint256 nonce, uint256 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), "Treats::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "Treats::delegateBySig: invalid nonce" ); require(block.timestamp <= expiry, "Treats::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, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "Treats::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, "Treats::_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 getChainId() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" function updateCodeAddress(address newAddress) internal { require( bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) } } function proxiableUUID() public pure returns (bytes32) { return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; } } contract LibraryLockDataLayout { bool public initialized = false; } contract LibraryLock is LibraryLockDataLayout { // Ensures no one can manipulate the Logic Contract once it is deployed. // PARITY WALLET HACK PREVENTION modifier delegatedOnly() { require(initialized == true, "The library is locked. No direct 'call' is allowed"); _; } function initialize() internal { initialized = true; } } contract DataLayout is LibraryLock { // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 rewardDebtAtBlock; // the last block user stake uint256 lastWithdrawBlock; // the last block a user withdrew at. uint256 firstDepositBlock; // the last block a user deposited at. uint256 blockdelta; //time passed since withdrawals uint256 lastDepositBlock; // // We do some fancy math here. Basically, any point in time, the amount of HokkFiTokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accGovTokenPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accGovTokenPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } struct UserGlobalInfo { uint256 globalAmount; mapping(address => uint256) referrals; uint256 totalReferals; uint256 globalRefAmount; } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HokkFiTokens to distribute per block. uint256 lastRewardBlock; // Last block number that HokkFiTokens distribution occurs. uint256 accGovTokenPerShare; // Accumulated HokkFiTokens per share, times 1e12. See below. } // The Governance token Treats public govToken; // Dev address. address public devaddr; // LP address address public liquidityaddr; // Community Fund Address address public comfundaddr; // Founder Reward address public founderaddr; // HokkFiTokens created per block. uint256 public REWARD_PER_BLOCK; // Bonus muliplier for early Treats makers. uint256[] public REWARD_MULTIPLIER; // init in constructor function uint256[] public HALVING_AT_BLOCK; // init in constructor function uint256[] public blockDeltaStartStage; uint256[] public blockDeltaEndStage; uint256[] public userFeeStage; uint256[] public devFeeStage; uint256 public FINISH_BONUS_AT_BLOCK; uint256 public userDepFee; uint256 public devDepFee; // The block number when Treats mining starts. uint256 public START_BLOCK; uint256 public PERCENT_LOCK_BONUS_REWARD; // lock xx% of bounus reward in 3 year uint256 public PERCENT_FOR_DEV; // dev bounties + partnerships uint256 public PERCENT_FOR_LP; // LP fund uint256 public PERCENT_FOR_COM; // community fund uint256 public PERCENT_FOR_FOUNDERS; // founders fund // Info of each pool. PoolInfo[] public poolInfo; mapping(address => uint256) public poolId1; // poolId1 count from 1, subtraction 1 before using with poolInfo // Info of each user that stakes LP tokens. pid => user address => info mapping(uint256 => mapping(address => UserInfo)) public userInfo; mapping(address => UserGlobalInfo) public userGlobalInfo; mapping(IERC20 => bool) public poolExistence; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; address payable public stakingContract; } // MasterChef is the master breeder of whatever creature the Treats represents. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once Treats is sufficiently // distributed and the community can show to govern itself. // contract MasterChef is Ownable, Authorizable, ReentrancyGuard, Proxiable, DataLayout { using SafeMath for uint256; using SafeERC20 for IERC20; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event SendHokkFiTokenReward( address indexed user, uint256 indexed pid, uint256 amount, uint256 lockAmount ); event DevAddressChange(address indexed dev); event BonusFinishUpdate(uint256 _block); event HalvingUpdate(uint256[] block); event LpAddressUpdate(address indexed lpAddress); event ComAddressUpdate(address indexed comAddress); event FounderAddressUpdate(address indexed founderAddress); event RewardUpdate(uint256 amount); event RewardMulUpdate(uint256[] rewardMultiplier); event LockUpdate(uint256 PERCENT_LOCK_BONUS_REWARD); event LockdevUpdate(uint256 PERCENT_FOR_DEV); event LocklpUpdate(uint256 PERCENT_FOR_LP); event LockcomUpdate(uint256 PERCENT_FOR_COM); event LockfounderUpdate(uint256 PERCENT_FOR_FOUNDERS); event StarblockUpdate(uint256 START_BLOCK); event WithdrawRevised(address indexed user, uint256 block); event DepositRevised(address indexed user, uint256 amount); event StageStartSet(uint256[] blockStarts); event StageEndSet(uint256[] blockEnds); event UserFeeStageUpdate(uint256[] userFees); event DevFeeStageUpdate(uint256[] devFees); event DevDepFeeUpdate(uint256 devFeePerecnt); event UserDepFeeUpdate(uint256 usrDepFees); modifier nonDuplicated(IERC20 _lpToken) { require(!poolExistence[_lpToken], "MasterChef::nonDuplicated: duplicated"); _; } modifier validatePoolByPid(uint256 _pid) { require(_pid < poolInfo.length, "Pool does not exist"); _; } constructor( ) { } function initializeProxy( Treats _govToken, // address _devaddr, // address _liquidityaddr, // address _comfundaddr, // address _founderaddr, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _halvingAfterBlock, uint256 _userDepFee, uint256 _devDepFee, uint256[] memory _rewardMultiplier, uint256[] memory _blockDeltaStartStage, uint256[] memory _blockDeltaEndStage, uint256[] memory _userFeeStage, uint256[] memory _devFeeStage ) public { require(!initialized); setOwnableConstructor(); govToken = _govToken; // devaddr = _devaddr; // liquidityaddr = _liquidityaddr; // comfundaddr = _comfundaddr; // founderaddr = _founderaddr; REWARD_PER_BLOCK = _rewardPerBlock; START_BLOCK = _startBlock; userDepFee = _userDepFee; devDepFee = _devDepFee; REWARD_MULTIPLIER = _rewardMultiplier; blockDeltaStartStage = _blockDeltaStartStage; blockDeltaEndStage = _blockDeltaEndStage; userFeeStage = _userFeeStage; devFeeStage = _devFeeStage; for (uint256 i = 0; i < REWARD_MULTIPLIER.length - 1; i++) { uint256 halvingAtBlock = _halvingAfterBlock.mul(i + 1).add(_startBlock).add(1); HALVING_AT_BLOCK.push(halvingAtBlock); } FINISH_BONUS_AT_BLOCK = _halvingAfterBlock .mul(REWARD_MULTIPLIER.length) .add(_startBlock); HALVING_AT_BLOCK.push(type(uint256).max - 1); initialize(); } function updateCode(address newCode) public onlyOwner delegatedOnly { updateCodeAddress(newCode); } function resetAuthorizedOwner() public onlyOwner { setAuthorizedOwner(); } function setStakingContract(address payable _stakingContract) external onlyOwner{ stakingContract = _stakingContract; } function poolLength() external view returns(uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external onlyOwner nonDuplicated(_lpToken) { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > START_BLOCK ? block.number : START_BLOCK; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_lpToken] = true; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accGovTokenPerShare: 0 }) ); } // Update the given pool's Treats allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner validatePoolByPid(_pid) { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 GovTokenForDev; uint256 GovTokenForFarmer; uint256 GovTokenForLP; uint256 GovTokenForCom; uint256 GovTokenForFounders; ( GovTokenForDev, GovTokenForFarmer, GovTokenForLP, GovTokenForCom, GovTokenForFounders ) = getPoolReward(pool.lastRewardBlock, block.number, pool.allocPoint); govToken.mint(address(this), GovTokenForFarmer); pool.accGovTokenPerShare = pool.accGovTokenPerShare.add( GovTokenForFarmer.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; if (GovTokenForDev > 0) { govToken.mint(address(devaddr), GovTokenForDev); //Dev fund has xx% locked during the starting bonus period. After which locked funds drip out linearly each block over 3 years. if (block.number <= FINISH_BONUS_AT_BLOCK) { govToken.lock(address(devaddr), GovTokenForDev.mul(75).div(100)); } } if (GovTokenForLP > 0) { govToken.mint(liquidityaddr, GovTokenForLP); //LP + Partnership fund has only xx% locked over time as most of it is needed early on for incentives and listings. The locked amount will drip out linearly each block after the bonus period. if (block.number <= FINISH_BONUS_AT_BLOCK) { govToken.lock(address(liquidityaddr), GovTokenForLP.mul(45).div(100)); } } if (GovTokenForCom > 0) { govToken.mint(comfundaddr, GovTokenForCom); //Community Fund has xx% locked during bonus period and then drips out linearly over 3 years. if (block.number <= FINISH_BONUS_AT_BLOCK) { govToken.lock(address(comfundaddr), GovTokenForCom.mul(85).div(100)); } } if (GovTokenForFounders > 0) { govToken.mint(founderaddr, GovTokenForFounders); //The Founders reward has xx% of their funds locked during the bonus period which then drip out linearly per block over 3 years. if (block.number <= FINISH_BONUS_AT_BLOCK) { govToken.lock(address(founderaddr), GovTokenForFounders.mul(95).div(100)); } } } // |--------------------------------------| // [20, 30, 40, 50, 60, 70, 80, 99999999] // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns(uint256) { uint256 result = 0; if (_from < START_BLOCK || _to > FINISH_BONUS_AT_BLOCK) return 0; for (uint256 i = 0; i < HALVING_AT_BLOCK.length; i++) { uint256 endBlock = HALVING_AT_BLOCK[i]; if (_to <= endBlock) { uint256 m = _to.sub(_from).mul(REWARD_MULTIPLIER[i]); return result.add(m); } if (_from < endBlock) { uint256 m = endBlock.sub(_from).mul(REWARD_MULTIPLIER[i]); _from = endBlock; result = result.add(m); } } return result; } function getPoolReward( uint256 _from, uint256 _to, uint256 _allocPoint ) public view returns( uint256 forDev, uint256 forFarmer, uint256 forLP, uint256 forCom, uint256 forFounders ) { uint256 multiplier = getMultiplier(_from, _to); uint256 amount = multiplier.mul(REWARD_PER_BLOCK).mul(_allocPoint).div( totalAllocPoint ); uint256 HokkFiTokenCanMint = govToken.cap().sub(govToken.totalSupply()); uint256 mulFactor = PERCENT_FOR_DEV + PERCENT_FOR_LP + PERCENT_FOR_COM + PERCENT_FOR_FOUNDERS; uint256 checkAmount = amount + amount.mul(mulFactor).div(100); if (HokkFiTokenCanMint < amount) { forDev = 0; forFarmer = HokkFiTokenCanMint; forLP = 0; forCom = 0; forFounders = 0; } else if (HokkFiTokenCanMint < checkAmount) { forDev = 0; forFarmer = amount; forLP = 0; forCom = 0; forFounders = 0; } else { forDev = amount.mul(PERCENT_FOR_DEV).div(100); forFarmer = amount; forLP = amount.mul(PERCENT_FOR_LP).div(100); forCom = amount.mul(PERCENT_FOR_COM).div(100); forFounders = amount.mul(PERCENT_FOR_FOUNDERS).div(100); } } // View function to see pending HokkFiTokens on frontend. function pendingReward(uint256 _pid, address _user) external view validatePoolByPid(_pid) returns(uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGovTokenPerShare = pool.accGovTokenPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply > 0) { uint256 GovTokenForFarmer; (, GovTokenForFarmer, , , ) = getPoolReward( pool.lastRewardBlock, block.number, pool.allocPoint ); accGovTokenPerShare = accGovTokenPerShare.add( GovTokenForFarmer.mul(1e12).div(lpSupply) ); } return user.amount.mul(accGovTokenPerShare).div(1e12).sub(user.rewardDebt); } function claimRewards(uint256[] memory _pids) external { for (uint256 i = 0; i < _pids.length; i++) { claimReward(_pids[i]); } } function claimReward(uint256 _pid) public validatePoolByPid(_pid) { updatePool(_pid); _harvest(_pid); } // lock 95% of reward if it comes from bonus time function _harvest(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accGovTokenPerShare).div(1e12).sub( user.rewardDebt ); uint256 masterBal = govToken.balanceOf(address(this)); if (pending > masterBal) { pending = masterBal; } if (pending > 0) { govToken.transfer(msg.sender, pending); uint256 lockAmount = 0; if (user.rewardDebtAtBlock <= FINISH_BONUS_AT_BLOCK) { lockAmount = pending.mul(PERCENT_LOCK_BONUS_REWARD).div( 100 ); govToken.lock(msg.sender, lockAmount); } user.rewardDebtAtBlock = block.number; emit SendHokkFiTokenReward(msg.sender, _pid, pending, lockAmount); } user.rewardDebt = user.amount.mul(pool.accGovTokenPerShare).div(1e12); if (_pid == 0) { IStaking(stakingContract).claimRewards(msg.sender, msg.sender, user.amount); } } } function getGlobalAmount(address _user) external view returns(uint256) { UserGlobalInfo storage current = userGlobalInfo[_user]; return current.globalAmount; } function getGlobalRefAmount(address _user) external view returns(uint256) { UserGlobalInfo storage current = userGlobalInfo[_user]; return current.globalRefAmount; } function getTotalRefs(address _user) external view returns(uint256) { UserGlobalInfo storage current = userGlobalInfo[_user]; return current.totalReferals; } function getRefValueOf(address _user, address _user2) external view returns(uint256) { UserGlobalInfo storage current = userGlobalInfo[_user]; uint256 a = current.referrals[_user2]; return a; } // Deposit LP tokens to MasterChef for Treats allocation. function deposit( uint256 _pid, uint256 _amount, address _ref ) external nonReentrant validatePoolByPid(_pid) { require( _amount > 0, "MasterChef::deposit: amount must be greater than 0" ); // require(_ref != address(0), "MasterChef::deposit: zero address for ref"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; UserInfo storage devr = userInfo[_pid][devaddr]; UserGlobalInfo storage refer = userGlobalInfo[_ref]; UserGlobalInfo storage current = userGlobalInfo[msg.sender]; if (refer.referrals[msg.sender] > 0) { refer.referrals[msg.sender] = refer.referrals[msg.sender] + _amount; refer.globalRefAmount = refer.globalRefAmount + _amount; } else { refer.referrals[msg.sender] = refer.referrals[msg.sender] + _amount; refer.totalReferals = refer.totalReferals + 1; refer.globalRefAmount = refer.globalRefAmount + _amount; } current.globalAmount = current.globalAmount + _amount - _amount.mul(userDepFee).div(10000); updatePool(_pid); _harvest(_pid); pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); if (user.amount == 0) { user.rewardDebtAtBlock = block.number; } user.amount = user.amount.add( _amount.sub(_amount.mul(userDepFee).div(10000)) ); user.rewardDebt = user.amount.mul(pool.accGovTokenPerShare).div(1e12); devr.amount = devr.amount.add( _amount.sub(_amount.mul(devDepFee).div(10000)) ); devr.rewardDebt = devr.amount.mul(pool.accGovTokenPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); if (user.firstDepositBlock > 0) {} else { user.firstDepositBlock = block.number; } user.lastDepositBlock = block.number; if (_pid == 0) { IStaking(stakingContract).deposit(msg.sender, _amount.sub(_amount.mul(userDepFee).div(10000))); } } // Withdraw LP tokens from MasterChef. function withdraw( uint256 _pid, uint256 _amount, address _ref ) external nonReentrant validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; UserGlobalInfo storage refer = userGlobalInfo[_ref]; UserGlobalInfo storage current = userGlobalInfo[msg.sender]; require(user.amount >= _amount, "MasterChef::withdraw: not good"); if (_ref != address(0)) { refer.referrals[msg.sender] = refer.referrals[msg.sender] - _amount; refer.globalRefAmount = refer.globalRefAmount - _amount; } current.globalAmount = current.globalAmount - _amount; updatePool(_pid); _harvest(_pid); if (_amount > 0) { user.amount = user.amount.sub(_amount); if (user.lastWithdrawBlock > 0) { user.blockdelta = block.number - user.lastWithdrawBlock; } else { user.blockdelta = block.number - user.firstDepositBlock; } if ( user.blockdelta == blockDeltaStartStage[0] || block.number == user.lastDepositBlock ) { //25% fee for withdrawals of LP tokens in the same block this is to prevent abuse from flashloans pool.lpToken.safeTransfer( address(msg.sender), _amount.mul(userFeeStage[0]).div(100) ); pool.lpToken.safeTransfer( address(devaddr), _amount.mul(devFeeStage[0]).div(100) ); } else if ( user.blockdelta >= blockDeltaStartStage[1] && user.blockdelta <= blockDeltaEndStage[0] ) { //8% fee if a user deposits and withdraws in between same block and 59 minutes. pool.lpToken.safeTransfer( address(msg.sender), _amount.mul(userFeeStage[1]).div(100) ); pool.lpToken.safeTransfer( address(devaddr), _amount.mul(devFeeStage[1]).div(100) ); } else if ( user.blockdelta >= blockDeltaStartStage[2] && user.blockdelta <= blockDeltaEndStage[1] ) { //4% fee if a user deposits and withdraws after 1 hour but before 1 day. pool.lpToken.safeTransfer( address(msg.sender), _amount.mul(userFeeStage[2]).div(100) ); pool.lpToken.safeTransfer( address(devaddr), _amount.mul(devFeeStage[2]).div(100) ); } else if ( user.blockdelta >= blockDeltaStartStage[3] && user.blockdelta <= blockDeltaEndStage[2] ) { //2% fee if a user deposits and withdraws between after 1 day but before 3 days. pool.lpToken.safeTransfer( address(msg.sender), _amount.mul(userFeeStage[3]).div(100) ); pool.lpToken.safeTransfer( address(devaddr), _amount.mul(devFeeStage[3]).div(100) ); } else if ( user.blockdelta >= blockDeltaStartStage[4] && user.blockdelta <= blockDeltaEndStage[3] ) { //1% fee if a user deposits and withdraws after 3 days but before 5 days. pool.lpToken.safeTransfer( address(msg.sender), _amount.mul(userFeeStage[4]).div(100) ); pool.lpToken.safeTransfer( address(devaddr), _amount.mul(devFeeStage[4]).div(100) ); } else if ( user.blockdelta >= blockDeltaStartStage[5] && user.blockdelta <= blockDeltaEndStage[4] ) { //0.5% fee if a user deposits and withdraws if the user withdraws after 5 days but before 2 weeks. pool.lpToken.safeTransfer( address(msg.sender), _amount.mul(userFeeStage[5]).div(1000) ); pool.lpToken.safeTransfer( address(devaddr), _amount.mul(devFeeStage[5]).div(1000) ); } else if ( user.blockdelta >= blockDeltaStartStage[6] && user.blockdelta <= blockDeltaEndStage[5] ) { //0.25% fee if a user deposits and withdraws after 2 weeks. pool.lpToken.safeTransfer( address(msg.sender), _amount.mul(userFeeStage[6]).div(10000) ); pool.lpToken.safeTransfer( address(devaddr), _amount.mul(devFeeStage[6]).div(10000) ); } else if (user.blockdelta > blockDeltaStartStage[7]) { //0.1% fee if a user deposits and withdraws after 4 weeks. pool.lpToken.safeTransfer( address(msg.sender), _amount.mul(userFeeStage[7]).div(10000) ); pool.lpToken.safeTransfer( address(devaddr), _amount.mul(devFeeStage[7]).div(10000) ); } user.rewardDebt = user.amount.mul(pool.accGovTokenPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); user.lastWithdrawBlock = block.number; if (_pid == 0) { IStaking(stakingContract).withdraw(msg.sender, _amount, true); } } } // Withdraw without caring about rewards. EMERGENCY ONLY. This has the same 25% fee as same block withdrawals to prevent abuse of thisfunction. function emergencyWithdraw(uint256 _pid) external nonReentrant validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; //reordered from Sushi function to prevent risk of reentrancy uint256 amountToSend = user.amount.mul(75).div(100); uint256 devToSend = user.amount.mul(25).div(100); if (_pid == 0) { IStaking(stakingContract).withdraw(msg.sender, user.amount, true); } user.amount = 0; user.rewardDebt = 0; user.rewardDebtAtBlock = 0; user.lastWithdrawBlock = 0; user.firstDepositBlock = 0; user.blockdelta = 0; user.lastDepositBlock = 0; pool.lpToken.safeTransfer(address(msg.sender), amountToSend); pool.lpToken.safeTransfer(address(devaddr), devToSend); emit EmergencyWithdraw(msg.sender, _pid, amountToSend); } // Safe GovToken transfer function, just in case if rounding error causes pool to not have enough GovTokens. function safeGovTokenTransfer(address _to, uint256 _amount) internal { uint256 govTokenBal = govToken.balanceOf(address(this)); bool transferSuccess = false; if (_amount > govTokenBal) { transferSuccess = govToken.transfer(_to, govTokenBal); } else { transferSuccess = govToken.transfer(_to, _amount); } require(transferSuccess, "MasterChef::safeGovTokenTransfer: transfer failed"); } // Update dev address by the previous dev. function dev(address _devaddr) external onlyAuthorized { devaddr = _devaddr; emit DevAddressChange(devaddr); } // Update Finish Bonus Block function bonusFinishUpdate(uint256 _newFinish) external onlyAuthorized { FINISH_BONUS_AT_BLOCK = _newFinish; emit BonusFinishUpdate(FINISH_BONUS_AT_BLOCK); } // Update Halving At Block function halvingUpdate(uint256[] memory _newHalving) external onlyAuthorized { HALVING_AT_BLOCK = _newHalving; emit HalvingUpdate(HALVING_AT_BLOCK); } // Update Liquidityaddr function lpUpdate(address _newLP) external onlyAuthorized { liquidityaddr = _newLP; emit LpAddressUpdate(liquidityaddr); } // Update comfundaddr function comUpdate(address _newCom) external onlyAuthorized { comfundaddr = _newCom; emit ComAddressUpdate(comfundaddr); } // Update founderaddr function founderUpdate(address _newFounder) external onlyAuthorized { founderaddr = _newFounder; emit FounderAddressUpdate(founderaddr); } // Update Reward Per Block function rewardUpdate(uint256 _newReward) external onlyAuthorized { REWARD_PER_BLOCK = _newReward; emit RewardUpdate(REWARD_PER_BLOCK); } // Update Rewards Mulitplier Array function rewardMulUpdate(uint256[] memory _newMulReward) external onlyAuthorized { REWARD_MULTIPLIER = _newMulReward; emit RewardMulUpdate(REWARD_MULTIPLIER); } // Update % lock for general users function lockUpdate(uint256 _newlock) external onlyAuthorized { PERCENT_LOCK_BONUS_REWARD = _newlock; emit LockUpdate(PERCENT_LOCK_BONUS_REWARD); } // Update % lock for dev function lockdevUpdate(uint256 _newdevlock) external onlyAuthorized { PERCENT_FOR_DEV = _newdevlock; emit LockdevUpdate(PERCENT_FOR_DEV); } // Update % lock for LP function locklpUpdate(uint256 _newlplock) external onlyAuthorized { PERCENT_FOR_LP = _newlplock; emit LocklpUpdate(PERCENT_FOR_LP); } // Update % lock for COM function lockcomUpdate(uint256 _newcomlock) external onlyAuthorized { PERCENT_FOR_COM = _newcomlock; emit LockcomUpdate(PERCENT_FOR_COM); } // Update % lock for Founders function lockfounderUpdate(uint256 _newfounderlock) external onlyAuthorized { PERCENT_FOR_FOUNDERS = _newfounderlock; emit LockfounderUpdate(PERCENT_FOR_FOUNDERS); } // Update START_BLOCK function starblockUpdate(uint256 _newstarblock) external onlyAuthorized { START_BLOCK = _newstarblock; emit StarblockUpdate(START_BLOCK); } function getNewRewardPerBlock(uint256 pid1) external view returns(uint256) { uint256 multiplier = getMultiplier(block.number - 1, block.number); return multiplier .mul(REWARD_PER_BLOCK) .mul(poolInfo[pid1].allocPoint) .div(totalAllocPoint); } function userDelta(uint256 _pid) external view validatePoolByPid(_pid) returns(uint256) { UserInfo storage user = userInfo[_pid][msg.sender]; if (user.lastWithdrawBlock > 0) { uint256 estDelta = block.number - user.lastWithdrawBlock; return estDelta; } else { uint256 estDelta = block.number - user.firstDepositBlock; return estDelta; } } function reviseWithdraw( uint256 _pid, address _user, uint256 _block ) external onlyAuthorized() validatePoolByPid(_pid) { UserInfo storage user = userInfo[_pid][_user]; user.lastWithdrawBlock = _block; emit WithdrawRevised(_user, _block); } function reviseDeposit( uint256 _pid, address _user, uint256 _block ) external onlyAuthorized() validatePoolByPid(_pid) { UserInfo storage user = userInfo[_pid][_user]; user.firstDepositBlock = _block; emit DepositRevised(_user, _block); } function setStageStarts(uint256[] memory _blockStarts) external onlyAuthorized() { blockDeltaStartStage = _blockStarts; emit StageStartSet(blockDeltaStartStage); } function setStageEnds(uint256[] memory _blockEnds) external onlyAuthorized() { blockDeltaEndStage = _blockEnds; emit StageEndSet(blockDeltaEndStage); } function setUserFeeStage(uint256[] memory _userFees) external onlyAuthorized() { userFeeStage = _userFees; emit UserFeeStageUpdate(userFeeStage); } function setDevFeeStage(uint256[] memory _devFees) external onlyAuthorized() { devFeeStage = _devFees; emit DevFeeStageUpdate(userFeeStage); } function setDevDepFee(uint256 _devDepFees) external onlyAuthorized() { devDepFee = _devDepFees; emit DevDepFeeUpdate(devDepFee); } function setUserDepFee(uint256 _usrDepFees) external onlyAuthorized() { userDepFee = _usrDepFees; emit UserDepFeeUpdate(userDepFee); } function reclaimTokenOwnership(address _newOwner) external onlyAuthorized() { govToken.transferOwnership(_newOwner); } }
Update % lock for COM
function lockcomUpdate(uint256 _newcomlock) external onlyAuthorized { PERCENT_FOR_COM = _newcomlock; emit LockcomUpdate(PERCENT_FOR_COM); }
10,151,477
./full_match/1/0xC817C0B518e8Fc98034ad867d679d4f8A284BFBE/sources/contracts/vliz.sol
ensure input is in 18 decimal points as token is 18dp
function mintAdditional(uint256 _amount) external onlyOwner { _mint(lizardDaoTreasury, _amount); }
8,443,932
./full_match/5/0xFf4927e04c6a01868284F5C3fB9cba7F7ca4aeC0/sources/project_/contracts/modules/CMTAT_BASE.sol
Returns the number of decimals used to get its user representation./
function decimals() public view virtual override(ERC20Upgradeable, ERC20BaseModule) returns (uint8) { return ERC20BaseModule.decimals(); }
7,059,374
// File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/vendor/SafeMathChainlink.sol pragma solidity ^0.7.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 SafeMathChainlink { /** * @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: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/vendor/Address.sol // From https://github.com/OpenZeppelin/openzeppelin-contracts v3.4.0(fa64a1ced0b70ab89073d5d0b6e01b0778f7e7d6) 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); } } } } // File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/interfaces/WithdrawalInterface.sol pragma solidity ^0.7.0; interface WithdrawalInterface { /** * @notice transfer LINK held by the contract belonging to msg.sender to * another address * @param recipient is the address to send the LINK to * @param amount is the amount of LINK to send */ function withdraw( address recipient, uint256 amount ) external; /** * @notice query the available amount of LINK to withdraw by msg.sender */ function withdrawable() external view returns ( uint256 ); } // File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/interfaces/OracleInterface.sol pragma solidity ^0.7.0; interface OracleInterface { function fulfillOracleRequest( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes32 data ) external returns ( bool ); function withdraw( address recipient, uint256 amount ) external; function withdrawable() external view returns ( uint256 ); } // File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/interfaces/ChainlinkRequestInterface.sol pragma solidity ^0.7.0; interface ChainlinkRequestInterface { function oracleRequest( address sender, uint256 requestPrice, bytes32 serviceAgreementID, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunctionId, uint256 expiration ) external; } // File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/interfaces/OperatorInterface.sol pragma solidity ^0.7.0; interface OperatorInterface is ChainlinkRequestInterface, OracleInterface { function requestOracleData( address sender, uint256 payment, bytes32 specId, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function fulfillOracleRequest2( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data ) external returns ( bool ); function ownerTransferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); } // File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/interfaces/LinkTokenInterface.sol pragma solidity ^0.7.0; interface LinkTokenInterface { 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: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/interfaces/OwnableInterface.sol pragma solidity ^0.7.0; interface OwnableInterface { function owner() external returns ( address ); function transferOwnership( address recipient ) external; function acceptOwnership() external; } // File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/ConfirmedOwnerWithProposal.sol pragma solidity ^0.7.0; /** * @title The ConfirmedOwner contract * @notice A contract with helpers for basic contract ownership. */ contract ConfirmedOwnerWithProposal is OwnableInterface { address private s_owner; address private s_pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor( address newOwner, address pendingOwner ) { require(newOwner != address(0), "Cannot set owner to zero"); s_owner = newOwner; if (pendingOwner != address(0)) { _transferOwnership(pendingOwner); } } /** * @notice Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership( address to ) public override onlyOwner() { _transferOwnership(to); } /** * @notice Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external override { require(msg.sender == s_pendingOwner, "Must be proposed owner"); address oldOwner = s_owner; s_owner = msg.sender; s_pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @notice Get the current owner */ function owner() public view override returns ( address ) { return s_owner; } /** * @notice validate, transfer ownership, and emit relevant events */ function _transferOwnership( address to ) private { require(to != msg.sender, "Cannot transfer to self"); s_pendingOwner = to; emit OwnershipTransferRequested(s_owner, to); } /** * @notice validate access */ function _validateOwnership() internal view { require(msg.sender == s_owner, "Only callable by owner"); } /** * @notice Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { _validateOwnership(); _; } } // File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/ConfirmedOwner.sol pragma solidity ^0.7.0; /** * @title The ConfirmedOwner contract * @notice A contract with helpers for basic contract ownership. */ contract ConfirmedOwner is ConfirmedOwnerWithProposal { constructor( address newOwner ) ConfirmedOwnerWithProposal( newOwner, address(0) ) { } } // File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/LinkTokenReceiver.sol pragma solidity ^0.7.0; abstract contract LinkTokenReceiver { /** * @notice Called when LINK is sent to the contract via `transferAndCall` * @dev The data payload's first 2 words will be overwritten by the `sender` and `amount` * values to ensure correctness. Calls oracleRequest. * @param sender Address of the sender * @param amount Amount of LINK sent (specified in wei) * @param data Payload of the transaction */ function onTokenTransfer( address sender, uint256 amount, bytes memory data ) public validateFromLINK() permittedFunctionsForLINK(data) { assembly { // solhint-disable-next-line avoid-low-level-calls mstore(add(data, 36), sender) // ensure correct sender is passed // solhint-disable-next-line avoid-low-level-calls mstore(add(data, 68), amount) // ensure correct amount is passed } // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).delegatecall(data); // calls oracleRequest require(success, "Unable to create request"); } function getChainlinkToken() public view virtual returns ( address ); /** * @notice Validate the function called on token transfer */ function _validateTokenTransferAction( bytes4 funcSelector, bytes memory data ) internal virtual; /** * @dev Reverts if not sent from the LINK token */ modifier validateFromLINK() { require(msg.sender == getChainlinkToken(), "Must use LINK token"); _; } /** * @dev Reverts if the given data does not begin with the `oracleRequest` function selector * @param data The data payload of the request */ modifier permittedFunctionsForLINK( bytes memory data ) { bytes4 funcSelector; assembly { // solhint-disable-next-line avoid-low-level-calls funcSelector := mload(add(data, 32)) } _validateTokenTransferAction(funcSelector, data); _; } } // File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/interfaces/AuthorizedReceiverInterface.sol pragma solidity ^0.7.0; interface AuthorizedReceiverInterface { function isAuthorizedSender( address sender ) external view returns (bool); function getAuthorizedSenders() external returns ( address[] memory ); function setAuthorizedSenders( address[] calldata senders ) external; } // File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/AuthorizedReceiver.sol pragma solidity ^0.7.0; abstract contract AuthorizedReceiver is AuthorizedReceiverInterface { mapping(address => bool) private s_authorizedSenders; address[] private s_authorizedSenderList; event AuthorizedSendersChanged( address[] senders, address changedBy ); /** * @notice Sets the fulfillment permission for a given node. Use `true` to allow, `false` to disallow. * @param senders The addresses of the authorized Chainlink node */ function setAuthorizedSenders( address[] calldata senders ) external override validateAuthorizedSenderSetter() { require(senders.length > 0, "Must have at least 1 authorized sender"); // Set previous authorized senders to false uint256 authorizedSendersLength = s_authorizedSenderList.length; for (uint256 i = 0; i < authorizedSendersLength; i++) { s_authorizedSenders[s_authorizedSenderList[i]] = false; } // Set new to true for (uint256 i = 0; i < senders.length; i++) { s_authorizedSenders[senders[i]] = true; } // Replace list s_authorizedSenderList = senders; emit AuthorizedSendersChanged(senders, msg.sender); } /** * @notice Retrieve a list of authorized senders * @return array of addresses */ function getAuthorizedSenders() external view override returns ( address[] memory ) { return s_authorizedSenderList; } /** * @notice Use this to check if a node is authorized for fulfilling requests * @param sender The address of the Chainlink node * @return The authorization status of the node */ function isAuthorizedSender( address sender ) public view override returns (bool) { return s_authorizedSenders[sender]; } /** * @notice customizable guard of who can update the authorized sender list * @return bool whether sender can update authorized sender list */ function _canSetAuthorizedSenders() internal virtual returns (bool); /** * @notice validates the sender is an authorized sender */ function _validateIsAuthorizedSender() internal view { require(isAuthorizedSender(msg.sender), "Not authorized sender"); } /** * @notice prevents non-authorized addresses from calling this method */ modifier validateAuthorizedSender() { _validateIsAuthorizedSender(); _; } /** * @notice prevents non-authorized addresses from calling this method */ modifier validateAuthorizedSenderSetter() { require(_canSetAuthorizedSenders(), "Cannot set authorized senders"); _; } } // File: https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.7/Operator.sol pragma solidity ^0.7.0; /** * @title The Chainlink Operator contract * @notice Node operators can deploy this contract to fulfill requests sent to them */ contract Operator is AuthorizedReceiver, ConfirmedOwner, LinkTokenReceiver, OperatorInterface, WithdrawalInterface { using Address for address; using SafeMathChainlink for uint256; struct Commitment { bytes31 paramsHash; uint8 dataVersion; } uint256 constant public getExpiryTime = 5 minutes; uint256 constant private MAXIMUM_DATA_VERSION = 256; uint256 constant private MINIMUM_CONSUMER_GAS_LIMIT = 400000; uint256 constant private SELECTOR_LENGTH = 4; uint256 constant private EXPECTED_REQUEST_WORDS = 2; uint256 constant private MINIMUM_REQUEST_LENGTH = SELECTOR_LENGTH + (32 * EXPECTED_REQUEST_WORDS); // We initialize fields to 1 instead of 0 so that the first invocation // does not cost more gas. uint256 constant private ONE_FOR_CONSISTENT_GAS_COST = 1; // oracleRequest is version 1, enabling single word responses bytes4 constant private ORACLE_REQUEST_SELECTOR = this.oracleRequest.selector; // requestOracleData is version 2, enabling multi-word responses bytes4 constant private OPERATOR_REQUEST_SELECTOR = this.requestOracleData.selector; LinkTokenInterface internal immutable linkToken; mapping(bytes32 => Commitment) private s_commitments; // Tokens sent for requests that have not been fulfilled yet uint256 private s_tokensInEscrow = ONE_FOR_CONSISTENT_GAS_COST; event OracleRequest( bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data ); event CancelOracleRequest( bytes32 indexed requestId ); event OracleResponse( bytes32 indexed requestId ); event OwnableContractAccepted( address indexed accpetedContract ); event TargetsUpdatedAuthorizedSenders( address[] targets, address[] senders, address changedBy ); /** * @notice Deploy with the address of the LINK token * @dev Sets the LinkToken address for the imported LinkTokenInterface * @param link The address of the LINK token * @param owner The address of the owner */ constructor( address link, address owner ) ConfirmedOwner(owner) { linkToken = LinkTokenInterface(link); // external but already deployed and unalterable } function oracleRequest( address sender, uint256 payment, bytes32 specId, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external override { requestOracleData( sender, payment, specId, callbackAddress, callbackFunctionId, nonce, dataVersion, data ); } /** * @notice Creates the Chainlink request * @dev Stores the hash of the params as the on-chain commitment for the request. * Emits OracleRequest event for the Chainlink node to detect. * @param sender The sender of the request * @param payment The amount of payment given (specified in wei) * @param specId The Job Specification ID * @param callbackAddress The callback address for the response * @param callbackFunctionId The callback function ID for the response * @param nonce The nonce sent by the requester * @param dataVersion The specified data version * @param data The CBOR payload of the request */ function requestOracleData( address sender, uint256 payment, bytes32 specId, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) public override validateFromLINK() validateNotToLINK(callbackAddress) { (bytes32 requestId, uint256 expiration) = _verifyOracleRequest( sender, payment, callbackAddress, callbackFunctionId, nonce, dataVersion ); emit OracleRequest( specId, sender, requestId, payment, callbackAddress, callbackFunctionId, expiration, dataVersion, data); } /** * @notice Called by the Chainlink node to fulfill requests * @dev Given params must hash back to the commitment stored from `oracleRequest`. * Will call the callback address' callback function without bubbling up error * checking in a `require` so that the node can get paid. * @param requestId The fulfillment request ID that must match the requester's * @param payment The payment amount that will be released for the oracle (specified in wei) * @param callbackAddress The callback address to call for fulfillment * @param callbackFunctionId The callback function ID to use for fulfillment * @param expiration The expiration that the node should respond by before the requester can cancel * @param data The data to return to the consuming contract * @return Status if the external call was successful */ function fulfillOracleRequest( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes32 data ) external override validateAuthorizedSender() validateRequestId(requestId) returns ( bool ) { _verifyOracleResponse( requestId, payment, callbackAddress, callbackFunctionId, expiration, 1 ); emit OracleResponse(requestId); require(gasleft() >= MINIMUM_CONSUMER_GAS_LIMIT, "Must provide consumer enough gas"); // All updates to the oracle's fulfillment should come before calling the // callback(addr+functionId) as it is untrusted. // See: https://solidity.readthedocs.io/en/develop/security-considerations.html#use-the-checks-effects-interactions-pattern (bool success, ) = callbackAddress.call(abi.encodeWithSelector(callbackFunctionId, requestId, data)); // solhint-disable-line avoid-low-level-calls return success; } /** * @notice Called by the Chainlink node to fulfill requests with multi-word support * @dev Given params must hash back to the commitment stored from `oracleRequest`. * Will call the callback address' callback function without bubbling up error * checking in a `require` so that the node can get paid. * @param requestId The fulfillment request ID that must match the requester's * @param payment The payment amount that will be released for the oracle (specified in wei) * @param callbackAddress The callback address to call for fulfillment * @param callbackFunctionId The callback function ID to use for fulfillment * @param expiration The expiration that the node should respond by before the requester can cancel * @param data The data to return to the consuming contract * @return Status if the external call was successful */ function fulfillOracleRequest2( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data ) external override validateAuthorizedSender() validateRequestId(requestId) validateMultiWordResponseId(requestId, data) returns ( bool ) { _verifyOracleResponse( requestId, payment, callbackAddress, callbackFunctionId, expiration, 2 ); emit OracleResponse(requestId); require(gasleft() >= MINIMUM_CONSUMER_GAS_LIMIT, "Must provide consumer enough gas"); // All updates to the oracle's fulfillment should come before calling the // callback(addr+functionId) as it is untrusted. // See: https://solidity.readthedocs.io/en/develop/security-considerations.html#use-the-checks-effects-interactions-pattern (bool success, ) = callbackAddress.call(abi.encodePacked(callbackFunctionId, data)); // solhint-disable-line avoid-low-level-calls return success; } /** * @notice Transfer the ownership of ownable contracts * @param ownable list of addresses to transfer * @param newOwner address to transfer ownership to */ function transferOwnableContracts( address[] calldata ownable, address newOwner ) external onlyOwner() { for (uint256 i = 0; i < ownable.length; i++) { OwnableInterface(ownable[i]).transferOwnership(newOwner); } } /** * @notice Accept the ownership of an ownable contract * @dev Must be the pending owner on the contract * @param ownable list of addresses of Ownable contracts to accept */ function acceptOwnableContracts( address[] calldata ownable ) public validateAuthorizedSenderSetter() { for (uint256 i = 0; i < ownable.length; i++) { OwnableInterface(ownable[i]).acceptOwnership(); emit OwnableContractAccepted(ownable[i]); } } /** * @notice Sets the fulfillment permission for * @param targets The addresses to set permissions on * @param senders The addresses that are allowed to send updates */ function setAuthorizedSendersOn( address[] calldata targets, address[] calldata senders ) public validateAuthorizedSenderSetter() { TargetsUpdatedAuthorizedSenders(targets, senders, msg.sender); for (uint256 i = 0; i < targets.length; i++) { AuthorizedReceiverInterface(targets[i]).setAuthorizedSenders(senders); } } /** * @notice Sets the fulfillment permission for * @param targets The addresses to set permissions on * @param senders The addresses that are allowed to send updates */ function acceptAuthorizedReceivers( address[] calldata targets, address[] calldata senders ) external validateAuthorizedSenderSetter() { acceptOwnableContracts(targets); setAuthorizedSendersOn(targets, senders); } /** * @notice Allows the node operator to withdraw earned LINK to a given address * @dev The owner of the contract can be another wallet and does not have to be a Chainlink node * @param recipient The address to send the LINK token to * @param amount The amount to send (specified in wei) */ function withdraw( address recipient, uint256 amount ) external override(OracleInterface, WithdrawalInterface) onlyOwner() validateAvailableFunds(amount) { assert(linkToken.transfer(recipient, amount)); } /** * @notice Displays the amount of LINK that is available for the node operator to withdraw * @dev We use `ONE_FOR_CONSISTENT_GAS_COST` in place of 0 in storage * @return The amount of withdrawable LINK on the contract */ function withdrawable() external view override(OracleInterface, WithdrawalInterface) returns (uint256) { return _fundsAvailable(); } /** * @notice Forward a call to another contract * @dev Only callable by the owner * @param to address * @param data to forward */ function ownerForward( address to, bytes calldata data ) external onlyOwner() validateNotToLINK(to) { require(to.isContract(), "Must forward to a contract"); (bool status,) = to.call(data); require(status, "Forwarded call failed"); } /** * @notice Interact with other LinkTokenReceiver contracts by calling transferAndCall * @param to The address to transfer to. * @param value The amount to be transferred. * @param data The extra data to be passed to the receiving contract. * @return success bool */ function ownerTransferAndCall( address to, uint256 value, bytes calldata data ) external override onlyOwner() validateAvailableFunds(value) returns ( bool success ) { return linkToken.transferAndCall(to, value, data); } /** * @notice Distribute funds to multiple addresses using ETH send * to this payable function. * @dev Array length must be equal, ETH sent must equal the sum of amounts. * @param receivers list of addresses * @param amounts list of amounts */ function distributeFunds( address payable[] calldata receivers, uint[] calldata amounts ) external payable { require(receivers.length > 0 && receivers.length == amounts.length, "Invalid array length(s)"); uint256 valueRemaining = msg.value; for (uint256 i = 0; i < receivers.length; i++) { uint256 sendAmount = amounts[i]; valueRemaining = valueRemaining.sub(sendAmount); receivers[i].transfer(sendAmount); } require(valueRemaining == 0, "Too much ETH sent"); } /** * @notice Allows requesters to cancel requests sent to this oracle contract. Will transfer the LINK * sent for the request back to the requester's address. * @dev Given params must hash to a commitment stored on the contract in order for the request to be valid * Emits CancelOracleRequest event. * @param requestId The request ID * @param payment The amount of payment given (specified in wei) * @param callbackFunc The requester's specified callback address * @param expiration The time of the expiration for the request */ function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunc, uint256 expiration ) external override { bytes31 paramsHash = _buildFunctionHash(payment, msg.sender, callbackFunc, expiration); require(s_commitments[requestId].paramsHash == paramsHash, "Params do not match request ID"); // solhint-disable-next-line not-rely-on-time require(expiration <= block.timestamp, "Request is not expired"); delete s_commitments[requestId]; emit CancelOracleRequest(requestId); assert(linkToken.transfer(msg.sender, payment)); } /** * @notice Returns the address of the LINK token * @dev This is the public implementation for chainlinkTokenAddress, which is * an internal method of the ChainlinkClient contract */ function getChainlinkToken() public view override returns ( address ) { return address(linkToken); } /** * @notice Require that the token transfer action is valid * @dev OPERATOR_REQUEST_SELECTOR = multiword, ORACLE_REQUEST_SELECTOR = singleword */ function _validateTokenTransferAction( bytes4 funcSelector, bytes memory data ) internal override pure { require(data.length >= MINIMUM_REQUEST_LENGTH, "Invalid request length"); require(funcSelector == OPERATOR_REQUEST_SELECTOR || funcSelector == ORACLE_REQUEST_SELECTOR, "Must use whitelisted functions"); } /** * @notice Verify the Oracle Request * @param sender The sender of the request * @param payment The amount of payment given (specified in wei) * @param callbackAddress The callback address for the response * @param callbackFunctionId The callback function ID for the response * @param nonce The nonce sent by the requester */ function _verifyOracleRequest( address sender, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion ) private returns ( bytes32 requestId, uint256 expiration ) { requestId = keccak256(abi.encodePacked(sender, nonce)); require(s_commitments[requestId].paramsHash == 0, "Must use a unique ID"); // solhint-disable-next-line not-rely-on-time expiration = block.timestamp.add(getExpiryTime); bytes31 paramsHash = _buildFunctionHash(payment, callbackAddress, callbackFunctionId, expiration); s_commitments[requestId] = Commitment(paramsHash, _safeCastToUint8(dataVersion)); s_tokensInEscrow = s_tokensInEscrow.add(payment); return (requestId, expiration); } /** * @notice Verify the Oracle Response * @param requestId The fulfillment request ID that must match the requester's * @param payment The payment amount that will be released for the oracle (specified in wei) * @param callbackAddress The callback address to call for fulfillment * @param callbackFunctionId The callback function ID to use for fulfillment * @param expiration The expiration that the node should respond by before the requester can cancel */ function _verifyOracleResponse( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, uint256 dataVersion ) internal { bytes31 paramsHash = _buildFunctionHash(payment, callbackAddress, callbackFunctionId, expiration); require(s_commitments[requestId].paramsHash == paramsHash, "Params do not match request ID"); require(s_commitments[requestId].dataVersion <= _safeCastToUint8(dataVersion), "Data versions must match"); s_tokensInEscrow = s_tokensInEscrow.sub(payment); delete s_commitments[requestId]; } /** * @notice Build the bytes31 function hash from the payment, callback and expiration. * @param payment The payment amount that will be released for the oracle (specified in wei) * @param callbackAddress The callback address to call for fulfillment * @param callbackFunctionId The callback function ID to use for fulfillment * @param expiration The expiration that the node should respond by before the requester can cancel * @return hash bytes31 */ function _buildFunctionHash( uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration ) internal pure returns ( bytes31 ) { return bytes31(keccak256( abi.encodePacked( payment, callbackAddress, callbackFunctionId, expiration ) )); } /** * @notice Safely cast uint256 to uint8 * @param number uint256 * @return uint8 number */ function _safeCastToUint8( uint256 number ) internal pure returns ( uint8 ) { require(number < MAXIMUM_DATA_VERSION, "number too big to cast"); return uint8(number); } /** * @notice Returns the LINK available in this contract, not locked in escrow * @return uint256 LINK tokens available */ function _fundsAvailable() private view returns ( uint256 ) { uint256 inEscrow = s_tokensInEscrow.sub(ONE_FOR_CONSISTENT_GAS_COST); return linkToken.balanceOf(address(this)).sub(inEscrow); } /** * @notice concrete implementation of AuthorizedReceiver * @return bool of whether sender is authorized */ function _canSetAuthorizedSenders() internal view override returns (bool) { return isAuthorizedSender(msg.sender) || owner() == msg.sender; } // MODIFIERS /** * @dev Reverts if the first 32 bytes of the bytes array is not equal to requestId * @param requestId bytes32 * @param data bytes */ modifier validateMultiWordResponseId( bytes32 requestId, bytes memory data ) { bytes32 firstWord; assembly{ firstWord := mload(add(data, 0x20)) } require(requestId == firstWord, "First word must be requestId"); _; } /** * @dev Reverts if amount requested is greater than withdrawable balance * @param amount The given amount to compare to `s_withdrawableTokens` */ modifier validateAvailableFunds( uint256 amount ) { require(_fundsAvailable() >= amount, "Amount requested is greater than withdrawable balance"); _; } /** * @dev Reverts if request ID does not exist * @param requestId The given request ID to check in stored `commitments` */ modifier validateRequestId( bytes32 requestId ) { require(s_commitments[requestId].paramsHash != 0, "Must have a valid requestId"); _; } /** * @dev Reverts if the callback address is the LINK token * @param to The callback address */ modifier validateNotToLINK( address to ) { require(to != address(linkToken), "Cannot call to LINK"); _; } } // File: contracts/Operator.sol pragma solidity ^0.7.0;
Allows the node operator to withdraw earned LINK to a given address The owner of the contract can be another wallet and does not have to be a Chainlink node recipient The address to send the LINK token to amount The amount to send (specified in wei)/
function withdraw( address recipient, uint256 amount ) external override(OracleInterface, WithdrawalInterface) onlyOwner() validateAvailableFunds(amount) { assert(linkToken.transfer(recipient, amount)); }
206,687
pragma solidity ^ 0.4 .24; 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; } } contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IERC20 { function totalSupply() external view returns(uint256); function balanceOf(address who) external view returns(uint256); function allowance(address owner, address spender) external view returns(uint256); 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); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns(uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns(uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns(uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns(bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns(bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @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(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, 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 Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string name, string symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } } library SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(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' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } 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); } } contract FlychatToken is ERC20, ERC20Detailed, ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); uint256 public constant INITIAL_SUPPLY = 6000000000 * (10 ** uint256(decimals())); uint256 public constant INITIAL_SUPPLY2 = 14000000000 * (10 ** uint256(decimals())); uint256 public rate = 10000000; enum CrowdsaleStage { presale, ico } CrowdsaleStage public stage = CrowdsaleStage.presale; bool public allowbuy = false; bool public endbuy = false; uint256 public preallocation = 2400000000 * (10 ** uint256(18)); uint256 public icoallocation = 9600000000 * (10 ** uint256(18)); uint256 public minbuy = 10000000000000000; uint256 public availableonpresale = preallocation; uint256 public availableonico = icoallocation; constructor(address wallet) public ERC20Detailed("FlychatToken", "FLY", 18) { require(rate > 0); require(wallet != address(0)); _rate = rate; _wallet = wallet; _token = this; _mint(msg.sender, INITIAL_SUPPLY); _mint(this, INITIAL_SUPPLY2); } function setallowbuy(bool status) public onlyOwner { allowbuy = status; } function setendbuy(bool status) public onlyOwner { endbuy = status; } function setstage(uint8 _stage) public onlyOwner { setCrowdsaleStage(_stage); } function setCrowdsaleStage(uint8 _stage) internal { require(_stage > uint8(stage) && _stage < 2); if (uint8(CrowdsaleStage.presale) == _stage) { stage = CrowdsaleStage.presale; } else { stage = CrowdsaleStage.ico; } } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer fund 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(msg.sender); } /** * @return the token being sold. */ function token() public view returns(IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns(address) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns(uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); uint256 tottokens; // update bonus if (stage == CrowdsaleStage.presale) { if (availableonpresale >= tokens) { availableonpresale = availableonpresale - tokens; tottokens = tokens + (tokens.mul(15).div(100)); } else { uint256 xtoken = availableonpresale; availableonpresale = availableonpresale - xtoken; uint256 ytoken = tokens - availableonpresale; availableonico = availableonico - ytoken; tottokens = tokens + (xtoken.mul(15).div(100)) + (ytoken.mul(10).div(100)); setCrowdsaleStage(1); } } else { require(availableonico >= tokens); availableonico = availableonico - tokens; tottokens = tokens + (tokens.mul(10).div(100)); if (availableonico <= 0) { endbuy = true; } } // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tottokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { require(beneficiary != address(0)); require(weiAmount != 0); require(allowbuy); require(!endbuy); require(weiAmount >= minbuy); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to 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(uint256 weiAmount) internal view returns(uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } function sendBack() public onlyOwner { _deliverTokens(owner(), balanceOf(this)); } }
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 spender The address which will spend the funds. 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; }
12,638,085
./partial_match/1/0xdDc2c27eA8a42b35B329c4e0216600F12EED13d1/sources/contracts/wombat-core/pool/WormholeAdaptor.sol
Estimate the amount of message value required to deliver a message with given `deliveryGasLimit` and `receiveValue` A buffer should be added to `deliveryGasLimit` in case the amount of gas required is higher than the expectation toChain wormhole chain ID deliveryGasLimit gas limit of the callback function on the designated network receiverValue target amount of gas token to receive Note that this function may fail if the value requested is too large. Using deliveryGasLimit 200000 is typically enough/
function estimateDeliveryFee( uint16 toChain, uint256 receiverValue, uint32 deliveryGasLimit ) external view returns (uint256 nativePriceQuote, uint256 targetChainRefundPerGasUnused) { return relayer.quoteEVMDeliveryPrice(toChain, receiverValue, deliveryGasLimit); }
2,762,598
pragma solidity ^0.4.24; // File: node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: node_modules/openzeppelin-solidity/contracts/introspection/IERC165.sol /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ 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. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract 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 ); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom( address from, address to, uint256 tokenId, bytes data ) public; } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 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)"))` */ function onERC721Received( address operator, address from, uint256 tokenId, bytes data ) public returns(bytes4); } // File: node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol /** * @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: node_modules/openzeppelin-solidity/contracts/utils/Address.sol /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: node_modules/openzeppelin-solidity/contracts/introspection/ERC165.sol /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { require(_tokenOwner[tokenId] == address(0)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes _data ) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) private { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ /** * @dev Constructor function */ constructor() public { // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256) { require(index < balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } /** * @dev Internal function to add a token ID to the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { super._addTokenTo(to, tokenId); uint256 length = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); _ownedTokensIndex[tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { super._removeTokenFrom(from, tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = _ownedTokensIndex[tokenId]; uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 lastToken = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list _ownedTokensIndex[tokenId] = 0; _ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Reorg all tokens array uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 lastToken = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastToken; _allTokens[lastTokenIndex] = 0; _allTokens.length--; _allTokensIndex[tokenId] = 0; _allTokensIndex[lastToken] = tokenIndex; } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Metadata is IERC721 { function name() external view returns (string); function symbol() external view returns (string); function tokenURI(uint256 tokenId) external view returns (string); } // File: contracts/ERC721Metadata.sol //import "../node_modules/openzeppelin-solidity/contracts/math/Safemath.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { using SafeMath for uint256; event LockUpdate(uint256 indexed tokenId, uint256 fromLockedTo, uint256 fromLockId, uint256 toLockedTo, uint256 toLockId, uint256 callId); event StatsUpdate(uint256 indexed tokenId, uint256 fromLevel, uint256 fromWins, uint256 fromLosses, uint256 toLevel, uint256 toWins, uint256 toLosses); // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs string private _baseURI; string private _description; string private _url; struct Character { uint256 mintedAt; uint256 genes; uint256 lockedTo; uint256 lockId; uint256 level; uint256 wins; uint256 losses; } mapping(uint256 => Character) characters; // tokenId => Character bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor(string name, string symbol, string baseURI, string description, string url) public { _name = name; _symbol = symbol; _baseURI = baseURI; _description = description; _url = url; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return _symbol; } /** * @dev Gets the contract description * @return string representing the contract description */ function description() external view returns (string) { return _description; } /** * @dev Gets the project url * @return string representing the project url */ function url() external view returns (string) { return _url; } /** * @dev Function to set the token base URI * @param newBaseUri string URI to assign */ function _setBaseURI(string newBaseUri) internal { _baseURI = newBaseUri; } /** * @dev Function to set the contract description * @param newDescription string contract description to assign */ function _setDescription(string newDescription) internal { _description = newDescription; } /** * @dev Function to set the project url * @param newUrl string project url to assign */ function _setURL(string newUrl) internal { _url = newUrl; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string) { require(_exists(tokenId)); return string(abi.encodePacked(_baseURI, uint2str(tokenId))); } function _setMetadata(uint256 tokenId, uint256 genes, uint256 level) internal { require(_exists(tokenId)); // Character storage character = characters[_tokenId]; characters[tokenId] = Character({ mintedAt : now, genes : genes, lockedTo : 0, lockId : 0, level : level, wins : 0, losses : 0 }); emit StatsUpdate(tokenId, 0, 0, 0, level, 0, 0); } function _clearMetadata(uint256 tokenId) internal { require(_exists(tokenId)); delete characters[tokenId]; } /* LOCKS */ function isFree(uint tokenId) public view returns (bool) { require(_exists(tokenId)); return now > characters[tokenId].lockedTo; } function getLock(uint256 tokenId) external view returns (uint256 lockedTo, uint256 lockId) { require(_exists(tokenId)); Character memory c = characters[tokenId]; return (c.lockedTo, c.lockId); } function getLevel(uint256 tokenId) external view returns (uint256) { require(_exists(tokenId)); return characters[tokenId].level; } function getGenes(uint256 tokenId) external view returns (uint256) { require(_exists(tokenId)); return characters[tokenId].genes; } function getRace(uint256 tokenId) external view returns (uint256) { require(_exists(tokenId)); return characters[tokenId].genes & 0xFFFF; } function getCharacter(uint256 tokenId) external view returns ( uint256 mintedAt, uint256 genes, uint256 race, uint256 lockedTo, uint256 lockId, uint256 level, uint256 wins, uint256 losses ) { require(_exists(tokenId)); Character memory c = characters[tokenId]; return (c.mintedAt, c.genes, c.genes & 0xFFFF, c.lockedTo, c.lockId, c.level, c.wins, c.losses); } function _setLock(uint256 tokenId, uint256 lockedTo, uint256 lockId, uint256 callId) internal returns (bool) { require(isFree(tokenId)); Character storage c = characters[tokenId]; emit LockUpdate(tokenId, c.lockedTo, c.lockId, lockedTo, lockId, callId); c.lockedTo = lockedTo; c.lockId = lockId; return true; } /* CHARACTER LOGIC */ function _addWin(uint256 tokenId, uint256 _winsCount, uint256 _levelUp) internal returns (bool) { require(_exists(tokenId)); Character storage c = characters[tokenId]; uint prevWins = c.wins; uint prevLevel = c.level; c.wins = c.wins.add(_winsCount); c.level = c.level.add(_levelUp); emit StatsUpdate(tokenId, prevLevel, prevWins, c.losses, c.level, c.wins, c.losses); return true; } function _addLoss(uint256 tokenId, uint256 _lossesCount, uint256 _levelDown) internal returns (bool) { require(_exists(tokenId)); Character storage c = characters[tokenId]; uint prevLosses = c.losses; uint prevLevel = c.level; c.losses = c.losses.add(_lossesCount); c.level = c.level > _levelDown ? c.level.sub(_levelDown) : 1; emit StatsUpdate(tokenId, prevLevel, c.wins, prevLosses, c.level, c.wins, c.losses); return true; } /** * @dev Convert uint to string * @param i The uint to convert * @return A string representation of uint. */ 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); } } // File: lib/HasAgents.sol /** * @title agents * @dev Library for managing addresses assigned to a agent. */ library Agents { using Address for address; struct Data { uint id; bool exists; bool allowance; } struct Agent { mapping(address => Data) data; mapping(uint => address) list; } /** * @dev give an account access to this agent */ function add(Agent storage agent, address account, uint id, bool allowance) internal { require(!exists(agent, account)); agent.data[account] = Data({ id : id, exists : true, allowance : allowance }); agent.list[id] = account; } /** * @dev remove an account's access to this agent */ function remove(Agent storage agent, address account) internal { require(exists(agent, account)); //if it not updated agent - clean list record if (agent.list[agent.data[account].id] == account) { delete agent.list[agent.data[account].id]; } delete agent.data[account]; } /** * @dev check if an account has this agent * @return bool */ function exists(Agent storage agent, address account) internal view returns (bool) { require(account != address(0)); //auto prevent existing of agents with updated address and same id return agent.data[account].exists && agent.list[agent.data[account].id] == account; } /** * @dev get agent id of the account * @return uint */ function id(Agent storage agent, address account) internal view returns (uint) { require(exists(agent, account)); return agent.data[account].id; } function byId(Agent storage agent, uint agentId) internal view returns (address) { address account = agent.list[agentId]; require(account != address(0)); require(agent.data[account].exists && agent.data[account].id == agentId); return account; } function allowance(Agent storage agent, address account) internal view returns (bool) { require(exists(agent, account)); return account.isContract() && agent.data[account].allowance; } } contract HasAgents is Ownable { using Agents for Agents.Agent; event AgentAdded(address indexed account); event AgentRemoved(address indexed account); Agents.Agent private agents; constructor() internal { _addAgent(msg.sender, 0, false); } modifier onlyAgent() { require(isAgent(msg.sender)); _; } function isAgent(address account) public view returns (bool) { return agents.exists(account); } function addAgent(address account, uint id, bool allowance) public onlyOwner { _addAgent(account, id, allowance); } function removeAgent(address account) public onlyOwner { _removeAgent(account); } function renounceAgent() public { _removeAgent(msg.sender); } function _addAgent(address account, uint id, bool allowance) internal { agents.add(account, id, allowance); emit AgentAdded(account); } function _removeAgent(address account) internal { agents.remove(account); emit AgentRemoved(account); } function getAgentId(address account) public view returns (uint) { return agents.id(account); } // function getCallerAgentId() public view returns (uint) { // return agents.id(msg.sender); // } function getAgentById(uint id) public view returns (address) { return agents.byId(id); } function isAgentHasAllowance(address account) public view returns (bool) { return agents.allowance(account); } } // File: node_modules/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol /** * @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); } } // File: lib/HasDepositary.sol /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract HasDepositary is Ownable, ReentrancyGuard { event Depositary(address depositary); address private _depositary; // constructor() internal { // _depositary = msg.sender; // } /// @notice The fallback function payable function() external payable { require(msg.value > 0); // _depositary.transfer(msg.value); } function depositary() external view returns (address) { return _depositary; } function setDepositary(address newDepositary) external onlyOwner { require(newDepositary != address(0)); require(_depositary == address(0)); _depositary = newDepositary; emit Depositary(newDepositary); } function withdraw() external onlyOwner nonReentrant { uint256 balance = address(this).balance; require(balance > 0); if (_depositary == address(0)) { owner().transfer(balance); } else { _depositary.transfer(balance); } } } // File: node_modules/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); 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); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: lib/CanReclaimToken.sol /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { /** * @dev Reclaim all ERC20 compatible tokens * @param token ERC20 The address of the token contract */ function reclaimToken(IERC20 token) external onlyOwner { if (address(token) == address(0)) { owner().transfer(address(this).balance); return; } uint256 balance = token.balanceOf(this); token.transfer(owner(), balance); } } // File: contracts/Heroes.sol interface AgentContract { function isAllowed(uint _tokenId) external returns (bool); } contract Heroes is Ownable, ERC721, ERC721Enumerable, ERC721Metadata, HasAgents, HasDepositary { uint256 private lastId = 1000; event Mint(address indexed to, uint256 indexed tokenId); event Burn(address indexed from, uint256 indexed tokenId); constructor() HasAgents() ERC721Metadata( "CRYPTO HEROES", //name "CH ⚔️", //symbol "https://api.cryptoheroes.app/hero/", //baseURI "The first blockchain game in the world with famous characters and fights built on real cryptocurrency exchange quotations.", //description "https://cryptoheroes.app" //url ) public {} /** * @dev Function to set the token base URI * @param uri string URI to assign */ function setBaseURI(string uri) external onlyOwner { _setBaseURI(uri); } function setDescription(string description) external onlyOwner { _setDescription(description); } function setURL(string url) external onlyOwner { _setURL(url); } /** * @dev override */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { return ( super._isApprovedOrOwner(spender, tokenId) || //approve tx from agents on behalf user //agent's functions must have onlyOwnerOf modifier to prevent phishing from 3-d party contracts (isAgent(spender) && super._isApprovedOrOwner(tx.origin, tokenId)) || //just for exceptional cases, no reason to abuse owner() == spender ); } /** * @dev Mints a token to an address * @param to The address that will receive the minted tokens. * @param genes token genes * @param level token level * @return A new token id. */ function mint(address to, uint256 genes, uint256 level) public onlyAgent returns (uint) { lastId = lastId.add(1); return mint(lastId, to, genes, level); // _mint(to, lastId); // _setMetadata(lastId, genes, level); // emit Mint(to, lastId); // return lastId; } /** * @dev Mints a token with specific id to an address * @param to The address that will receive the minted tokens. * @param genes token genes * @param level token level * @return A new token id. */ function mint(uint256 tokenId, address to, uint256 genes, uint256 level) public onlyAgent returns (uint) { _mint(to, tokenId); _setMetadata(tokenId, genes, level); emit Mint(to, tokenId); return tokenId; } /** * @dev Function to burn tokens from sender address * @param tokenId The token id to burn. * @return A burned token id. */ function burn(uint256 tokenId) public returns (uint) { require(_isApprovedOrOwner(msg.sender, tokenId)); address owner = ownerOf(tokenId); _clearMetadata(tokenId); _burn(owner, tokenId); emit Burn(owner, tokenId); return tokenId; } /* CHARACTER LOGIC */ function addWin(uint256 _tokenId, uint _winsCount, uint _levelUp) external onlyAgent returns (bool){ require(_addWin(_tokenId, _winsCount, _levelUp)); return true; } function addLoss(uint256 _tokenId, uint _lossesCount, uint _levelDown) external onlyAgent returns (bool){ require(_addLoss(_tokenId, _lossesCount, _levelDown)); return true; } /* LOCKS */ /* * Принудительно пере-блокируем свободного персонажа c текущего агента на указанный */ function lock(uint256 _tokenId, uint256 _lockedTo, bool _onlyFreeze) external onlyAgent returns(bool) { require(_exists(_tokenId)); uint agentId = getAgentId(msg.sender); Character storage c = characters[_tokenId]; if (c.lockId != 0 && agentId != c.lockId) { //если текущий агент другой, то вызываем его функция "проверки персонажа" address a = getAgentById(c.lockId); if (isAgentHasAllowance(a)) { AgentContract ac = AgentContract(a); require(ac.isAllowed(_tokenId)); } } require(_setLock(_tokenId, _lockedTo, _onlyFreeze ? c.lockId : agentId, agentId)); return true; } function unlock(uint256 _tokenId) external onlyAgent returns (bool){ require(_exists(_tokenId)); uint agentId = getAgentId(msg.sender); //only current owned agent allowed require(agentId == characters[_tokenId].lockId); require(_setLock(_tokenId, 0, 0, agentId)); return true; } function isCallerAgentOf(uint _tokenId) public view returns (bool) { require(_exists(_tokenId)); return isAgent(msg.sender) && getAgentId(msg.sender) == characters[_tokenId].lockId; } /** * @dev Transfers the ownership of a given token ID from the owner to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transfer(address to, uint256 tokenId) public { transferFrom(msg.sender, to, tokenId); } }
Transfers the ownership of a given token ID from the owner to another address Usage of this method is discouraged, use `safeTransferFrom` whenever possible Requires the msg sender to be the owner, approved, or operator to address to receive the ownership of the given token ID tokenId uint256 ID of the token to be transferred/
function transfer(address to, uint256 tokenId) public { transferFrom(msg.sender, to, tokenId); }
12,726,151
./full_match/4/0x4E643d71a7e55f8CFf24ec3B55E61ACC0866cf16/sources/shibanova/libs/ShibaBEP20.sol
Destroys `amount` tokens from `account`, reducing the total supply. Emits a {Transfer} event with `to` set to the zero address. Requirements - `account` cannot be the zero address. - `account` must have at least `amount` tokens./
function _burn(address account, uint256 amount) internal { require(account != BURN_ADDRESS, "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); _burnSupply = _burnSupply.add(amount); emit Transfer(account, BURN_ADDRESS, amount); }
12,475,451
./full_match/5/0x8956E81d76FDdAbF0de54D8Da0d06c2474DeA340/sources/contracts/flatten.sol
will claim the tokens user owed. projectToken address for the projects token contract Ensure we have enough tokens available for claiming
function _claim(address projectToken) internal projectExists(projectToken) { UserClaim storage userClaim = s_userClaims[_msgSender()][projectToken]; ProjectToken memory project = s_projectTokens[projectToken]; if (userClaim.lastClaim == 0 || userClaim.lastClaim >= project.endMonth) { s_userProjects[_msgSender()].remove(projectToken); revert ErrNotEligible(); } if (project.startMonth > block.timestamp) { revert ErrClaimingIsNotAllowedYet(project.startMonth); } if (claimableMonthCount == 0) { revert ErrNothingToClaim(); } uint256 tokensToClaim = project.monthlyAmount.mul(claimableMonthCount); if (project.token.balanceOf(address(this)) < tokensToClaim) { revert ErrNotEnoughTokenLeft(projectToken); } userClaim.totalTokensClaimed = userClaim.totalTokensClaimed.add(tokensToClaim); emit TokensClaimed(_msgSender(), projectToken, claimableMonthCount, tokensToClaim); }
11,605,909
./full_match/4/0x0D2A0040ebbDa84D489503e5354640a602C967a8/sources/contracts/WithLimitedSupply.sol
Update the supply for the collection _supply the new token supply. create additional token supply for this collection.
function _setSupply(uint256 _supply) internal virtual { require( _supply > tokenCount(), "Can't set the supply to less than the current token count" ); _totalSupply = _supply; emit SupplyChanged(totalSupply()); }
13,317,496
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/access/Ownable.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.1.0/contracts/token/ERC20/SafeERC20.sol"; contract TankChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 lastRewardBlock; // Last block number that Rewards distribution occurs. uint256 accRewardPerShare; // Accumulated Rewards per share, times 1e18. See below. } // The deposit token! IERC20 immutable depositToken; IERC20 immutable rewardToken; // Reward tokens created per block. uint256 immutable rewardPerBlock; // Info of each pool. PoolInfo public poolInfo; // Info of each user that stakes tokens. mapping (address => UserInfo) public userInfo; uint256 immutable startBlock; uint256 public endBlock; // The amount to burn in 0.01 percentages uint256 immutable burnMultiplier; // Block smart contracts bool public blockContracts; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event DisableContracts(bool block); constructor( IERC20 _depositToken, IERC20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock, uint256 _burnMultiplier ) public { depositToken = _depositToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; burnMultiplier = _burnMultiplier; // staking pool poolInfo = PoolInfo({ token: _depositToken, lastRewardBlock: _startBlock, accRewardPerShare: 0 }); } function stopReward() external onlyOwner { endBlock = block.number; } function adjustBlockEnd() external onlyOwner { uint256 totalLeft = rewardToken.balanceOf(address(this)); endBlock = block.number + totalLeft.div(rewardPerBlock); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= endBlock) { return _to.sub(_from); } else if (_from >= endBlock) { return 0; } else { return endBlock.sub(_from); } } // View function to see pending Reward on frontend. function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = poolInfo.accRewardPerShare; uint256 supply = poolInfo.token.balanceOf(address(this)); if (block.number > poolInfo.lastRewardBlock && supply != 0) { uint256 multiplier = getMultiplier(poolInfo.lastRewardBlock, block.number); uint256 reward = multiplier.mul(rewardPerBlock); accRewardPerShare = accRewardPerShare.add(reward.mul(1e18).div(supply)); } return user.amount.mul(accRewardPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables of the given pool to be up-to-date. function updatePool() public { if (block.number <= poolInfo.lastRewardBlock) { return; } uint256 supply = poolInfo.token.balanceOf(address(this)); if (supply == 0) { poolInfo.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(poolInfo.lastRewardBlock, block.number); uint256 reward = multiplier.mul(rewardPerBlock); poolInfo.accRewardPerShare = poolInfo.accRewardPerShare.add(reward.mul(1e18).div(supply)); poolInfo.lastRewardBlock = block.number; } // Stake depositToken tokens to SmartChef function deposit(uint256 _amount) external { if (blockContracts) { require(msg.sender == tx.origin, "contracts blocked"); } UserInfo storage user = userInfo[msg.sender]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(poolInfo.accRewardPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { user.rewardDebt = user.amount.mul(poolInfo.accRewardPerShare).div(1e18); rewardToken.safeTransfer(address(msg.sender), pending); } } if(_amount > 0) { uint256 burnAmount = _amount.mul(burnMultiplier).div(10000); poolInfo.token.safeTransferFrom(address(msg.sender), address(this), _amount - burnAmount); if (burnAmount > 0) { poolInfo.token.safeTransferFrom(address(msg.sender), address(0xdead), burnAmount); } user.amount = user.amount.add(_amount - burnAmount); } user.rewardDebt = user.amount.mul(poolInfo.accRewardPerShare).div(1e18); emit Deposit(msg.sender, _amount); } // Withdraw depositToken tokens from STAKING. function withdraw(uint256 _amount) external { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(); uint256 pending = user.amount.mul(poolInfo.accRewardPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); poolInfo.token.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(poolInfo.accRewardPerShare).div(1e18); emit Withdraw(msg.sender, _amount); } function disableContracts(bool _block) external onlyOwner { blockContracts = _block; emit DisableContracts(_block); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external { UserInfo storage user = userInfo[msg.sender]; poolInfo.token.safeTransfer(address(msg.sender), user.amount); user.amount = 0; user.rewardDebt = 0; emit EmergencyWithdraw(msg.sender, user.amount); } // Withdraw reward. EMERGENCY ONLY. function emergencyRewardWithdraw(uint256 _amount) external onlyOwner { require(_amount <= rewardToken.balanceOf(address(this)), 'not enough token'); rewardToken.safeTransfer(address(msg.sender), _amount); } }
Update reward variables of the given pool to be up-to-date.
function updatePool() public { if (block.number <= poolInfo.lastRewardBlock) { return; } uint256 supply = poolInfo.token.balanceOf(address(this)); if (supply == 0) { poolInfo.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(poolInfo.lastRewardBlock, block.number); uint256 reward = multiplier.mul(rewardPerBlock); poolInfo.accRewardPerShare = poolInfo.accRewardPerShare.add(reward.mul(1e18).div(supply)); poolInfo.lastRewardBlock = block.number; }
967,204
./full_match/43113/0x7b22B49a73059AD9e8bb4410c7a1E8e4B4cD56aa/sources/contracts/AraToken.sol
overrides transfer function to meet tokenomics of ARA
function _transfer(address sender, address recipient, uint256 amount) internal virtual override { if (sender == owner() || recipient == owner()) { super._transfer(sender, recipient, amount); uint256 taxAmount; if (amount <= maxTransferAmount()) { taxAmount = amount.mul(transferTaxRate).div(10000); console.log('transferTaxRate', transferTaxRate); taxAmount = amount.mul(whaleTransferTaxRate).div(10000); console.log('whaleTransferTaxRate', whaleTransferTaxRate); } console.log('taxAmount', taxAmount); uint256 burnAmount = taxAmount.mul(burnRate).div(10000); console.log('burnAmount', burnAmount); uint256 liquidityAmount = taxAmount.mul(liquidityRate).div(10000); console.log('liquidityAmount', liquidityAmount); uint256 feesAmount = taxAmount.sub(burnAmount).sub(liquidityAmount); console.log('feesAmount', feesAmount); require(taxAmount == burnAmount + liquidityAmount + feesAmount, "SEED::transfer value invalid"); uint256 sendAmount = amount.sub(taxAmount); console.log('sendAmount', sendAmount); require(amount == sendAmount + taxAmount, "SEED::transfer: Tax value invalid"); super._transfer(sender, BURN_ADDRESS, burnAmount); super._transfer(sender, liquidityAddress, liquidityAmount); super._transfer(sender, feesAddress, feesAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } }
7,179,910
./full_match/1/0x60eEC879cd31e47347058048433D9E381F510606/sources/contracts/ommf/ommf_token/ommf.sol
Creates `_sharesAmount` shares and assigns them to `_recipient`, increasing the total amount of shares. This doesn't increase the token total supply. Requirements: - `_recipient` cannot be the zero address. - the contract must not be paused./
function _mintShares( address _recipient, uint256 _sharesAmount ) internal whenNotPaused returns (uint256) { require(_recipient != address(0), "MINT_TO_THE_ZERO_ADDRESS"); _beforeTokenTransfer(address(0), _recipient, _sharesAmount); totalShares += _sharesAmount; shares[_recipient] = shares[_recipient] + _sharesAmount; return totalShares; }
16,405,062
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./helpers.sol"; contract AdminModule is Helpers { modifier onlyOwner() { require(owner == msg.sender, "only owner"); _; } modifier onlyAuth() { require(isAuth[msg.sender], "only owner"); _; } function updateOwner(address owner_) external onlyOwner { owner = owner_; emit updateOwnerLog(owner_); } function updateAuth(address auth_, bool isAuth_) external onlyOwner { isAuth[auth_] = isAuth_; emit updateAuthLog(auth_, isAuth_); } function updateRates(uint16[] memory rates_) external onlyOwner { ratios = Ratios(rates_[0], rates_[1], rates_[2], rates_[3]); emit updateRatesLog(rates_[0], rates_[1], rates_[2], rates_[3]); } function updateRevenueFee(uint newRevenueFee_) external onlyOwner { uint oldRevenueFee_ = revenueFee; revenueFee = newRevenueFee_; emit updateRevenueFeeLog(oldRevenueFee_, newRevenueFee_); } function updateRatios(uint16[] memory ratios_) external onlyOwner { ratios = Ratios(ratios_[0], ratios_[1], ratios_[2], uint128(ratios_[3]) * 1e23); emit updateRatesLog(ratios_[0], ratios_[1], ratios_[2], uint128(ratios_[3]) * 1e23); } } contract CoreHelpers is AdminModule { using SafeERC20 for IERC20; function updateStorage( uint256 exchangePrice_, uint256 newRevenue_ ) internal { if (exchangePrice_ > lastRevenueExchangePrice) { lastRevenueExchangePrice = exchangePrice_; revenue = revenue + newRevenue_; } } function supplyInternal( address token_, uint256 amount_, address to_, bool isEth_ ) internal returns (uint256 vtokenAmount_) { require(amount_ != 0, "amount cannot be zero"); ( uint256 exchangePrice_, uint256 newRevenue_ ) = getCurrentExchangePrice(); updateStorage(exchangePrice_, newRevenue_); if (isEth_) { wethCoreContract.deposit{value: amount_}(); } else { if (token_ == stEthAddr) { IERC20(token_).safeTransferFrom(msg.sender, address(this), amount_); } else if (token_ == wethAddr) { IERC20(token_).safeTransferFrom(msg.sender, address(this), amount_); } else { revert("wrong-token"); } } vtokenAmount_ = (amount_ * 1e18) / exchangePrice_; _mint(to_, vtokenAmount_); emit supplyLog(token_, amount_, to_); } function withdrawHelper( uint amount_, uint limit_ ) internal pure returns ( uint, uint ) { uint transferAmt_; if (limit_ > amount_) { transferAmt_ = amount_; amount_ = 0; } else { transferAmt_ = limit_; amount_ = amount_ - limit_; } return (amount_, transferAmt_); } function withdrawFinal( uint amount_ ) public view returns (uint[] memory transferAmts_) { require(amount_ > 0, "amount-invalid"); (uint netCollateral_, uint netBorrow_, BalVariables memory balances_,,) = netAssets(); uint ratio_ = netCollateral_ > 0 ? (netBorrow_ * 1e4) / netCollateral_ : 0; require(ratio_ < ratios.maxLimit, "already-risky"); // don't allow any withdrawal if Aave position is risky require(amount_ < balances_.totalBal, "excess-withdrawal"); transferAmts_ = new uint[](4); if (balances_.wethVaultBal > 10) { (amount_, transferAmts_[0]) = withdrawHelper(amount_, balances_.wethVaultBal); } if (balances_.wethDsaBal > 10 && amount_ > 0) { (amount_, transferAmts_[1]) = withdrawHelper(amount_, balances_.wethDsaBal); } if (balances_.stethVaultBal > 10 && amount_ > 0) { (amount_, transferAmts_[2]) = withdrawHelper(amount_, balances_.stethVaultBal); } if (balances_.stethDsaBal > 10 && amount_ > 0) { (amount_, transferAmts_[3]) = withdrawHelper(amount_, balances_.stethDsaBal); } } function withdrawTransfers(uint amount_, uint[] memory transferAmts_) internal returns (uint wethAmt_, uint stEthAmt_) { wethAmt_ = transferAmts_[0] + transferAmts_[1]; stEthAmt_ = transferAmts_[2] + transferAmts_[3]; uint totalTransferAmount_ = wethAmt_ + stEthAmt_; // adding final condition in the end in case we fucked up anywhere in above function then this will surely fail // Makes the chances of having a bug to lose asset 0 in withdrawFinal() require(amount_ == totalTransferAmount_, "transfers-not-valid"); // batching up spells and withdrawing all the required asset from DSA to vault at once uint i; uint j; if (transferAmts_[1] > 0 && transferAmts_[3] > 0) { i = 2; } else if (transferAmts_[3] > 0 || transferAmts_[1] > 0) { i = 1; } string[] memory targets_ = new string[](i); bytes[] memory calldata_ = new bytes[](i); if (transferAmts_[1] > 0) { targets_[j] = "BASIC-A"; calldata_[j] = abi.encodeWithSignature("withdraw(address,uint256,address,uint256,uint256)", wethAddr, transferAmts_[1], address(this), 0, 0); j++; } if (transferAmts_[3] > 0) { targets_[j] = "BASIC-A"; calldata_[j] = abi.encodeWithSignature("withdraw(address,uint256,address,uint256,uint256)", stEthAddr, transferAmts_[3], address(this), 0, 0); j++; } if (i > 0) vaultDsa.cast(targets_, calldata_, address(this)); } } contract InstaVaultImplementation is CoreHelpers { using SafeERC20 for IERC20; function supplyEth(address to_) external payable nonReentrant returns (uint vtokenAmount_) { uint amount_ = msg.value; vtokenAmount_ = supplyInternal( ethAddr, amount_, to_, true ); } function supply( address token_, uint256 amount_, address to_ ) external nonReentrant returns (uint256 vtokenAmount_) { vtokenAmount_ = supplyInternal( token_, amount_, to_, false ); } // gives preference to weth in case of withdrawal function withdraw( uint256 amount_, address to_ ) external nonReentrant returns (uint256 vtokenAmount_) { require(amount_ != 0, "amount cannot be zero"); ( uint256 exchangePrice_, uint256 newRevenue_ ) = getCurrentExchangePrice(); updateStorage(exchangePrice_, newRevenue_); if (amount_ == type(uint).max) { vtokenAmount_ = balanceOf(msg.sender); amount_ = vtokenAmount_ * exchangePrice_ / 1e18; } else { vtokenAmount_ = (amount_ * 1e18) / exchangePrice_; } _burn(msg.sender, vtokenAmount_); uint[] memory transferAmts_ = withdrawFinal(amount_); (uint wethAmt_, uint stEthAmt_) = withdrawTransfers(amount_, transferAmts_); if (wethAmt_ > 0) { // withdraw weth and sending ETH to user wethCoreContract.withdraw(wethAmt_); payable(to_).call{value: wethAmt_}(""); } if (stEthAmt_ > 0) stEthContract.safeTransfer(to_, stEthAmt_); emit withdrawLog(amount_, to_); } struct RebalanceOneVariables { uint stETHBal_; string[] targets; bytes[] calldatas; bool[] checks; } // rebalance for leveraging function rebalanceOne( address flashTkn_, uint flashAmt_, uint route_, uint excessDebt_, uint paybackDebt_, uint totalAmountToSwap_, uint extraWithdraw_, uint unitAmt_, bytes memory oneInchData_ ) external nonReentrant onlyAuth { if (excessDebt_ < 1e14) excessDebt_ = 0; if (paybackDebt_ < 1e14) paybackDebt_ = 0; if (totalAmountToSwap_ < 1e14) totalAmountToSwap_ = 0; if (extraWithdraw_ < 1e14) extraWithdraw_ = 0; require(!(excessDebt_ > 0 && paybackDebt_ > 0), "cannot-borrow-and-payback-at-once"); require(!(totalAmountToSwap_ > 0 && paybackDebt_ > 0), "cannot-swap-and-payback-at-once"); RebalanceOneVariables memory v_; BalVariables memory balances_ = getIdealBalances(); if (balances_.wethVaultBal > 1e14) wethContract.safeTransfer(address(vaultDsa), balances_.wethVaultBal); if (balances_.stethVaultBal > 1e14) stEthContract.safeTransfer(address(vaultDsa), balances_.stethVaultBal); v_.stETHBal_ = balances_.stethVaultBal + balances_.stethDsaBal; if (v_.stETHBal_ < 1e14) v_.stETHBal_ = 0; uint i; uint j; if (excessDebt_ > 0) j += 6; if (paybackDebt_ > 0) j += 1; if (v_.stETHBal_ > 0) j += 1; if (extraWithdraw_ > 0) j += 2; v_.targets = new string[](j); v_.calldatas = new bytes[](j); if (excessDebt_ > 0) { require(unitAmt_ > (1e18 - 10), "invalid-unit-amt"); require(totalAmountToSwap_ > 0, "invalid-swap-amt"); v_.targets[0] = "AAVE-V2-A"; v_.calldatas[0] = abi.encodeWithSignature("deposit(address,uint256,uint256,uint256)", flashTkn_, flashAmt_, 0, 0); v_.targets[1] = "AAVE-V2-A"; v_.calldatas[1] = abi.encodeWithSignature("borrow(address,uint256,uint256,uint256,uint256)", wethAddr, excessDebt_, 2, 0, 0); v_.targets[2] = "1INCH-A"; v_.calldatas[2] = abi.encodeWithSignature("sell(address,address,uint256,uint256,bytes,uint256)", wethAddr, stEthAddr, totalAmountToSwap_, unitAmt_, oneInchData_, 0); v_.targets[3] = "AAVE-V2-A"; v_.calldatas[3] = abi.encodeWithSignature("deposit(address,uint256,uint256,uint256)", stEthAddr, type(uint).max, 0, 0); v_.targets[4] = "AAVE-V2-A"; v_.calldatas[4] = abi.encodeWithSignature("withdraw(address,uint256,uint256,uint256)", flashTkn_, flashAmt_, 0, 0); v_.targets[5] = "INSTAPOOL-C"; v_.calldatas[5] = abi.encodeWithSignature("flashPayback(address,uint256,uint256,uint256)", flashTkn_, flashAmt_, 0, 0); i = 6; } if (paybackDebt_ > 0) { v_.targets[i] = "AAVE-V2-A"; v_.calldatas[i] = abi.encodeWithSignature("payback(address,uint256,uint256,uint256,uint256)", wethAddr, paybackDebt_, 2, 0, 0); i++; } if (v_.stETHBal_ > 0) { v_.targets[i] = "AAVE-V2-A"; v_.calldatas[i] = abi.encodeWithSignature("deposit(address,uint256,uint256,uint256)", stEthAddr, type(uint).max, 0, 0); i++; } if (extraWithdraw_ > 0) { v_.targets[i] = "AAVE-V2-A"; v_.calldatas[i] = abi.encodeWithSignature("withdraw(address,uint256,uint256,uint256)", stEthAddr, extraWithdraw_, 0, 0); v_.targets[i + 1] = "BASIC-A"; v_.calldatas[i + 1] = abi.encodeWithSignature("withdraw(address,uint256,address,uint256,uint256)", stEthAddr, extraWithdraw_, address(this), 0, 0); } if (excessDebt_ > 0) { bytes memory encodedFlashData_ = abi.encode(v_.targets, v_.calldatas); string[] memory flashTarget_ = new string[](1); bytes[] memory flashCalldata_ = new bytes[](1); flashTarget_[0] = "INSTAPOOL-C"; flashCalldata_[0] = abi.encodeWithSignature("flashBorrowAndCast(address,uint256,uint256,bytes,bytes)", flashTkn_, flashAmt_, route_, encodedFlashData_, "0x"); vaultDsa.cast(flashTarget_, flashCalldata_, address(this)); require(getWethBorrowRate() < ratios.maxBorrowRate, "high-borrow-rate"); } else { if (j > 0) vaultDsa.cast(v_.targets, v_.calldatas, address(this)); } v_.checks = new bool[](3); (v_.checks[0], v_.checks[1], v_.checks[2]) = validateFinalRatio(); if (excessDebt_ > 0) { require(v_.checks[1], "final assets after leveraging"); } if (extraWithdraw_ > 0) { require(v_.checks[0], "position risky"); } require(v_.checks[2], "ratio is too low"); emit rebalanceOneLog(flashTkn_, flashAmt_, route_, excessDebt_, paybackDebt_, totalAmountToSwap_, extraWithdraw_, unitAmt_); } // rebalance for saving. To be run in times of making position less risky or to fill up the withdraw amount for users to exit function rebalanceTwo( uint withdrawAmt_, address flashTkn_, uint flashAmt_, uint route_, uint saveAmt_, uint unitAmt_, bytes memory oneInchData_ ) external nonReentrant onlyOwner { string[] memory targets_ = new string[](6); bytes[] memory calldata_ = new bytes[](6); targets_[0] = "AAVE-V2-A"; calldata_[0] = abi.encodeWithSignature("deposit(address,uint256,uint256,uint256)", flashTkn_, flashAmt_, 0, 0); targets_[1] = "AAVE-V2-A"; calldata_[1] = abi.encodeWithSignature("withdraw(address,uint256,uint256,uint256)", stEthAddr, (saveAmt_ + withdrawAmt_), 0, 0); targets_[2] = "1INCH-A"; calldata_[2] = abi.encodeWithSignature("sell(address,address,uint256,uint256,bytes,uint256)", stEthAddr, wethAddr, saveAmt_, unitAmt_, oneInchData_, 0); targets_[3] = "AAVE-V2-A"; calldata_[3] = abi.encodeWithSignature("payback(address,uint256,uint256,uint256,uint256)", wethAddr, 0, 2, type(uint).max, 0); targets_[4] = "AAVE-V2-A"; calldata_[4] = abi.encodeWithSignature("withdraw(address,uint256,uint256,uint256)", flashTkn_, flashAmt_, 0, 0); targets_[5] = "INSTAPOOL-C"; calldata_[5] = abi.encodeWithSignature("flashPayback(address,uint256,uint256,uint256)", flashTkn_, flashAmt_, 0, 0); bytes memory encodedFlashData_ = abi.encode(targets_, calldata_); string[] memory flashTarget_ = new string[](1); bytes[] memory flashCalldata_ = new bytes[](1); flashTarget_[0] = "INSTAPOOL-C"; flashCalldata_[0] = abi.encodeWithSignature("flashBorrowAndCast(address,uint256,uint256,bytes,bytes)", flashTkn_, flashAmt_, route_, encodedFlashData_, "0x"); vaultDsa.cast(flashTarget_, flashCalldata_, address(this)); (bool isOk_,,) = validateFinalRatio(); require(isOk_, "position-not-risky"); emit rebalanceTwoLog(withdrawAmt_, flashTkn_, flashAmt_, route_, saveAmt_, unitAmt_); } function initialize( string memory name_, string memory symbol_, address owner_, address auth_, uint256 revenueFee_, uint16[] memory ratios_ ) public initializer { address vaultDsaAddr_ = instaIndex.build(address(this), 2, address(this)); vaultDsa = IDSA(vaultDsaAddr_); __ERC20_init(name_, symbol_); owner = owner_; isAuth[auth_] = true; revenueFee = revenueFee_; lastRevenueExchangePrice = 1e18; // sending borrow rate in 4 decimals eg:- 300 meaning 3% and converting into 27 decimals eg:- 3 * 1e25 ratios = Ratios(ratios_[0], ratios_[1], ratios_[2], uint128(ratios_[3]) * 1e23); } receive() external payable {} } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./events.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract Helpers is Events { using SafeERC20 for IERC20; modifier nonReentrant() { require(_status != 2, "ReentrancyGuard: reentrant call"); _status = 2; _; _status = 1; } /** * @dev Approves the token to the spender address with allowance amount. * @notice Approves the token to the spender address with allowance amount. * @param token_ token for which allowance is to be given. * @param spender_ the address to which the allowance is to be given. * @param amount_ amount of token. */ function approve( address token_, address spender_, uint256 amount_ ) internal { TokenInterface tokenContract_ = TokenInterface(token_); try tokenContract_.approve(spender_, amount_) {} catch { IERC20 token = IERC20(token_); token.safeApprove(spender_, 0); token.safeApprove(spender_, amount_); } } function getWethBorrowRate() internal view returns (uint256 wethBorrowRate_) { (,,,, wethBorrowRate_,,,,,) = aaveProtocolDataProvider .getReserveData(wethAddr); } function getStEthCollateralAmount() internal view returns (uint256 stEthAmount_) { (stEthAmount_, , , , , , , , ) = aaveProtocolDataProvider .getUserReserveData(stEthAddr, address(vaultDsa)); } function getWethDebtAmount() internal view returns (uint256 wethDebtAmount_) { (, , wethDebtAmount_, , , , , , ) = aaveProtocolDataProvider .getUserReserveData(wethAddr, address(vaultDsa)); } struct BalVariables { uint wethVaultBal; uint wethDsaBal; uint stethVaultBal; uint stethDsaBal; uint totalBal; } function getIdealBalances() public view returns ( BalVariables memory balances_ ) { IERC20 wethCon_ = IERC20(wethAddr); IERC20 stethCon_ = IERC20(stEthAddr); balances_.wethVaultBal = wethCon_.balanceOf(address(this)); balances_.wethDsaBal = wethCon_.balanceOf(address(vaultDsa)); balances_.stethVaultBal = stethCon_.balanceOf(address(this)); balances_.stethDsaBal = stethCon_.balanceOf(address(vaultDsa)); balances_.totalBal = balances_.wethVaultBal + balances_.wethDsaBal + balances_.stethVaultBal + balances_.stethDsaBal; } // not substracting revenue here function netAssets() public view returns ( uint netCollateral_, uint netBorrow_, BalVariables memory balances_, uint netSupply_, uint netBal_ ) { netCollateral_ = getStEthCollateralAmount(); netBorrow_ = getWethDebtAmount(); balances_ = getIdealBalances(); netSupply_ = netCollateral_ + balances_.totalBal; netBal_ = netSupply_ - netBorrow_; } function getCurrentExchangePrice() public view returns ( uint256 exchangePrice_, uint256 newRevenue_ ) { (,,,, uint256 netBal_) = netAssets(); netBal_ = netBal_ - revenue; uint totalSupply_ = totalSupply(); uint exchangePriceWithRevenue_; if (totalSupply_ != 0) { exchangePriceWithRevenue_ = (netBal_ * 1e18) / totalSupply_; } else { exchangePriceWithRevenue_ = 1e18; } // Only calculate revenue if there's a profit if (exchangePriceWithRevenue_ > lastRevenueExchangePrice) { uint revenueCut_ = ((exchangePriceWithRevenue_ - lastRevenueExchangePrice) * revenueFee) / 10000; // 10% revenue fee cut newRevenue_ = revenueCut_ * netBal_ / 1e18; exchangePrice_ = exchangePriceWithRevenue_ - revenueCut_; } else { exchangePrice_ = exchangePriceWithRevenue_; } } function validateFinalRatio() internal view returns (bool maxIsOk_, bool minIsOk_, bool minGapIsOk_) { // Not substracting revenue here as it can also help save position. (uint netCollateral_, uint netBorrow_, , uint netSupply_,) = netAssets(); uint ratioMax_ = (netBorrow_ * 1e4) / netCollateral_; // Aave position ratio should not go above max limit maxIsOk_ = ratios.maxLimit > ratioMax_; uint ratioMin_ = (netBorrow_ * 1e4) / netSupply_; // net ratio (position + ideal) should not go above min limit minIsOk_ = ratios.minLimit > ratioMin_; minGapIsOk_ = ratios.minLimitGap < ratioMin_; } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./variables.sol"; contract Events is Variables { event updateOwnerLog(address owner_); event updateAuthLog(address auth_, bool isAuth_); event updateRatesLog(uint16 maxLimit, uint16 minLimit, uint16 gap, uint128 maxBorrowRate); event updateRevenueFeeLog(uint oldRevenueFee_, uint newRevenueFee_); event supplyLog(address token_, uint256 amount_, address to_); event withdrawLog(uint256 amount_, address to_); event rebalanceOneLog( address flashTkn_, uint flashAmt_, uint route_, uint excessDebt_, uint paybackDebt_, uint totalAmountToSwap_, uint extraWithdraw_, uint unitAmt_ ); event rebalanceTwoLog( uint withdrawAmt_, address flashTkn_, uint flashAmt_, uint route_, uint saveAmt_, uint unitAmt_ ); } // 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: Unlicense pragma solidity ^0.8.0; import "./interfaces.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; contract ConstantVariables is ERC20Upgradeable { using SafeERC20 for IERC20; address internal constant ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; IInstaIndex internal constant instaIndex = IInstaIndex(0x2971AdFa57b20E5a416aE5a708A8655A9c74f723); address internal constant wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant stEthAddr = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IAaveProtocolDataProvider internal constant aaveProtocolDataProvider = IAaveProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); TokenInterface internal constant wethCoreContract = TokenInterface(wethAddr); // contains deposit & withdraw for weth IERC20 internal constant wethContract = IERC20(wethAddr); IERC20 internal constant stEthContract = IERC20(stEthAddr); uint internal constant liquidationThreshold = 7500; } contract Variables is ConstantVariables { uint internal _status = 1; address public owner; // only authorized addresses can rebalance mapping (address => bool) public isAuth; IDSA public vaultDsa; // TODO: make sure all the values will <= 1e14 // Initially could be: [7400, 7000, 6900, 300 * 1e23] = [74%, 70%, 69%, 3%] struct Ratios { uint16 maxLimit; // Above this withdrawals are not allowed uint16 minLimit; // After leverage the ratio should be below minLimit & above minLimitGap uint16 minLimitGap; // send borrow rate in 4 decimals from UI. In the smart contract it'll convert to 27 decimals which where is 100% uint128 maxBorrowRate; // maximum borrow rate above this leveraging should not happen } Ratios public ratios; // last revenue exchange price (helps in calculating revenue) // Exchange price when revenue got updated last. It'll only increase overtime. uint256 public lastRevenueExchangePrice; uint256 public revenueFee; // 1000 = 10% (10% of user's profit) uint256 public revenue; } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IInstaIndex { function build( address owner_, uint256 accountVersion_, address origin_ ) external returns (address account_); } interface IDSA { function cast( string[] calldata _targetNames, bytes[] calldata _datas, address _origin ) external payable returns (bytes32); } interface IAaveProtocolDataProvider { function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); } interface TokenInterface { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; function balanceOf(address) external view returns (uint256); function decimals() external view returns (uint256); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/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 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _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 {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } // 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 (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 (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 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 `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 "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ 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() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // 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 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 * ==== * * [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 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); } } } }
gives preference to weth in case of withdrawal withdraw weth and sending ETH to user
function withdraw( uint256 amount_, address to_ ) external nonReentrant returns (uint256 vtokenAmount_) { require(amount_ != 0, "amount cannot be zero"); ( uint256 exchangePrice_, uint256 newRevenue_ ) = getCurrentExchangePrice(); updateStorage(exchangePrice_, newRevenue_); if (amount_ == type(uint).max) { vtokenAmount_ = balanceOf(msg.sender); amount_ = vtokenAmount_ * exchangePrice_ / 1e18; vtokenAmount_ = (amount_ * 1e18) / exchangePrice_; } _burn(msg.sender, vtokenAmount_); uint[] memory transferAmts_ = withdrawFinal(amount_); (uint wethAmt_, uint stEthAmt_) = withdrawTransfers(amount_, transferAmts_); if (wethAmt_ > 0) { wethCoreContract.withdraw(wethAmt_); } if (stEthAmt_ > 0) stEthContract.safeTransfer(to_, stEthAmt_); emit withdrawLog(amount_, to_); }
342,062
./partial_match/42/0xd9BA7ff04243f7FB2Efe5ae5A5A0e12D54e1A723/sources/MasterChef.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. _tokenAToEthSwap should be the _lpTokenSwap.tokenA's swap, _tokenBToEthSwap should be the _lpTokenSwap.tokenB's swap
function add(address _lpTokenSwap, address _tokenAToEthSwap, address _tokenBToEthSwap, bool _withUpdate) public onlyOwner{ if(block.number < stageOneDepositEndBlock){ stageOne.add(_lpTokenSwap, _tokenAToEthSwap, _tokenBToEthSwap); return; } if (_withUpdate) { massUpdatePools(); } IERC20 lpToken = IERC20(_lpTokenSwap); IUniswapV2Pair lpTokenSwap = IUniswapV2Pair(_lpTokenSwap); TokenPairInfo memory tokenAInfo = generateOrcaleInfo(_tokenAToEthSwap, commonToken); TokenPairInfo memory tokenBInfo = generateOrcaleInfo(_tokenBToEthSwap, commonToken); poolInfo.push(PoolInfo({ lpToken: lpToken, lpTokenSwap: lpTokenSwap, lpTokenAmount: 0, usersTotalWeight: 0, accumulativeDividend: 0, oracleWeight: 0, lastCalculateOracleHeight: 0, lastDividendHeight: 0, isInRank: false, tokenAPairInfo: tokenAInfo, tokenBPairInfo: tokenBInfo, standardPairType: PoolStandardPairType.TwoPairStandard })); }
3,323,236
./partial_match/1/0x8378998f3CCB6e2b00e35df41F1F22B1DF49d9A9/sources/ERC20.sol
ERC-677 functionality, can be useful for swapping and wrapping tokens
function transferAndCall(address recipient, uint amount, bytes calldata data) public returns (bool) { bool success = transfer(recipient, amount); if (success){ IERC677Receiver(recipient).onTokenTransfer(msg.sender, amount, data); } return success; }
9,211,370
./full_match/1/0x4A65096Ca0f3A0490AceD01969B0Ed986237adC9/sources/browser/rektcity.sol
Returns the minting state
function isMintingAllowed() public view returns (bool) { return allowMinting; }
9,608,432
./partial_match/3/0xB9E7217Cab612aF97a44E6423b2ee396cDee180b/sources/Bid.sol
require(msg.sender == oracleCallbackAddr);
function __callback(bytes32 _requestId, string memory _result, bool _success) public{ RequestData storage _requestData = requestIdToData[_requestId]; require(_requestData.status); _requestData.status = false; uint256 _amount = safeParseInt(_result, 0); require(_amount != 0); ERC721 candidateContract = ERC721(_requestData.tokenContractAddr); require(candidateContract.safeTransferFrom(_requestData.tokenIdOfOwner, _requestData.bidSender, _requestData.tokenId)); emit LogCallBack(_requestId, _amount, _result, _success); }
5,195,636
./full_match/80001/0xd791d25ca5F798604c307f69f7A690F0B460B57e/sources/contracts/SingleEditionMintable.sol
/ Set ownership to original sender of contract call Set edition id start to be 1 not 0
function initialize( address _owner, string memory _name, string memory _symbol, string memory _description, string memory _animationUrl, bytes32 _animationHash, string memory _imageUrl, bytes32 _imageHash, uint256 _editionSize, uint256 _royaltyBPS ) public initializer { __ERC721_init(_name, _symbol); __Ownable_init(); transferOwnership(_owner); description = _description; animationUrl = _animationUrl; animationHash = _animationHash; imageUrl = _imageUrl; imageHash = _imageHash; editionSize = _editionSize; editionOwnedAddress = new address[](_editionSize); royaltyBPS = _royaltyBPS; atEditionId.increment(); }
9,464,220
pragma solidity ^0.8.4; //import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol"; //import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "./erc721enum.sol"; //import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; //import '@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol'; // import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Full.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Mintable.sol"; interface ContractInterface { function balanceOf(address owner) external view returns (uint256 number); } contract NFZv2 is OwnableUpgradeable, ERC721EnumerableUpgradeable { uint256 constant MAX_INIT_SUPPLY = 4444; uint256 constant MAXSUPPLY = 6666; bool public isPresale; bool public isLaunched; bytes32 private Whitelist_Root; bytes32 private HalfMintRoot; bytes32 private uniCandyRoot; uint256 private value; string baseURI; mapping(address => bool) public preSaleMapping; //Where your zombie goes will be stored on the blockchain //coming in phase 2.0 mapping(uint256 => Locations[]) public passport; struct Locations { string locationName; uint256 locationId; } mapping(address => bool) public claimMapping; uint256 public MINT_PRICE; bytes32 private freeClaimRoot; //init function called on deploy function init( bytes32 wlroot, bytes32 hmroot, string memory _base ) public initializer { isPresale = false; isLaunched = false; Whitelist_Root = wlroot; HalfMintRoot = hmroot; __ERC721_init("Nice Fun Zombies", "NFZ"); __ERC721Enumerable_init(); __Ownable_init(); baseURI = _base; } function giveways(address[] memory freeNFZ) external onlyOwner { uint256 counter = totalSupply(); for (uint256 i = 1; i <= freeNFZ.length; i++) { address winner = freeNFZ[i - 1]; _safeMint(winner, counter + i); } } //owner can mint after deploy function teamMint(uint256 amount) external onlyOwner { uint256 counter = totalSupply(); for (uint256 i = 1; i < amount + 1; i++) { _safeMint(msg.sender, counter + i); } } //to toggle general sale function launchToggle() public onlyOwner { isLaunched = !isLaunched; } //to toggle presale function presaleToggle() public onlyOwner { isPresale = !isPresale; } function setMintPrice(uint256 _price) public onlyOwner { MINT_PRICE = _price; } function claim() public {} function freeClaim( address account, uint256 _mintAmount, bytes32[] calldata proof ) external { require(isLaunched, "Minting is off"); require( MerkleProofUpgradeable.verify(proof, freeClaimRoot, _leaf(account)), "account not part of claim list" ); require( _mintAmount <= (balanceOf(account) * 2), "Trying to claim too many" ); require(_mintAmount < 101); require(!claimMapping[account], "already claimed"); uint256 counter = totalSupply(); for (uint256 i = 1; i < _mintAmount + 1; i++) { _safeMint(account, counter + i); } claimMapping[account] = true; } //general mint function - checks to make sure launch = true; function mint(address account, uint256 _mintAmount) external payable { uint256 counter = totalSupply(); require(isLaunched, "general mint has not started"); require( counter + _mintAmount < MAX_INIT_SUPPLY, "exceeds contract limit" ); require( msg.value >= MINT_PRICE * _mintAmount, "Not enough eth sent: check price" ); require(_mintAmount < 11, "Only mint 10. Leave some for the rest!"); for (uint256 i = 1; i < _mintAmount + 1; i++) { _safeMint(account, counter + i); } } function _leaf(address account) internal pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } function withdraw() public payable onlyOwner { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function contractURI() public pure returns (string memory) { return "https://api.nicefunzombies.io/contract"; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function updateMerkleRoot(string memory rootType, bytes32 root) external onlyOwner { if ( keccak256(abi.encodePacked(rootType)) == keccak256(abi.encodePacked("freeClaimRoot")) ) { freeClaimRoot = root; } else { revert("Incorrect rootType"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * 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 { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProofUpgradeable { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC721EnumerableUpgradeable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer {} // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint16[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds" ); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(uint16(tokenId)); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = uint16(lastTokenId); // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @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 IERC721ReceiverUpgradeable { /** * @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 "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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 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; 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 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; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 IERC165Upgradeable { /** * @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; import "../token/ERC721/extensions/IERC721EnumerableUpgradeable.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
See {IERC721Enumerable-tokenOfOwnerByIndex}./
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; }
92,569
./full_match/4/0x106980Cc2C2E3b4C5599B5DD6fdFa3F607FCe72b/sources/browser/Vault.sol
Asgard calls to transfer to recipient
function asgardTransfer(address to, address asset, uint value, string memory memo) public onlyAsgard { require(asset != address(0), "Ether must be sent from asgard"); require(value <= asgardAllowance[asset], "must not send more than allowance"); asgardAllowance[asset] -= value; ERC20(asset).transfer(to, value); emit Transfer(to, asset, value, memo); }
13,356,979
/** *Submitted for verification at Etherscan.io on 2020-11-05 */ /* website: bns.finance This project is freshly written to change the way ICO is done. BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNNN SSSSSSSSSSSSSSS DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFIIIIIIIIII B::::::::::::::::B N:::::::N N::::::N SS:::::::::::::::S D::::::::::::DDD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I B::::::BBBBBB:::::B N::::::::N N::::::NS:::::SSSSSS::::::S D:::::::::::::::DD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I BB:::::B B:::::BN:::::::::N N::::::NS:::::S SSSSSSS DDD:::::DDDDD:::::DEE::::::EEEEEEEEE::::EFF::::::FFFFFFFFF::::FII::::::II B::::B B:::::BN::::::::::N N::::::NS:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F FFFFFF I::::I B::::B B:::::BN:::::::::::N N::::::NS:::::S D:::::D D:::::DE:::::E F:::::F I::::I B::::BBBBBB:::::B N:::::::N::::N N::::::N S::::SSSS D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I B:::::::::::::BB N::::::N N::::N N::::::N SS::::::SSSSS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I B::::BBBBBB:::::B N::::::N N::::N:::::::N SSS::::::::SS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I B::::B B:::::BN::::::N N:::::::::::N SSSSSS::::S D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I B::::B B:::::BN::::::N N::::::::::N S:::::S D:::::D D:::::DE:::::E F:::::F I::::I B::::B B:::::BN::::::N N:::::::::N S:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F I::::I BB:::::BBBBBB::::::BN::::::N N::::::::NSSSSSSS S:::::S DDD:::::DDDDD:::::DEE::::::EEEEEEEE:::::EFF:::::::FF II::::::II B:::::::::::::::::B N::::::N N:::::::NS::::::SSSSSS:::::S ...... D:::::::::::::::DD E::::::::::::::::::::EF::::::::FF I::::::::I B::::::::::::::::B N::::::N N::::::NS:::::::::::::::SS .::::. D::::::::::::DDD E::::::::::::::::::::EF::::::::FF I::::::::I BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNN SSSSSSSSSSSSSSS ...... DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFF IIIIIIIIII */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /* * @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 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); } /** * @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, "SAO"); 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, "SMO"); 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. * * [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, "IB"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "RR"); } /** * @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, "IBC"); 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), "CNC"); // 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); } } } } /** * @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, "DAB0"); _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, "LF1"); if (returndata.length != 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "LF2"); } } } /** * @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 public _totalSupply; string public _name; string public _symbol; uint8 public _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), "ISA"); require(recipient != address(0), "IRA"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "TIF"); _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), "M0"); _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), "B0"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "BIB"); _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), "IA"); require(spender != address(0), "A0"); _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 { } } contract BnsdLaunchPool is Context { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of a raising pool. struct RaisePoolInfo { IERC20 raiseToken; // Address of raising token contract. uint256 maxTokensPerPerson; // Maximum tokens a user can buy. uint256 totalTokensOnSale; // Total tokens available on offer. uint256 startBlock; // When the sale starts uint256 endBlock; // When the sale ends uint256 totalTokensSold; // Total tokens sold to users so far uint256 tokensDeposited; // Total ICO tokens deposited uint256 votes; // Voted by users address owner; // Owner of the pool bool updateLocked; // No pool info can be updated once this is turned ON bool balanceAdded; // Whether ICO tokens are added in correct amount bool paymentMethodAdded; // Supported currencies added or not string poolName; // Human readable string name of the pool } struct AirdropPoolInfo { uint256 totalTokensAvailable; // Total tokens staked so far. IERC20 airdropToken; // Address of staking LP token. bool airdropExists; } // Info of a raising pool. struct UseCasePoolInfo { uint256 tokensAllocated; // Total tokens available for this use uint256 tokensClaimed; // Total tokens claimed address reserveAdd; // Address where tokens will be released for that usecase. bool tokensDeposited; // No pool info can be updated once this is turned ON bool exists; // Whether reserve already exists for a pool string useName; // Human readable string name of the pool uint256[] unlock_perArray; // Release percent for usecase uint256[] unlock_daysArray; // Release days for usecase } struct DistributionInfo { uint256[] percentArray; // Percentage of tokens to be unlocked every phase uint256[] daysArray; // Days from the endDate when tokens starts getting unlocked } // The BNSD TOKEN! address public timeLock; // Dev address. address public devaddr; // Temp dev address while switching address private potentialAdmin; // To store owner diistribution info after sale ends mapping (uint256 => DistributionInfo) private ownerDistInfo; // To store user distribution info after sale ends mapping (uint256 => DistributionInfo) private userDistInfo; // To store tokens on sale and their rates mapping (uint256 => mapping (address => uint256)) public saleRateInfo; // To store invite codes and corresponding token address and pool owners, INVITE CODE => TOKEN => OWNER => bool mapping (uint256 => mapping (address => mapping (address => bool))) private inviteCodeList; // To store user contribution for a sale - POOL => USER => USDT mapping (uint256 => mapping (address => mapping (address => uint256))) public userDepositInfo; // To store total token promised to a user - POOL => USER mapping (uint256 => mapping (address => uint256)) public userTokenAllocation; // To store total token claimed by a user already mapping (uint256 => mapping (address => uint256)) public userTokenClaimed; // To store total token redeemed by users after sale mapping (uint256 => uint256) public totalTokenClaimed; // To store total token raised by a project - POOL => TOKEN => AMT mapping (uint256 => mapping (address => uint256)) public fundsRaisedSoFar; mapping (uint256 => address) private tempAdmin; // To store total token claimed by a project mapping (uint256 => mapping (address => uint256)) public fundsClaimedSoFar; // To store addresses voted for a project - POOL => USER => BOOL mapping (uint256 => mapping (address => bool)) public userVotes; // No of blocks in a day - 6700 uint256 public constant BLOCKS_PER_DAY = 6700; // Changing to 5 for test cases // Info of each pool on blockchain. RaisePoolInfo[] public poolInfo; // Info of reserve pool of any project - POOL => RESERVE_ADD => USECASEINFO mapping (uint256 => mapping (address => UseCasePoolInfo)) public useCaseInfo; // To store total token reserved mapping (uint256 => uint256) public totalTokenReserved; // To store total reserved claimed mapping (uint256 => uint256) public totalReservedTokenClaimed; // To store list of all sales associated with a token mapping (address => uint256[]) public listSaleTokens; // To store list of all currencies allowed for a sale mapping (uint256 => address[]) public listSupportedCurrencies; // To store list of all reserve addresses for a sale mapping (uint256 => address[]) public listReserveAddresses; // To check if staking is enabled on a token mapping (address => bool) public stakingEnabled; // To get staking weight of a token mapping (address => uint256) public stakingWeight; // To store sum of weight of all staking tokens uint256 public totalStakeWeight; // To store list of staking addresses address[] public stakingPools; // To store stats of staked tokens per sale mapping (uint256 => mapping (address => uint256)) public stakedLPTokensInfo; // To store user staked amount for a sale - POOL => USER => LP_TOKEN mapping (uint256 => mapping (address => mapping (address => uint256))) public userStakeInfo; // To store reward claimed by a user - POOL => USER => BOOL mapping (uint256 => mapping (address => bool)) public rewardClaimed; // To store airdrop claimed by a user - POOL => USER => BOOL mapping (uint256 => mapping (address => bool)) public airdropClaimed; // To store extra airdrop tokens withdrawn by fund raiser - POOL => BOOL mapping (uint256 => bool) public extraAirdropClaimed; // To store airdrop info for a sale mapping (uint256 => AirdropPoolInfo) public airdropInfo; // To store airdrop tokens balance of a user , TOKEN => USER => BAL mapping (address => mapping (address => uint256)) public airdropBalances; uint256 public fee = 300; // To be divided by 1e4 before using it anywhere => 3.00% uint256 public constant rewardPer = 8000; // To be divided by 1e4 before using it anywhere => 80.00% event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Stake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount); event UnStake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount); event MoveStake(address indexed user, address indexed lptoken, uint256 pid, uint256 indexed pidnew, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event WithdrawAirdrop(address indexed user, address indexed token, uint256 amount); event ClaimAirdrop(address indexed user, address indexed token, uint256 amount); event AirdropDeposit(address indexed user, address indexed token, uint256 indexed pid, uint256 amount); event AirdropExtraWithdraw(address indexed user, address indexed token, uint256 indexed pid, uint256 amount); event Voted(address indexed user, uint256 indexed pid); constructor() public { devaddr = _msgSender(); } modifier onlyAdmin() { require(devaddr == _msgSender(), "ND"); _; } modifier onlyAdminOrTimeLock() { require((devaddr == _msgSender() || timeLock == _msgSender()), "ND"); _; } function setTimeLockAdd(address _add) public onlyAdmin { timeLock = _add; } function poolLength() external view returns (uint256) { return poolInfo.length; } function getListOfSale(address _token) external view returns (uint256[] memory) { return listSaleTokens[_token]; } function getUserDistPercent(uint256 _pid) external view returns (uint256[] memory) { return userDistInfo[_pid].percentArray; } function getUserDistDays(uint256 _pid) external view returns (uint256[] memory) { return userDistInfo[_pid].daysArray; } function getReserveUnlockPercent(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) { return useCaseInfo[_pid][_reserveAdd].unlock_perArray; } function getReserveUnlockDays(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) { return useCaseInfo[_pid][_reserveAdd].unlock_daysArray; } function getUserDistBlocks(uint256 _pid) external view returns (uint256[] memory) { uint256[] memory daysArray = userDistInfo[_pid].daysArray; uint256 endPool = poolInfo[_pid].endBlock; for(uint256 i=0; i<daysArray.length; i++){ daysArray[i] = (daysArray[i].mul(BLOCKS_PER_DAY)).add(endPool); } return daysArray; } function getOwnerDistPercent(uint256 _pid) external view returns (uint256[] memory) { return ownerDistInfo[_pid].percentArray; } function getOwnerDistDays(uint256 _pid) external view returns (uint256[] memory) { return ownerDistInfo[_pid].daysArray; } // Add a new token sale to the pool. Can only be called by the person having the invite code. function addNewPool(uint256 totalTokens, uint256 maxPerPerson, uint256 startBlock, uint256 endBlock, string memory namePool, IERC20 tokenAddress, uint256 _inviteCode) external returns (uint256) { require(endBlock > startBlock, "ESC"); // END START COMPARISON FAILED require(startBlock > block.number, "TLS"); // TIME LIMIT START SALE require(maxPerPerson !=0 && totalTokens!=0, "IIP"); // INVALID INDIVIDUAL PER PERSON require(inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()]==true,"IIC"); // INVALID INVITE CODE poolInfo.push(RaisePoolInfo({ raiseToken: tokenAddress, maxTokensPerPerson: maxPerPerson, totalTokensOnSale: totalTokens, startBlock: startBlock, endBlock: endBlock, poolName: namePool, updateLocked: false, owner: _msgSender(), totalTokensSold: 0, balanceAdded: false, tokensDeposited: 0, paymentMethodAdded: false, votes: 0 })); uint256 poolId = (poolInfo.length - 1); listSaleTokens[address(tokenAddress)].push(poolId); // This makes the invite code claimed inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()] = false; return poolId; } function _checkSumArray(uint256[] memory _percentArray) internal pure returns (bool) { uint256 _sum; for (uint256 i = 0; i < _percentArray.length; i++) { _sum = _sum.add(_percentArray[i]); } return (_sum==10000); } function _checkValidDaysArray(uint256[] memory _daysArray) internal pure returns (bool) { uint256 _lastDay = _daysArray[0]; for (uint256 i = 1; i < _daysArray.length; i++) { if(_lastDay < _daysArray[i]){ _lastDay = _daysArray[i]; } else { return false; } } return true; } function _checkUpdateAllowed(uint256 _pid) internal view{ RaisePoolInfo storage pool = poolInfo[_pid]; require(pool.updateLocked == false, "CT2"); // CRITICAL TERMINATION 2 require(pool.owner==_msgSender(), "OAU"); // OWNER AUTHORIZATION FAILED require(pool.startBlock > block.number, "CT"); // CRITICAL TERMINATION } // Add rule for funds locking after sale function updateUserDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external { require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH _checkUpdateAllowed(_pid); require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING userDistInfo[_pid] = DistributionInfo({ percentArray: _percentArray, daysArray: _daysArray }); } // Add rule for funds unlocking of the fund raiser after sale function updateOwnerDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external { require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH _checkUpdateAllowed(_pid); require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING ownerDistInfo[_pid] = DistributionInfo({ percentArray: _percentArray, daysArray: _daysArray }); } // Lock sale detail changes in future function lockPool(uint256 _pid) external { require(poolInfo[_pid].paymentMethodAdded==true, "CP"); // CHECK PAYMENT METHOD FAILED _checkUpdateAllowed(_pid); poolInfo[_pid].updateLocked = true; } // Add supported currencies and their rate w.r.t token on sale // rateToken = price of one satoshi of the token in terms of token to be raised * 1e18 // 1 BNSD = 0.00021 ETH => 1e18 BNSD Satoshi = 0.00021 * 1e18 ETH satoshi => 1 BNSD Satoshi = 0.00021 ETH satoshi => rateToken = 0.00021 * 1e18 = 21 * 1e13 // rateToken for BNSD/ETH pair = 21 * 1e13; function addSupportedCurrencies(uint256 _pid, address _tokenRaise, uint256 rateToken) external { _checkUpdateAllowed(_pid); require(rateToken!=0, "IR"); // INVALID RATE require(_tokenRaise!=address(poolInfo[_pid].raiseToken), "IT"); // INVALIID PURCHASE TOKEN if(address(this).balance == 0){ //inject PRESENT ETHER listSupportedCurrencies[_pid].push(_tokenRaise); } saleRateInfo[_pid][_tokenRaise] = rateToken; poolInfo[_pid].paymentMethodAdded = true; } function getSupportedCurrencies(uint256 _pid) external view returns (address[] memory) { return listSupportedCurrencies[_pid]; } function _checkUpdateReserveAllowed(uint256 _pid, address _resAdd) internal view returns (bool) { UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd]; return (poolU.exists == false || poolU.tokensDeposited == false); // if(poolU.exists == false || poolU.tokensDeposited == false){ // return true; // } // return false; } function addReservePool(uint256 _pid, address _reserveAdd, string memory _nameReserve, uint256 _totalTokens, uint256[] memory _perArray, uint256[] memory _daysArray) external { _checkUpdateAllowed(_pid); require(_checkUpdateReserveAllowed(_pid, _reserveAdd) == true, "UB"); // UPDATE RESERVE FAILED require(_checkSumArray(_perArray), "SE"); // SUM OF PERCENT INVALID require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING require(_perArray.length==_daysArray.length, "IAL"); // INVALID ARRAY LENGTH if(useCaseInfo[_pid][_reserveAdd].exists == false){ listReserveAddresses[_pid].push(_reserveAdd); } useCaseInfo[_pid][_reserveAdd] = UseCasePoolInfo({ reserveAdd: _reserveAdd, useName: _nameReserve, tokensAllocated: _totalTokens, unlock_perArray: _perArray, unlock_daysArray: _daysArray, tokensDeposited: false, tokensClaimed: 0, exists: true }); } function getReserveAddresses(uint256 _pid) external view returns (address[] memory) { return listReserveAddresses[_pid]; } function tokensPurchaseAmt(uint256 _pid, address _tokenAdd, uint256 amt) public view returns (uint256) { uint256 rateToken = saleRateInfo[_pid][_tokenAdd]; require(rateToken!=0, "NAT"); // NOT AVAILABLE TOKEN return (amt.mul(1e18)).div(rateToken); } // Check if user can deposit specfic amount of funds to the pool function _checkDepositAllowed(uint256 _pid, address _tokenAdd, uint256 _amt) internal view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; uint256 userBought = userTokenAllocation[_pid][_msgSender()]; uint256 purchasePossible = tokensPurchaseAmt(_pid, _tokenAdd, _amt); require(pool.balanceAdded == true, "NA"); // NOT AVAILABLE require(pool.startBlock <= block.number, "NT1"); // NOT AVAILABLE TIME 1 require(pool.endBlock >= block.number, "NT2"); // NOT AVAILABLE TIME 2 require(pool.totalTokensSold.add(purchasePossible) <= pool.totalTokensOnSale, "PLE"); // POOL LIMIT EXCEEDED require(userBought.add(purchasePossible) <= pool.maxTokensPerPerson, "ILE"); // INDIVIDUAL LIMIT EXCEEDED return purchasePossible; } // Check max a user can deposit right now function getMaxDepositAllowed(uint256 _pid, address _tokenAdd, address _user) external view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; uint256 maxBuyPossible = (pool.maxTokensPerPerson).sub(userTokenAllocation[_pid][_user]); uint256 maxBuyPossiblePoolLimit = (pool.totalTokensOnSale).sub(pool.totalTokensSold); if(maxBuyPossiblePoolLimit < maxBuyPossible){ maxBuyPossible = maxBuyPossiblePoolLimit; } if(block.number >= pool.startBlock && block.number <= pool.endBlock && pool.balanceAdded == true){ uint256 rateToken = saleRateInfo[_pid][_tokenAdd]; return (maxBuyPossible.mul(rateToken).div(1e18)); } else { return 0; } } // Check if deposit is enabled for a pool function checkDepositEnabled(uint256 _pid) external view returns (bool){ RaisePoolInfo storage pool = poolInfo[_pid]; if(pool.balanceAdded == true && pool.startBlock <= block.number && pool.endBlock >= block.number && pool.totalTokensSold <= pool.totalTokensOnSale && pool.paymentMethodAdded==true){ return true; } else { return false; } } // Deposit ICO tokens to start a pool for ICO. function depositICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external { RaisePoolInfo storage pool = poolInfo[_pid]; address msgSender = _msgSender(); require(_tokenAdd == pool.raiseToken, "NOT"); // NOT VALID TOKEN require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER require(block.number < pool.endBlock, "NT"); // No point adding tokens after sale has ended - Possible deadlock case _tokenAdd.safeTransferFrom(msgSender, address(this), _amount); pool.tokensDeposited = (pool.tokensDeposited).add(_amount); if(pool.tokensDeposited >= pool.totalTokensOnSale){ pool.balanceAdded = true; } emit Deposit(msgSender, _pid, _amount); } // Deposit Airdrop tokens anytime before end of the sale. function depositAirdropTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external { RaisePoolInfo storage pool = poolInfo[_pid]; require(block.number < pool.endBlock, "NT"); // NOT VALID TIME AirdropPoolInfo storage airdrop = airdropInfo[_pid]; require((_tokenAdd == airdrop.airdropToken || airdrop.airdropExists==false), "NOT"); // NOT VALID TOKEN require(_msgSender() == pool.owner || _msgSender() == devaddr , "NAU"); // NOT AUTHORISED USER _tokenAdd.safeTransferFrom(_msgSender(), address(this), _amount); airdrop.totalTokensAvailable = (airdrop.totalTokensAvailable).add(_amount); if(!airdrop.airdropExists){ airdrop.airdropToken = _tokenAdd; airdrop.airdropExists = true; } emit AirdropDeposit(_msgSender(), address(_tokenAdd), _pid, _amount); } // Withdraw extra airdrop tokens - Possible only if no one added liquidity to one of the pools function withdrawExtraAirdropTokens(uint256 _pid) external { require(extraAirdropClaimed[_pid]==false, "NA"); // NOT AVAILABLE RaisePoolInfo storage pool = poolInfo[_pid]; require(block.number > pool.endBlock, "NSE"); // SALE NOT ENDED address msgSender = _msgSender(); require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER uint256 extraTokens = calculateExtraAirdropTokens(_pid); require(extraTokens!=0, "NAT"); // NOT AVAILABLE TOKEN extraAirdropClaimed[_pid] = true; airdropInfo[_pid].airdropToken.safeTransfer(msgSender, extraTokens); emit AirdropExtraWithdraw(msg.sender, address(airdropInfo[_pid].airdropToken), _pid, extraTokens); } function calculateExtraAirdropTokens(uint256 _pid) public view returns (uint256){ if(extraAirdropClaimed[_pid] == true) return 0; uint256 _totalTokens; for (uint256 i=0; i<stakingPools.length; i++){ uint256 stake = stakedLPTokensInfo[_pid][stakingPools[i]]; if(address(this).balance == 0){ //inject PRESENT ETHER _totalTokens = _totalTokens.add(((stakingWeight[stakingPools[i]]).mul(airdropInfo[_pid].totalTokensAvailable)).div(totalStakeWeight)); } } return _totalTokens; } // Deposit LP tokens for a sale. function stakeLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external { require(stakingEnabled[address(_lpAdd)]==true, "NST"); // NOT STAKING TOKEN RaisePoolInfo storage pool = poolInfo[_pid]; require(block.number < pool.startBlock, "NT"); // NOT VALID TIME address msgSender = _msgSender(); _lpAdd.safeTransferFrom(msgSender, address(this), _amount); stakedLPTokensInfo[_pid][address(_lpAdd)] = (stakedLPTokensInfo[_pid][address(_lpAdd)]).add(_amount); userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).add(_amount); emit Stake(msg.sender, address(_lpAdd), _pid, _amount); } // Withdraw LP tokens from a sale after it's over => Automatically claims rewards and airdrops also function withdrawLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external { require(stakingEnabled[address(_lpAdd)]==true, "NAT"); // NOT AUTHORISED TOKEN RaisePoolInfo storage pool = poolInfo[_pid]; require(block.number > pool.endBlock, "SE"); // SALE NOT ENDED address msgSender = _msgSender(); claimRewardAndAirdrop(_pid); userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).sub(_amount); _lpAdd.safeTransfer(msgSender, _amount); emit UnStake(msg.sender, address(_lpAdd), _pid, _amount); } // Withdraw airdrop tokens accumulated over one or more than one sale. function withdrawAirdropTokens(IERC20 _token, uint256 _amount) external { address msgSender = _msgSender(); airdropBalances[address(_token)][msgSender] = (airdropBalances[address(_token)][msgSender]).sub(_amount); _token.safeTransfer(msgSender, _amount); emit WithdrawAirdrop(msgSender, address(_token), _amount); } // Move LP tokens from one sale to another directly => Automatically claims rewards and airdrops also function moveLPTokens(uint256 _pid, uint256 _newpid, uint256 _amount, address _lpAdd) external { require(stakingEnabled[_lpAdd]==true, "NAT1"); // NOT AUTHORISED TOKEN 1 RaisePoolInfo storage poolOld = poolInfo[_pid]; RaisePoolInfo storage poolNew = poolInfo[_newpid]; require(block.number > poolOld.endBlock, "NUA"); // OLD SALE NOT ENDED require(block.number < poolNew.startBlock, "NSA"); // SALE START CHECK FAILED address msgSender = _msgSender(); claimRewardAndAirdrop(_pid); userStakeInfo[_pid][msgSender][_lpAdd] = (userStakeInfo[_pid][msgSender][_lpAdd]).sub(_amount); userStakeInfo[_newpid][msgSender][_lpAdd] = (userStakeInfo[_newpid][msgSender][_lpAdd]).add(_amount); emit MoveStake(msg.sender, _lpAdd, _pid, _newpid, _amount); } function claimRewardAndAirdrop(uint256 _pid) public { RaisePoolInfo storage pool = poolInfo[_pid]; require(block.number > pool.endBlock, "SE"); // SUM INVALID _claimReward(_pid, _msgSender()); _claimAirdrop(_pid, _msgSender()); } function _claimReward(uint256 _pid, address _user) internal { if (rewardClaimed[_pid][_user]==false){ rewardClaimed[_pid][_user] = true; for (uint256 i=0; i<stakingPools.length; i++){ for(uint256 j=0; j<listSupportedCurrencies[_pid].length; j++){ uint256 _tokenAmt = getReward(_pid, _user, stakingPools[i], listSupportedCurrencies[_pid][j]); _creditAirdrop(_user, listSupportedCurrencies[_pid][j], _tokenAmt); } } } } function _claimAirdrop(uint256 _pid, address _user) internal { if (airdropClaimed[_pid][_user]==false){ airdropClaimed[_pid][_user] = true; address _airdropToken = address(airdropInfo[_pid].airdropToken); uint256 _tokenAmt = 0; for (uint256 i=0; i<stakingPools.length; i++){ _tokenAmt = _tokenAmt.add(getAirdrop(_pid, _user, stakingPools[i])); } if(_tokenAmt !=0){ _creditAirdrop(_user, _airdropToken, _tokenAmt); } } } function _creditAirdrop(address _user, address _token, uint256 _amt) internal { airdropBalances[_token][_user] = (airdropBalances[_token][_user]).add(_amt); emit ClaimAirdrop(_user, _token, _amt); } function getReward(uint256 _pid, address _user, address _lpAdd, address _token) public view returns (uint256) { uint256 stake = stakedLPTokensInfo[_pid][_lpAdd]; if(address(this).balance==0) return 0; //inject PRESENT ETHER uint256 _multipliedData = (userStakeInfo[_pid][_user][_lpAdd]).mul(fundsRaisedSoFar[_pid][_token]); _multipliedData = (_multipliedData).mul(rewardPer).mul(fee).mul(stakingWeight[_lpAdd]); return (((_multipliedData).div(stake)).div(1e8)).div(totalStakeWeight); } function getAirdrop(uint256 _pid, address _user, address _lpAdd) public view returns (uint256) { uint256 _userStaked = userStakeInfo[_pid][_user][_lpAdd]; uint256 _totalStaked = stakedLPTokensInfo[_pid][_lpAdd]; if(address(this).balance==0) return 0; //inject PRESENT ETHER return ((((_userStaked).mul(airdropInfo[_pid].totalTokensAvailable).mul(stakingWeight[_lpAdd])).div(_totalStaked))).div(totalStakeWeight); } // Deposit ICO tokens for a use case as reserve. function depositReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd, address _resAdd) external { RaisePoolInfo storage pool = poolInfo[_pid]; UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd]; address msgSender = _msgSender(); require(_tokenAdd == pool.raiseToken, "NOT"); // NOT AUTHORISED TOKEN require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER require(poolU.tokensDeposited == false, "DR"); // TOKENS NOT DEPOSITED require(poolU.tokensAllocated == _amount && _amount!=0, "NA"); // NOT AVAILABLE require(block.number < pool.endBlock, "CRN"); // CANNOT_RESERVE_NOW to avoid deadlocks _tokenAdd.safeTransferFrom(msgSender, address(this), _amount); totalTokenReserved[_pid] = (totalTokenReserved[_pid]).add(_amount); poolU.tokensDeposited = true; emit Deposit(msg.sender, _pid, _amount); } // Withdraw extra unsold ICO tokens or extra deposited tokens. function withdrawExtraICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external { RaisePoolInfo storage pool = poolInfo[_pid]; address msgSender = _msgSender(); require(_tokenAdd == pool.raiseToken, "NT"); // NOT AUTHORISED TOKEN require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER require(block.number > pool.endBlock, "NA"); // NOT AVAILABLE TIME uint256 _amtAvail = pool.tokensDeposited.sub(pool.totalTokensSold); require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE TOKEN pool.tokensDeposited = (pool.tokensDeposited).sub(_amount); _tokenAdd.safeTransfer(msgSender, _amount); emit Withdraw(msgSender, _pid, _amount); } // Fetch extra ICO tokens available. function fetchExtraICOTokens(uint256 _pid) external view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; return pool.tokensDeposited.sub(pool.totalTokensSold); } // Deposit tokens to a pool for ICO. function deposit(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external { address msgSender = _msgSender(); uint256 _buyThisStep = _checkDepositAllowed(_pid, address(_tokenAdd), _amount); // require(_buyThisStep >= _amount, "CDE"); _tokenAdd.safeTransferFrom(msgSender, address(this), _amount); userDepositInfo[_pid][msgSender][address(_tokenAdd)] = userDepositInfo[_pid][msgSender][address(_tokenAdd)].add(_amount); userTokenAllocation[_pid][msgSender] = userTokenAllocation[_pid][msgSender].add(_buyThisStep); poolInfo[_pid].totalTokensSold = poolInfo[_pid].totalTokensSold.add(_buyThisStep); fundsRaisedSoFar[_pid][address(_tokenAdd)] = fundsRaisedSoFar[_pid][address(_tokenAdd)].add(_amount); emit Deposit(msg.sender, _pid, _amount); } // Vote your favourite ICO project. function voteProject(uint256 _pid) external { address msgSender = _msgSender(); require(userVotes[_pid][msgSender]==false,"AVO"); // ALREADY VOTED require(poolInfo[_pid].endBlock >= block.number,"CVO"); // CANNOT VOTE NOW userVotes[_pid][msgSender] = true; poolInfo[_pid].votes = (poolInfo[_pid].votes).add(1); emit Voted(msgSender, _pid); } function _calculatePerAvailable(uint256[] memory _daysArray, uint256[] memory _percentArray, uint256 blockEnd) internal view returns (uint256) { uint256 _defaultPer = 10000; uint256 _perNow; if(address(this).balance==0){ //inject PRESENT ETHER return _defaultPer; } uint256 daysDone = ((block.number).sub(blockEnd)).div(BLOCKS_PER_DAY); for (uint256 i = 0; i < _daysArray.length; i++) { if(_daysArray[i] <= daysDone){ _perNow = _perNow.add(_percentArray[i]); } else { break; } } return _perNow; } function _getPercentAvailable(uint256 _pid, uint256 blockEnd) internal view returns (uint256){ DistributionInfo storage distInfo = userDistInfo[_pid]; uint256[] storage _percentArray = distInfo.percentArray; uint256[] storage _daysArray = distInfo.daysArray; return _calculatePerAvailable(_daysArray, _percentArray, blockEnd); } // Check amount of ICO tokens withdrawable by user till now - public function amountAvailToWithdrawUser(uint256 _pid, address _user) public view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; if(pool.endBlock < block.number){ uint256 percentAvail = _getPercentAvailable(_pid, pool.endBlock); return ((percentAvail).mul(userTokenAllocation[_pid][_user]).div(10000)).sub(userTokenClaimed[_pid][_user]); } else { return 0; } } // Withdraw ICO tokens after sale is over based on distribution rules. function withdrawUser(uint256 _pid, uint256 _amount) external { RaisePoolInfo storage pool = poolInfo[_pid]; address msgSender = _msgSender(); uint256 _amtAvail = amountAvailToWithdrawUser(_pid, msgSender); require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN userTokenClaimed[_pid][msgSender] = userTokenClaimed[_pid][msgSender].add(_amount); totalTokenClaimed[_pid] = totalTokenClaimed[_pid].add(_amount); pool.raiseToken.safeTransfer(msgSender, _amount); emit Withdraw(msgSender, _pid, _amount); } function _getPercentAvailableFundRaiser(uint256 _pid, uint256 blockEnd) internal view returns (uint256){ DistributionInfo storage distInfo = ownerDistInfo[_pid]; uint256[] storage _percentArray = distInfo.percentArray; uint256[] storage _daysArray = distInfo.daysArray; return _calculatePerAvailable(_daysArray, _percentArray, blockEnd); } // Check amount of ICO tokens withdrawable by user till now function amountAvailToWithdrawFundRaiser(uint256 _pid, IERC20 _tokenAdd) public view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; if(pool.endBlock < block.number){ uint256 percentAvail = _getPercentAvailableFundRaiser(_pid, pool.endBlock); return (((percentAvail).mul(fundsRaisedSoFar[_pid][address(_tokenAdd)]).div(10000))).sub(fundsClaimedSoFar[_pid][address(_tokenAdd)]); } else { return 0; } } function _getPercentAvailableReserve(uint256 _pid, uint256 blockEnd, address _resAdd) internal view returns (uint256){ UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd]; uint256[] storage _percentArray = poolU.unlock_perArray; uint256[] storage _daysArray = poolU.unlock_daysArray; return _calculatePerAvailable(_daysArray, _percentArray, blockEnd); } // Check amount of ICO tokens withdrawable by reserve user till now function amountAvailToWithdrawReserve(uint256 _pid, address _resAdd) public view returns (uint256){ RaisePoolInfo storage pool = poolInfo[_pid]; UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd]; if(pool.endBlock < block.number){ uint256 percentAvail = _getPercentAvailableReserve(_pid, pool.endBlock, _resAdd); return ((percentAvail).mul(poolU.tokensAllocated).div(10000)).sub(poolU.tokensClaimed); } else { return 0; } } // Withdraw ICO tokens for various use cases as per the schedule promised on provided address. function withdrawReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external { UseCasePoolInfo storage poolU = useCaseInfo[_pid][_msgSender()]; require(poolU.reserveAdd == _msgSender(), "NAUTH"); // NOT AUTHORISED USER require(_tokenAdd == poolInfo[_pid].raiseToken, "NT"); // NOT AUTHORISED TOKEN uint256 _amtAvail = amountAvailToWithdrawReserve(_pid, _msgSender()); require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE USER poolU.tokensClaimed = poolU.tokensClaimed.add(_amount); totalTokenReserved[_pid] = totalTokenReserved[_pid].sub(_amount); totalReservedTokenClaimed[_pid] = totalReservedTokenClaimed[_pid].add(_amount); _tokenAdd.safeTransfer(_msgSender(), _amount); emit Withdraw(_msgSender(), _pid, _amount); } // Withdraw raised funds after sale is over as per the schedule promised function withdrawFundRaiser(uint256 _pid, uint256 _amount, IERC20 _tokenAddress) external { RaisePoolInfo storage pool = poolInfo[_pid]; require(pool.owner == _msgSender(), "NAUTH"); // NOT AUTHORISED USER uint256 _amtAvail = amountAvailToWithdrawFundRaiser(_pid, _tokenAddress); require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN uint256 _fee = ((_amount).mul(fee)).div(1e4); uint256 _actualTransfer = _amtAvail.sub(_fee); uint256 _feeDev = (_fee).mul(10000 - rewardPer).div(1e4); // Remaining tokens for reward mining fundsClaimedSoFar[_pid][address(_tokenAddress)] = fundsClaimedSoFar[_pid][address(_tokenAddress)].add(_amount); _tokenAddress.safeTransfer(_msgSender(), _actualTransfer); _tokenAddress.safeTransfer(devaddr, _feeDev); emit Withdraw(_msgSender(), _pid, _actualTransfer); emit Withdraw(devaddr, _pid, _feeDev); } // Update dev address by initiating with the previous dev. function changeDev(address _newowner) external onlyAdmin { potentialAdmin = _newowner; } function becomeDev() external { require(potentialAdmin == msg.sender, "NA"); // NOT ALLOWED devaddr = msg.sender; } // Update temp pool owner address by initiating with the previous pool owner. function changePoolOwner(uint256 _pid, address _newowner) external { require(_msgSender()==poolInfo[_pid].owner, "OA"); // NOT AUTHORISED USER tempAdmin[_pid] = _newowner; } // Claim pool ownership with new address function becomePoolOwner(uint256 _pid) external { if (tempAdmin[_pid] == _msgSender()) poolInfo[_pid].owner = _msgSender(); } // Update fee, can never be more than 3%. function changeFee(uint256 _fee) external onlyAdmin{ require(_fee <= 300, "MAX3"); // MAX FEE POSSIBLE fee = _fee; } // To generate a new invite code function generateNewCode(address _token, address _poolOwner) external onlyAdminOrTimeLock returns (uint256) { uint256 inviteCode = block.number; inviteCodeList[inviteCode][_token][_poolOwner] = true; return inviteCode; } // To invalidate an invite code function invalidateOldCode(uint256 _inviteCode, address _token, address _poolOwner) external onlyAdmin { inviteCodeList[_inviteCode][_token][_poolOwner] = false; } // To add or update a staking pool with weight function addStakingPool(address _token, uint256 _weight) external onlyAdmin { if(stakingEnabled[_token]==false){ stakingPools.push(_token); stakingEnabled[_token] = true; } totalStakeWeight = totalStakeWeight.sub(stakingWeight[_token]).add(_weight); stakingWeight[_token] = _weight; } }
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), "IA"); require(spender != address(0), "A0"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
1,045,184
./full_match/1/0xb8d379c83A10b073565bD486Ea87147E7117B025/sources/contracts/facets/Basket/BasketFacet.sol
Enforce minimum to avoid rounding errors; (Minimum value is the same as in Balancer)
function addToken(address _token) external override protectedCall { LibBasketStorage.BasketStorage storage bs = LibBasketStorage.basketStorage(); require(!bs.inPool[_token], "TOKEN_ALREADY_IN_POOL"); require(balance(_token) >= MIN_AMOUNT, "BALANCE_TOO_SMALL"); bs.inPool[_token] = true; bs.tokens.push(IERC20(_token)); emit TokenAdded(_token); }
17,123,486
pragma solidity ^0.4.23; import "./SafeMath.sol"; contract Membership { using SafeMath for uint256; // 用enum宣告列舉型別 enum Class {Basic, VIP, VVIP} // 用struct宣告自定義結構 struct Member { string name; uint256 point; Class class; } // 使用constant宣告固定常數 // array, struct, mapping 不支援constant宣告 uint256 constant public rate = 100; mapping(address => Member) public members; modifier nextClass() { _; if (members[msg.sender].point >= 1000) { if (uint256(members[msg.sender].class) != 2) { members[msg.sender].class = Class.VVIP; } } else if (members[msg.sender].point >= 500) { if (uint256(members[msg.sender].class) != 1) { members[msg.sender].class = Class.VIP; } } } function register ( string name ) public { require( // string資料型別沒有length也無法用索引取得某個位置的字 // string s = 'something'; // s.length; // 編譯錯誤,沒有length // s[0]; // 編譯錯誤,無法用索引取得某個位置的字 // // 但實際上string與bytes資料型別相同,這兩者都是陣列array // string是動態長度的UTF-8資料陣列 // bytes就是byte[],bytes支援length以及索引取得某個位置的byte // 因型別相同,string可轉換為bytes,以間接支援length以及索引存取 // string s = 'something'; // bytes(s).length; // 取得s長度,回傳9 // bytes(s)[0]; // 用索引取得第一個以UTF-8編碼的byte,回傳's' // // 透過string與bytes轉換的技巧取得string長度,未初始化的string長度為0 bytes(members[msg.sender].name).length == 0 // 以本例來說,其實只需要檢查name && members[msg.sender].point == 0 // enum列舉型別可轉換為uint,取得當前索引值 // 未初始化的enum索引值為0 && uint256(members[msg.sender].class) == 0, "已註冊過會員" ); require( bytes(name).length > 0, "會員名稱為必填欄位" ); // 初始化struct,並將其加入mapping // 另一種struct初始化寫法,差異點為參數順序必須正確: // Member(name, 0, Class.Basic); members[msg.sender] = Member({ class: Class.Basic, name: name, point: 0 }); } function unregister() public { require( bytes(members[msg.sender].name).length > 0, "未註冊過會員" ); // 用delete關鍵詞刪除區塊鏈上的儲存狀態 // 以太坊將以退回Gas鼓勵開發者使用delete釋放區塊鏈上的儲存狀態 // delete的對象可以是各個變數,但是無法delete整個mapping // mapping中的內容四散為區塊資料,因無法也沒有記住四散的區塊位置,所以無法刪除mapping // 但可以delete各別mapping內個別的元素 // 若刪除的對象是struct,則struct內非mapping的成員也會被刪除 delete members[msg.sender]; } function shop( uint256 value ) public nextClass { uint256 point = value.div(rate); members[msg.sender].point = members[msg.sender].point.add(point); } }
用delete關鍵詞刪除區塊鏈上的儲存狀態 以太坊將以退回Gas鼓勵開發者使用delete釋放區塊鏈上的儲存狀態 delete的對象可以是各個變數,但是無法delete整個mapping mapping中的內容四散為區塊資料,因無法也沒有記住四散的區塊位置,所以無法刪除mapping 但可以delete各別mapping內個別的元素 若刪除的對象是struct,則struct內非mapping的成員也會被刪除
function unregister() public { require( bytes(members[msg.sender].name).length > 0, "未註冊過會員" ); delete members[msg.sender]; }
12,858,400
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TradingAction.sol"; import "./ActionGuards.sol"; import "./nTokenMintAction.sol"; import "./nTokenRedeemAction.sol"; import "../SettleAssetsExternal.sol"; import "../FreeCollateralExternal.sol"; import "../../math/SafeInt256.sol"; import "../../global/StorageLayoutV1.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/AccountContextHandler.sol"; import "../../../interfaces/notional/NotionalCallback.sol"; contract BatchAction is StorageLayoutV1, ActionGuards { using BalanceHandler for BalanceState; using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; using SafeInt256 for int256; /// @notice Executes a batch of balance transfers including minting and redeeming nTokens. /// @param account the account for the action /// @param actions array of balance actions to take, must be sorted by currency id /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange /// @dev auth:msg.sender auth:ERC1155 function batchBalanceAction(address account, BalanceAction[] calldata actions) external payable nonReentrant { require(account == msg.sender || msg.sender == address(this), "Unauthorized"); requireValidAccount(account); // Return any settle amounts here to reduce the number of storage writes to balances AccountContext memory accountContext = _settleAccountIfRequired(account); BalanceState memory balanceState; for (uint256 i = 0; i < actions.length; i++) { BalanceAction calldata action = actions[i]; // msg.value will only be used when currency id == 1, referencing ETH. The requirement // to sort actions by increasing id enforces that msg.value will only be used once. if (i > 0) { require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions"); } // Loads the currencyId into balance state balanceState.loadBalanceState(account, action.currencyId, accountContext); _executeDepositAction( account, balanceState, action.actionType, action.depositActionAmount ); _calculateWithdrawActionAndFinalize( account, accountContext, balanceState, action.withdrawAmountInternalPrecision, action.withdrawEntireCashBalance, action.redeemToUnderlying ); } _finalizeAccountContext(account, accountContext); } /// @notice Executes a batch of balance transfers and trading actions /// @param account the account for the action /// @param actions array of balance actions with trades to take, must be sorted by currency id /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity, /// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued /// @dev auth:msg.sender auth:ERC1155 function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions) external payable nonReentrant { require(account == msg.sender || msg.sender == address(this), "Unauthorized"); requireValidAccount(account); AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions); _finalizeAccountContext(account, accountContext); } /// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This /// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform /// other actions on behalf of the user. /// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract /// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM /// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting /// and will mainly be used for contracts that make migrating assets a better user experience. /// @param account the account that will take all the actions /// @param actions array of balance actions with trades to take, must be sorted by currency id /// @param callbackData arbitrary bytes to be passed backed to the caller in the callback /// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity, /// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued /// @dev auth:authorizedCallbackContract function batchBalanceAndTradeActionWithCallback( address account, BalanceActionWithTrades[] calldata actions, bytes calldata callbackData ) external payable { // NOTE: Re-entrancy is allowed for authorized callback functions. require(authorizedCallbackContract[msg.sender], "Unauthorized"); requireValidAccount(account); AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions); accountContext.setAccountContext(account); // Be sure to set the account context before initiating the callback, all stateful updates // have been finalized at this point so we are safe to issue a callback. This callback may // re-enter Notional safely to deposit or take other actions. NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData); if (accountContext.hasDebt != 0x00) { // NOTE: this method may update the account context to turn off the hasDebt flag, this // is ok because the worst case would be causing an extra free collateral check when it // is not required. This check will be entered if the account hasDebt prior to the callback // being triggered above, so it will happen regardless of what the callback function does. FreeCollateralExternal.checkFreeCollateralAndRevert(account); } } function _batchBalanceAndTradeAction( address account, BalanceActionWithTrades[] calldata actions ) internal returns (AccountContext memory) { AccountContext memory accountContext = _settleAccountIfRequired(account); BalanceState memory balanceState; // NOTE: loading the portfolio state must happen after settle account to get the // correct portfolio, it will have changed if the account is settled. PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); for (uint256 i = 0; i < actions.length; i++) { BalanceActionWithTrades calldata action = actions[i]; // msg.value will only be used when currency id == 1, referencing ETH. The requirement // to sort actions by increasing id enforces that msg.value will only be used once. if (i > 0) { require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions"); } // Loads the currencyId into balance state balanceState.loadBalanceState(account, action.currencyId, accountContext); // Does not revert on invalid action types here, they also have no effect. _executeDepositAction( account, balanceState, action.actionType, action.depositActionAmount ); if (action.trades.length > 0) { int256 netCash; if (accountContext.isBitmapEnabled()) { require( accountContext.bitmapCurrencyId == action.currencyId, "Invalid trades for account" ); bool didIncurDebt; (netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, action.trades ); if (didIncurDebt) { accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt; } } else { // NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch // because we want to only write to storage once after all trades are completed (portfolioState, netCash) = TradingAction.executeTradesArrayBatch( account, action.currencyId, portfolioState, action.trades ); } // If the account owes cash after trading, ensure that it has enough if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg()); balanceState.netCashChange = balanceState.netCashChange.add(netCash); } _calculateWithdrawActionAndFinalize( account, accountContext, balanceState, action.withdrawAmountInternalPrecision, action.withdrawEntireCashBalance, action.redeemToUnderlying ); } // Update the portfolio state if bitmap is not enabled. If bitmap is already enabled // then all the assets have already been updated in in storage. if (!accountContext.isBitmapEnabled()) { // NOTE: account context is updated in memory inside this method call. accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } // NOTE: free collateral and account context will be set outside of this method call. return accountContext; } /// @dev Executes deposits function _executeDepositAction( address account, BalanceState memory balanceState, DepositActionType depositType, uint256 depositActionAmount_ ) private { int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_); int256 assetInternalAmount; require(depositActionAmount >= 0); if (depositType == DepositActionType.None) { return; } else if ( depositType == DepositActionType.DepositAsset || depositType == DepositActionType.DepositAssetAndMintNToken ) { // NOTE: this deposit will NOT revert on a failed transfer unless there is a // transfer fee. The actual transfer will take effect later in balanceState.finalize assetInternalAmount = balanceState.depositAssetToken( account, depositActionAmount, false // no force transfer ); } else if ( depositType == DepositActionType.DepositUnderlying || depositType == DepositActionType.DepositUnderlyingAndMintNToken ) { // NOTE: this deposit will revert on a failed transfer immediately assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount); } else if (depositType == DepositActionType.ConvertCashToNToken) { // _executeNTokenAction will check if the account has sufficient cash assetInternalAmount = depositActionAmount; } _executeNTokenAction( balanceState, depositType, depositActionAmount, assetInternalAmount ); } /// @dev Executes nToken actions function _executeNTokenAction( BalanceState memory balanceState, DepositActionType depositType, int256 depositActionAmount, int256 assetInternalAmount ) private { // After deposits have occurred, check if we are minting nTokens if ( depositType == DepositActionType.DepositAssetAndMintNToken || depositType == DepositActionType.DepositUnderlyingAndMintNToken || depositType == DepositActionType.ConvertCashToNToken ) { // Will revert if trying to mint ntokens and results in a negative cash balance _checkSufficientCash(balanceState, assetInternalAmount); balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount); // Converts a given amount of cash (denominated in internal precision) into nTokens int256 tokensMinted = nTokenMintAction.nTokenMint( balanceState.currencyId, assetInternalAmount ); balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add( tokensMinted ); } else if (depositType == DepositActionType.RedeemNToken) { require( // prettier-ignore balanceState .storedNTokenBalance .add(balanceState.netNTokenTransfer) // transfers would not occur at this point .add(balanceState.netNTokenSupplyChange) >= depositActionAmount, "Insufficient token balance" ); balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub( depositActionAmount ); int256 assetCash = nTokenRedeemAction.nTokenRedeemViaBatch( balanceState.currencyId, depositActionAmount ); balanceState.netCashChange = balanceState.netCashChange.add(assetCash); } } /// @dev Calculations any withdraws and finalizes balances function _calculateWithdrawActionAndFinalize( address account, AccountContext memory accountContext, BalanceState memory balanceState, uint256 withdrawAmountInternalPrecision, bool withdrawEntireCashBalance, bool redeemToUnderlying ) private { int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision); require(withdrawAmount >= 0); // dev: withdraw action overflow // NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input if (withdrawEntireCashBalance) { // This option is here so that accounts do not end up with dust after lending since we generally // cannot calculate exact cash amounts from the liquidity curve. withdrawAmount = balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision); // If the account has a negative cash balance then cannot withdraw if (withdrawAmount < 0) withdrawAmount = 0; } // prettier-ignore balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .sub(withdrawAmount); balanceState.finalize(account, accountContext, redeemToUnderlying); } function _finalizeAccountContext(address account, AccountContext memory accountContext) private { // At this point all balances, market states and portfolio states should be finalized. Just need to check free // collateral if required. accountContext.setAccountContext(account); if (accountContext.hasDebt != 0x00) { FreeCollateralExternal.checkFreeCollateralAndRevert(account); } } /// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance /// to do so. function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision) private pure { // The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision require( amountInternalPrecision >= 0 && balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision, "Insufficient cash" ); } function _settleAccountIfRequired(address account) private returns (AccountContext memory) { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); if (accountContext.mustSettleAssets()) { // Returns a new memory reference to account context return SettleAssetsExternal.settleAccount(account, accountContext); } else { return accountContext; } } /// @notice Get a list of deployed library addresses (sorted by library name) function getLibInfo() external view returns (address, address, address, address, address, address) { return ( address(FreeCollateralExternal), address(MigrateIncentives), address(SettleAssetsExternal), address(TradingAction), address(nTokenMintAction), address(nTokenRedeemAction) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../FreeCollateralExternal.sol"; import "../SettleAssetsExternal.sol"; import "../../internal/markets/Market.sol"; import "../../internal/markets/CashGroup.sol"; import "../../internal/markets/AssetRate.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/portfolio/TransferAssets.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library TradingAction { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; using Market for MarketParameters; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; using SafeInt256 for int256; using SafeMath for uint256; event LendBorrowTrade( address indexed account, uint16 indexed currencyId, uint40 maturity, int256 netAssetCash, int256 netfCash ); event AddRemoveLiquidity( address indexed account, uint16 indexed currencyId, uint40 maturity, int256 netAssetCash, int256 netfCash, int256 netLiquidityTokens ); event SettledCashDebt( address indexed settledAccount, uint16 indexed currencyId, address indexed settler, int256 amountToSettleAsset, int256 fCashAmount ); event nTokenResidualPurchase( uint16 indexed currencyId, uint40 indexed maturity, address indexed purchaser, int256 fCashAmountToPurchase, int256 netAssetCashNToken ); /// @dev Used internally to manage stack issues struct TradeContext { int256 cash; int256 fCashAmount; int256 fee; int256 netCash; int256 totalFee; uint256 blockTime; } /// @notice Executes trades for a bitmapped portfolio, cannot be called directly /// @param account account to put fCash assets in /// @param bitmapCurrencyId currency id of the bitmap /// @param nextSettleTime used to calculate the relative positions in the bitmap /// @param trades tightly packed array of trades, schema is defined in global/Types.sol /// @return netCash generated by trading /// @return didIncurDebt if the bitmap had an fCash position go negative function executeTradesBitmapBatch( address account, uint16 bitmapCurrencyId, uint40 nextSettleTime, bytes32[] calldata trades ) external returns (int256, bool) { CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId); MarketParameters memory market; bool didIncurDebt; TradeContext memory c; c.blockTime = block.timestamp; for (uint256 i = 0; i < trades.length; i++) { uint256 maturity; (maturity, c.cash, c.fCashAmount) = _executeTrade( account, cashGroup, market, trades[i], c.blockTime ); c.fCashAmount = BitmapAssetsHandler.addifCashAsset( account, bitmapCurrencyId, maturity, nextSettleTime, c.fCashAmount ); didIncurDebt = didIncurDebt || (c.fCashAmount < 0); c.netCash = c.netCash.add(c.cash); } return (c.netCash, didIncurDebt); } /// @notice Executes trades for a bitmapped portfolio, cannot be called directly /// @param account account to put fCash assets in /// @param currencyId currency id to trade /// @param portfolioState used to update the positions in the portfolio /// @param trades tightly packed array of trades, schema is defined in global/Types.sol /// @return resulting portfolio state /// @return netCash generated by trading function executeTradesArrayBatch( address account, uint16 currencyId, PortfolioState memory portfolioState, bytes32[] calldata trades ) external returns (PortfolioState memory, int256) { CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId); MarketParameters memory market; TradeContext memory c; c.blockTime = block.timestamp; for (uint256 i = 0; i < trades.length; i++) { TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i])))); if ( tradeType == TradeActionType.AddLiquidity || tradeType == TradeActionType.RemoveLiquidity ) { revert("Disabled"); /** * Manual adding and removing of liquidity is currently disabled. * * // Liquidity tokens can only be added by array portfolio * c.cash = _executeLiquidityTrade( * account, * cashGroup, * market, * tradeType, * trades[i], * portfolioState, * c.netCash * ); */ } else { uint256 maturity; (maturity, c.cash, c.fCashAmount) = _executeTrade( account, cashGroup, market, trades[i], c.blockTime ); portfolioState.addAsset( currencyId, maturity, Constants.FCASH_ASSET_TYPE, c.fCashAmount ); } c.netCash = c.netCash.add(c.cash); } return (portfolioState, c.netCash); } /// @notice Executes a non-liquidity token trade /// @param account the initiator of the trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param trade bytes32 encoding of the particular trade /// @param blockTime the current block time /// @return maturity of the asset that was traded /// @return cashAmount - a positive or negative cash amount accrued to the account /// @return fCashAmount - a positive or negative fCash amount accrued to the account function _executeTrade( address account, CashGroupParameters memory cashGroup, MarketParameters memory market, bytes32 trade, uint256 blockTime ) private returns ( uint256 maturity, int256 cashAmount, int256 fCashAmount ) { TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade)))); if (tradeType == TradeActionType.PurchaseNTokenResidual) { (maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual( account, cashGroup, blockTime, trade ); } else if (tradeType == TradeActionType.SettleCashDebt) { (maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade); } else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) { (cashAmount, fCashAmount) = _executeLendBorrowTrade( cashGroup, market, tradeType, blockTime, trade ); // This is a little ugly but required to deal with stack issues. We know the market is loaded // with the proper maturity inside _executeLendBorrowTrade maturity = market.maturity; emit LendBorrowTrade( account, uint16(cashGroup.currencyId), uint40(maturity), cashAmount, fCashAmount ); } else { revert("Invalid trade type"); } } /// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold /// liquidity tokens. /// @param account the initiator of the trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param tradeType whether this is add or remove liquidity /// @param trade bytes32 encoding of the particular trade /// @param portfolioState the current account's portfolio state /// @param netCash the current net cash accrued in this batch of trades, can be // used for adding liquidity /// @return cashAmount: a positive or negative cash amount accrued to the account function _executeLiquidityTrade( address account, CashGroupParameters memory cashGroup, MarketParameters memory market, TradeActionType tradeType, bytes32 trade, PortfolioState memory portfolioState, int256 netCash ) private returns (int256) { uint256 marketIndex = uint8(bytes1(trade << 8)); // NOTE: this loads the market in memory cashGroup.loadMarket(market, marketIndex, true, block.timestamp); int256 cashAmount; int256 fCashAmount; int256 tokens; if (tradeType == TradeActionType.AddLiquidity) { cashAmount = int256((uint256(trade) >> 152) & type(uint88).max); // Setting cash amount to zero will deposit all net cash accumulated in this trade into // liquidity. This feature allows accounts to borrow in one maturity to provide liquidity // in another in a single transaction without dust. It also allows liquidity providers to // sell off the net cash residuals and use the cash amount in the new market without dust if (cashAmount == 0) cashAmount = netCash; // Add liquidity will check cash amount is positive (tokens, fCashAmount) = market.addLiquidity(cashAmount); cashAmount = cashAmount.neg(); // Report a negative cash amount in the event } else { tokens = int256((uint256(trade) >> 152) & type(uint88).max); (cashAmount, fCashAmount) = market.removeLiquidity(tokens); tokens = tokens.neg(); // Report a negative amount tokens in the event } { uint256 minImpliedRate = uint32(uint256(trade) >> 120); uint256 maxImpliedRate = uint32(uint256(trade) >> 88); // If minImpliedRate is not set then it will be zero require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage"); if (maxImpliedRate != 0) require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage"); } // Add the assets in this order so they are sorted portfolioState.addAsset( cashGroup.currencyId, market.maturity, Constants.FCASH_ASSET_TYPE, fCashAmount ); // Adds the liquidity token asset portfolioState.addAsset( cashGroup.currencyId, market.maturity, marketIndex + 1, tokens ); emit AddRemoveLiquidity( account, cashGroup.currencyId, // This will not overflow for a long time uint40(market.maturity), cashAmount, fCashAmount, tokens ); return cashAmount; } /// @notice Executes a lend or borrow trade /// @param cashGroup parameters for the trade /// @param market market memory location to use /// @param tradeType whether this is add or remove liquidity /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return cashAmount - a positive or negative cash amount accrued to the account /// @return fCashAmount - a positive or negative fCash amount accrued to the account function _executeLendBorrowTrade( CashGroupParameters memory cashGroup, MarketParameters memory market, TradeActionType tradeType, uint256 blockTime, bytes32 trade ) private returns ( int256 cashAmount, int256 fCashAmount ) { uint256 marketIndex = uint256(uint8(bytes1(trade << 8))); // NOTE: this updates the market in memory cashGroup.loadMarket(market, marketIndex, false, blockTime); fCashAmount = int256(uint88(bytes11(trade << 16))); // fCash to account will be negative here if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg(); cashAmount = market.executeTrade( cashGroup, fCashAmount, market.maturity.sub(blockTime), marketIndex ); require(cashAmount != 0, "Trade failed, liquidity"); uint256 rateLimit = uint256(uint32(bytes4(trade << 104))); if (rateLimit != 0) { if (tradeType == TradeActionType.Borrow) { // Do not allow borrows over the rate limit require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage"); } else { // Do not allow lends under the rate limit require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage"); } } } /// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty /// rate to the 3 month market. /// @param account the account initiating the trade, used to check that self settlement is not possible /// @param cashGroup parameters for the trade /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return maturity: the date of the three month maturity where fCash will be exchanged /// @return cashAmount: a negative cash amount that the account must pay to the settled account /// @return fCashAmount: a positive fCash amount that the account will receive function _settleCashDebt( address account, CashGroupParameters memory cashGroup, uint256 blockTime, bytes32 trade ) internal returns ( uint256, int256, int256 ) { address counterparty = address(uint256(trade) >> 88); // Allowing an account to settle itself would result in strange outcomes require(account != counterparty, "Cannot settle self"); int256 amountToSettleAsset = int256(uint88(uint256(trade))); AccountContext memory counterpartyContext = AccountContextHandler.getAccountContext(counterparty); if (counterpartyContext.mustSettleAssets()) { counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext); } // This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive // number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the // max amount to settle. This will update the balance storage on the counterparty. amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt( counterparty, cashGroup, amountToSettleAsset, counterpartyContext ); // Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market // is not initialized. uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; int256 fCashAmount = _getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset); // Defensive check to ensure that we can't inadvertently cause the settler to lose fCash. require(fCashAmount >= 0); // It's possible that this action will put an account into negative free collateral. In this case they // will immediately become eligible for liquidation and the account settling the debt can also liquidate // them in the same transaction. Do not run a free collateral check here to allow this to happen. { PortfolioAsset[] memory assets = new PortfolioAsset[](1); assets[0].currencyId = cashGroup.currencyId; assets[0].maturity = threeMonthMaturity; assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur assets[0].assetType = Constants.FCASH_ASSET_TYPE; // Can transfer assets, we have settled above counterpartyContext = TransferAssets.placeAssetsInAccount( counterparty, counterpartyContext, assets ); } counterpartyContext.setAccountContext(counterparty); emit SettledCashDebt( counterparty, uint16(cashGroup.currencyId), account, amountToSettleAsset, fCashAmount.neg() ); return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount); } /// @dev Helper method to calculate the fCashAmount from the penalty settlement rate function _getfCashSettleAmount( CashGroupParameters memory cashGroup, uint256 threeMonthMaturity, uint256 blockTime, int256 amountToSettleAsset ) private view returns (int256) { uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime); int256 exchangeRate = Market.getExchangeRateFromImpliedRate( oracleRate.add(cashGroup.getSettlementPenalty()), threeMonthMaturity.sub(blockTime) ); // Amount to settle is positive, this returns the fCashAmount that the settler will // receive as a positive number return cashGroup.assetRate .convertToUnderlying(amountToSettleAsset) // Exchange rate converts from cash to fCash when multiplying .mulInRatePrecision(exchangeRate); } /// @notice Allows an account to purchase ntoken residuals /// @param purchaser account that is purchasing the residuals /// @param cashGroup parameters for the trade /// @param blockTime the current block time /// @param trade bytes32 encoding of the particular trade /// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged /// @return cashAmount: a positive or negative cash amount that the account will receive or pay /// @return fCashAmount: a positive or negative fCash amount that the account will receive function _purchaseNTokenResidual( address purchaser, CashGroupParameters memory cashGroup, uint256 blockTime, bytes32 trade ) internal returns ( uint256, int256, int256 ) { uint256 maturity = uint256(uint32(uint256(trade) >> 216)); int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128)); require(maturity > blockTime, "Invalid maturity"); // Require that the residual to purchase does not fall on an existing maturity (i.e. // it is an idiosyncratic maturity) require( !DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime), "Non idiosyncratic maturity" ); address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, /* assetArrayLength */, bytes5 parameters ) = nTokenHandler.getNTokenContext(nTokenAddress); // Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage // opportunities are not available (by generating residuals and then immediately purchasing them at a discount) // This is always relative to the last initialized time which is set at utc0 when initialized, not the // reference time. Therefore we will always restrict residual purchase relative to initialization, not reference. // This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization // until the residual time buffer passes. require( blockTime > lastInitializedTime.add( uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours ), "Insufficient block time" ); int256 notional = BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity); // Check if amounts are valid and set them to the max available if necessary if (notional < 0 && fCashAmountToPurchase < 0) { // Does not allow purchasing more negative notional than available if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional; } else if (notional > 0 && fCashAmountToPurchase > 0) { // Does not allow purchasing more positive notional than available if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional; } else { // Does not allow moving notional in the opposite direction revert("Invalid amount"); } // If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return // netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken. int256 netAssetCashNToken = _getResidualPriceAssetCash( cashGroup, maturity, blockTime, fCashAmountToPurchase, parameters ); _updateNTokenPortfolio( nTokenAddress, cashGroup.currencyId, maturity, lastInitializedTime, fCashAmountToPurchase, netAssetCashNToken ); emit nTokenResidualPurchase( uint16(cashGroup.currencyId), uint40(maturity), purchaser, fCashAmountToPurchase, netAssetCashNToken ); return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase); } /// @notice Returns the amount of asset cash required to purchase the nToken residual function _getResidualPriceAssetCash( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime, int256 fCashAmount, bytes6 parameters ) internal view returns (int256) { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); // Residual purchase incentive is specified in ten basis point increments uint256 purchaseIncentive = uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) * Constants.TEN_BASIS_POINTS; if (fCashAmount > 0) { // When fCash is positive then we add the purchase incentive, the purchaser // can pay less cash for the fCash relative to the oracle rate oracleRate = oracleRate.add(purchaseIncentive); } else if (oracleRate > purchaseIncentive) { // When fCash is negative, we reduce the interest rate that the purchaser will // borrow at, we do this check to ensure that we floor the oracle rate at zero. oracleRate = oracleRate.sub(purchaseIncentive); } else { // If the oracle rate is less than the purchase incentive floor the interest rate at zero oracleRate = 0; } int256 exchangeRate = Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime)); // Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount return cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate)); } function _updateNTokenPortfolio( address nTokenAddress, uint256 currencyId, uint256 maturity, uint256 lastInitializedTime, int256 fCashAmountToPurchase, int256 netAssetCashNToken ) private { int256 finalNotional = BitmapAssetsHandler.addifCashAsset( nTokenAddress, currencyId, maturity, lastInitializedTime, fCashAmountToPurchase.neg() // the nToken takes on the negative position ); // Defensive check to ensure that fCash amounts do not flip signs require( (fCashAmountToPurchase > 0 && finalNotional >= 0) || (fCashAmountToPurchase < 0 && finalNotional <= 0) ); // prettier-ignore ( int256 nTokenCashBalance, /* storedNTokenBalance */, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId); nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken); // This will ensure that the cash balance is not negative BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/StorageLayoutV1.sol"; import "../../internal/nToken/nTokenHandler.sol"; abstract contract ActionGuards is StorageLayoutV1 { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; function initializeReentrancyGuard() internal { require(reentrancyStatus == 0); // Initialize the guard to a non-zero value, see the OZ reentrancy guard // description for why this is more gas efficient: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol reentrancyStatus = _NOT_ENTERED; } modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(reentrancyStatus != _ENTERED, "Reentrant call"); // Any calls to nonReentrant after this point will fail reentrancyStatus = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) reentrancyStatus = _NOT_ENTERED; } // These accounts cannot receive deposits, transfers, fCash or any other // types of value transfers. function requireValidAccount(address account) internal view { require(account != Constants.RESERVE); // Reserve address is address(0) require(account != address(this)); ( uint256 isNToken, /* incentiveAnnualEmissionRate */, /* lastInitializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(account); require(isNToken == 0); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "../../internal/nToken/nTokenHandler.sol"; import "../../internal/nToken/nTokenCalculations.sol"; import "../../internal/markets/Market.sol"; import "../../internal/markets/CashGroup.sol"; import "../../internal/markets/AssetRate.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenMintAction { using SafeInt256 for int256; using BalanceHandler for BalanceState; using CashGroup for CashGroupParameters; using Market for MarketParameters; using nTokenHandler for nTokenPortfolio; using PortfolioHandler for PortfolioState; using AssetRate for AssetRateParameters; using SafeMath for uint256; using nTokenHandler for nTokenPortfolio; /// @notice Converts the given amount of cash to nTokens in the same currency. /// @param currencyId the currency associated the nToken /// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals /// @return nTokens minted by this action function nTokenMint(uint16 currencyId, int256 amountToDepositInternal) external returns (int256) { uint256 blockTime = block.timestamp; nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioStateful(currencyId); int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime); require(tokensToMint >= 0, "Invalid token amount"); if (nToken.portfolioState.storedAssets.length == 0) { // If the token does not have any assets, then the markets must be initialized first. nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, currencyId, nToken.cashBalance ); } else { _depositIntoPortfolio(nToken, amountToDepositInternal, blockTime); } // NOTE: token supply does not change here, it will change after incentives have been claimed // during BalanceHandler.finalize return tokensToMint; } /// @notice Calculates the tokens to mint to the account as a ratio of the nToken /// present value denominated in asset cash terms. /// @return the amount of tokens to mint, the ifCash bitmap function calculateTokensToMint( nTokenPortfolio memory nToken, int256 amountToDepositInternal, uint256 blockTime ) internal view returns (int256) { require(amountToDepositInternal >= 0); // dev: deposit amount negative if (amountToDepositInternal == 0) return 0; if (nToken.lastInitializedTime != 0) { // For the sake of simplicity, nTokens cannot be minted if they have assets // that need to be settled. This is only done during market initialization. uint256 nextSettleTime = nToken.getNextSettleTime(); // If next settle time <= blockTime then the token can be settled require(nextSettleTime > blockTime, "Requires settlement"); } int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); // Defensive check to ensure PV remains positive require(assetCashPV >= 0); // Allow for the first deposit if (nToken.totalSupply == 0) { return amountToDepositInternal; } else { // assetCashPVPost = assetCashPV + amountToDeposit // (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV // (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV // (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV // tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV); } } /// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When /// entering this method we know that assetCashDeposit is positive and the nToken has been /// initialized to have liquidity tokens. function _depositIntoPortfolio( nTokenPortfolio memory nToken, int256 assetCashDeposit, uint256 blockTime ) private { (int256[] memory depositShares, int256[] memory leverageThresholds) = nTokenHandler.getDepositParameters( nToken.cashGroup.currencyId, nToken.cashGroup.maxMarketIndex ); // Loop backwards from the last market to the first market, the reasoning is a little complicated: // If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient // to calculate the cash amount to lend. We do know that longer term maturities will have more // slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get // closer to the current block time. Any residual cash from lending will be rolled into shorter // markets as this loop progresses. int256 residualCash; MarketParameters memory market; for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) { int256 fCashAmount; // Loads values into the market memory slot nToken.cashGroup.loadMarket( market, marketIndex, true, // Needs liquidity to true blockTime ); // If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex // before initializing if (market.totalLiquidity == 0) continue; // Checked that assetCashDeposit must be positive before entering int256 perMarketDeposit = assetCashDeposit .mul(depositShares[marketIndex - 1]) .div(Constants.DEPOSIT_PERCENT_BASIS) .add(residualCash); (fCashAmount, residualCash) = _lendOrAddLiquidity( nToken, market, perMarketDeposit, leverageThresholds[marketIndex - 1], marketIndex, blockTime ); if (fCashAmount != 0) { BitmapAssetsHandler.addifCashAsset( nToken.tokenAddress, nToken.cashGroup.currencyId, market.maturity, nToken.lastInitializedTime, fCashAmount ); } } // nToken is allowed to store assets directly without updating account context. nToken.portfolioState.storeAssets(nToken.tokenAddress); // Defensive check to ensure that we do not somehow accrue negative residual cash. require(residualCash >= 0, "Negative residual cash"); // This will occur if the three month market is over levered and we cannot lend into it if (residualCash > 0) { // Any remaining residual cash will be put into the nToken balance and added as liquidity on the // next market initialization nToken.cashBalance = nToken.cashBalance.add(residualCash); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.cashBalance ); } } /// @notice For a given amount of cash to deposit, decides how much to lend or provide /// given the market conditions. function _lendOrAddLiquidity( nTokenPortfolio memory nToken, MarketParameters memory market, int256 perMarketDeposit, int256 leverageThreshold, uint256 marketIndex, uint256 blockTime ) private returns (int256 fCashAmount, int256 residualCash) { // We start off with the entire per market deposit as residuals residualCash = perMarketDeposit; // If the market is over leveraged then we will lend to it instead of providing liquidity if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { (residualCash, fCashAmount) = _deleverageMarket( nToken.cashGroup, market, perMarketDeposit, blockTime, marketIndex ); // Recalculate this after lending into the market, if it is still over leveraged then // we will not add liquidity and just exit. if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { // Returns the residual cash amount return (fCashAmount, residualCash); } } // Add liquidity to the market only if we have successfully delevered. // (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored // If deleveraged, residualCash is what remains // If not deleveraged, residual cash is per market deposit fCashAmount = fCashAmount.add( _addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash) ); // No residual cash if we're adding liquidity return (fCashAmount, 0); } /// @notice Markets are over levered when their proportion is greater than a governance set /// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken /// account for the given amount of cash deposited, putting the nToken account at risk of liquidation. /// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead. function _isMarketOverLeveraged( CashGroupParameters memory cashGroup, MarketParameters memory market, int256 leverageThreshold ) private pure returns (bool) { int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // Comparison we want to do: // (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold // However, the division will introduce rounding errors so we change this to: // totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying) // Leverage threshold is denominated in rate precision. return ( market.totalfCash.mul(Constants.RATE_PRECISION) > leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying)) ); } function _addLiquidityToMarket( nTokenPortfolio memory nToken, MarketParameters memory market, uint256 index, int256 perMarketDeposit ) private returns (int256) { // Add liquidity to the market PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index]; // We expect that all the liquidity tokens are in the portfolio in order. require( asset.maturity == market.maturity && // Ensures that the asset type references the proper liquidity token asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX && // Ensures that the storage state will not be overwritten asset.storageState == AssetStorageState.NoChange, "PT: invalid liquidity token" ); // This will update the market state as well, fCashAmount returned here is negative (int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit); asset.notional = asset.notional.add(liquidityTokens); asset.storageState = AssetStorageState.Update; return fCashAmount; } /// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due /// to slippage or result in some amount of residual cash. function _deleverageMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, int256 perMarketDeposit, uint256 blockTime, uint256 marketIndex ) private returns (int256, int256) { uint256 timeToMaturity = market.maturity.sub(blockTime); // Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this // is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here // because it is very gas inefficient. int256 assumedExchangeRate; if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) { // Floor the exchange rate at zero interest rate assumedExchangeRate = Constants.RATE_PRECISION; } else { assumedExchangeRate = Market.getExchangeRateFromImpliedRate( market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER), timeToMaturity ); } int256 fCashAmount; { int256 perMarketDepositUnderlying = cashGroup.assetRate.convertToUnderlying(perMarketDeposit); // NOTE: cash * exchangeRate = fCash fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate); } int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex); // This means that the trade failed if (netAssetCash == 0) { return (perMarketDeposit, 0); } else { // Ensure that net the per market deposit figure does not drop below zero, this should not be possible // given how we've calculated the exchange rate but extra caution here int256 residual = perMarketDeposit.add(netAssetCash); require(residual >= 0); // dev: insufficient cash return (residual, fCashAmount); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../internal/markets/Market.sol"; import "../../internal/nToken/nTokenHandler.sol"; import "../../internal/nToken/nTokenCalculations.sol"; import "../../internal/portfolio/PortfolioHandler.sol"; import "../../internal/portfolio/TransferAssets.sol"; import "../../internal/balances/BalanceHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenRedeemAction { using SafeInt256 for int256; using SafeMath for uint256; using Bitmap for bytes32; using BalanceHandler for BalanceState; using Market for MarketParameters; using CashGroup for CashGroupParameters; using PortfolioHandler for PortfolioState; using nTokenHandler for nTokenPortfolio; /// @notice When redeeming nTokens via the batch they must all be sold to cash and this /// method will return the amount of asset cash sold. /// @param currencyId the currency associated the nToken /// @param tokensToRedeem the amount of nTokens to convert to cash /// @return amount of asset cash to return to the account, denominated in internal token decimals function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem) external returns (int256) { uint256 blockTime = block.timestamp; // prettier-ignore ( int256 totalAssetCash, bool hasResidual, /* PortfolioAssets[] memory newfCashAssets */ ) = _redeem(currencyId, tokensToRedeem, true, false, blockTime); require(!hasResidual, "Cannot redeem via batch, residual"); return totalAssetCash; } /// @notice Redeems nTokens for asset cash and fCash /// @param currencyId the currency associated the nToken /// @param tokensToRedeem the amount of nTokens to convert to cash /// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then place /// back into the account's portfolio /// @param acceptResidualAssets if true, then ifCash residuals will be placed into the account and there will /// be no penalty assessed /// @return assetCash positive amount of asset cash to the account /// @return hasResidual true if there are fCash residuals left /// @return assets an array of fCash asset residuals to place into the account function redeem( uint16 currencyId, int256 tokensToRedeem, bool sellTokenAssets, bool acceptResidualAssets ) external returns (int256, bool, PortfolioAsset[] memory) { return _redeem( currencyId, tokensToRedeem, sellTokenAssets, acceptResidualAssets, block.timestamp ); } function _redeem( uint16 currencyId, int256 tokensToRedeem, bool sellTokenAssets, bool acceptResidualAssets, uint256 blockTime ) internal returns (int256, bool, PortfolioAsset[] memory) { require(tokensToRedeem > 0); nTokenPortfolio memory nToken; nToken.loadNTokenPortfolioStateful(currencyId); // nTokens cannot be redeemed during the period of time where they require settlement. require(nToken.getNextSettleTime() > blockTime, "Requires settlement"); require(tokensToRedeem < nToken.totalSupply, "Cannot redeem"); PortfolioAsset[] memory newifCashAssets; // Get the ifCash bits that are idiosyncratic bytes32 ifCashBits = nTokenCalculations.getNTokenifCashBits( nToken.tokenAddress, currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup.maxMarketIndex ); if (ifCashBits != 0 && acceptResidualAssets) { // This will remove all the ifCash assets proportionally from the account newifCashAssets = _reduceifCashAssetsProportional( nToken.tokenAddress, currencyId, nToken.lastInitializedTime, tokensToRedeem, nToken.totalSupply, ifCashBits ); // Once the ifCash bits have been withdrawn, set this to zero so that getLiquidityTokenWithdraw // simply gets the proportional amount of liquidity tokens to remove ifCashBits = 0; } // Returns the liquidity tokens to withdraw per market and the netfCash amounts. Net fCash amounts are only // set when ifCashBits != 0. Otherwise they must be calculated in _withdrawLiquidityTokens (int256[] memory tokensToWithdraw, int256[] memory netfCash) = nTokenCalculations.getLiquidityTokenWithdraw( nToken, tokensToRedeem, blockTime, ifCashBits ); // Returns the totalAssetCash as a result of withdrawing liquidity tokens and cash. netfCash will be updated // in memory if required and will contain the fCash to be sold or returned to the portfolio int256 totalAssetCash = _reduceLiquidAssets( nToken, tokensToRedeem, tokensToWithdraw, netfCash, ifCashBits == 0, // If there are no residuals then we need to populate netfCash amounts blockTime ); bool netfCashRemaining = true; if (sellTokenAssets) { int256 assetCash; // NOTE: netfCash is modified in place and set to zero if the fCash is sold (assetCash, netfCashRemaining) = _sellfCashAssets(nToken, netfCash, blockTime); totalAssetCash = totalAssetCash.add(assetCash); } if (netfCashRemaining) { // If the account is unwilling to accept residuals then will fail here. require(acceptResidualAssets, "Residuals"); newifCashAssets = _addResidualsToAssets(nToken.portfolioState.storedAssets, newifCashAssets, netfCash); } return (totalAssetCash, netfCashRemaining, newifCashAssets); } /// @notice Removes liquidity tokens and cash from the nToken /// @param nToken portfolio object /// @param nTokensToRedeem tokens to redeem /// @param tokensToWithdraw array of liquidity tokens to withdraw /// @param netfCash array of netfCash figures /// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step /// @param blockTime current block time /// @return assetCashShare amount of cash the redeemer will receive from withdrawing cash assets from the nToken function _reduceLiquidAssets( nTokenPortfolio memory nToken, int256 nTokensToRedeem, int256[] memory tokensToWithdraw, int256[] memory netfCash, bool mustCalculatefCash, uint256 blockTime ) private returns (int256 assetCashShare) { // Get asset cash share for the nToken, if it exists. It is required in balance handler that the // nToken can never have a negative cash asset cash balance so what we get here is always positive // or zero. assetCashShare = nToken.cashBalance.mul(nTokensToRedeem).div(nToken.totalSupply); if (assetCashShare > 0) { nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare); BalanceHandler.setBalanceStorageForNToken( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.cashBalance ); } // Get share of liquidity tokens to remove, netfCash is modified in memory during this method if mustCalculatefcash // is set to true assetCashShare = assetCashShare.add( _removeLiquidityTokens(nToken, nTokensToRedeem, tokensToWithdraw, netfCash, blockTime, mustCalculatefCash) ); nToken.portfolioState.storeAssets(nToken.tokenAddress); // NOTE: Token supply change will happen when we finalize balances and after minting of incentives return assetCashShare; } /// @notice Removes nToken liquidity tokens and updates the netfCash figures. /// @param nToken portfolio object /// @param nTokensToRedeem tokens to redeem /// @param tokensToWithdraw array of liquidity tokens to withdraw /// @param netfCash array of netfCash figures /// @param blockTime current block time /// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step /// @return totalAssetCashClaims is the amount of asset cash raised from liquidity token cash claims function _removeLiquidityTokens( nTokenPortfolio memory nToken, int256 nTokensToRedeem, int256[] memory tokensToWithdraw, int256[] memory netfCash, uint256 blockTime, bool mustCalculatefCash ) private returns (int256 totalAssetCashClaims) { MarketParameters memory market; for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i]; asset.notional = asset.notional.sub(tokensToWithdraw[i]); // Cannot redeem liquidity tokens down to zero or this will cause many issues with // market initialization. require(asset.notional > 0, "Cannot redeem to zero"); require(asset.storageState == AssetStorageState.NoChange); asset.storageState = AssetStorageState.Update; // This will load a market object in memory nToken.cashGroup.loadMarket(market, i + 1, true, blockTime); int256 fCashClaim; { int256 assetCash; // Remove liquidity from the market (assetCash, fCashClaim) = market.removeLiquidity(tokensToWithdraw[i]); totalAssetCashClaims = totalAssetCashClaims.add(assetCash); } int256 fCashToNToken; if (mustCalculatefCash) { // Do this calculation if net ifCash is not set, will happen if there are no residuals int256 fCashShare = BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, asset.maturity ); fCashShare = fCashShare.mul(nTokensToRedeem).div(nToken.totalSupply); // netfCash = fCashClaim + fCashShare netfCash[i] = fCashClaim.add(fCashShare); fCashToNToken = fCashShare.neg(); } else { // Account will receive netfCash amount. Deduct that from the fCash claim and add the // remaining back to the nToken to net off the nToken's position // fCashToNToken = -fCashShare // netfCash = fCashClaim + fCashShare // fCashToNToken = -(netfCash - fCashClaim) // fCashToNToken = fCashClaim - netfCash fCashToNToken = fCashClaim.sub(netfCash[i]); } // Removes the account's fCash position from the nToken BitmapAssetsHandler.addifCashAsset( nToken.tokenAddress, asset.currencyId, asset.maturity, nToken.lastInitializedTime, fCashToNToken ); } return totalAssetCashClaims; } /// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash /// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on /// fCash assets. function _sellfCashAssets( nTokenPortfolio memory nToken, int256[] memory netfCash, uint256 blockTime ) private returns (int256 totalAssetCash, bool hasResidual) { MarketParameters memory market; hasResidual = false; for (uint256 i = 0; i < netfCash.length; i++) { if (netfCash[i] == 0) continue; nToken.cashGroup.loadMarket(market, i + 1, false, blockTime); int256 netAssetCash = market.executeTrade( nToken.cashGroup, // Use the negative of fCash notional here since we want to net it out netfCash[i].neg(), nToken.portfolioState.storedAssets[i].maturity.sub(blockTime), i + 1 ); if (netAssetCash == 0) { // This means that the trade failed hasResidual = true; } else { totalAssetCash = totalAssetCash.add(netAssetCash); netfCash[i] = 0; } } } /// @notice Combines newifCashAssets array with netfCash assets into a single finalfCashAssets array function _addResidualsToAssets( PortfolioAsset[] memory liquidityTokens, PortfolioAsset[] memory newifCashAssets, int256[] memory netfCash ) internal pure returns (PortfolioAsset[] memory finalfCashAssets) { uint256 numAssetsToExtend; for (uint256 i = 0; i < netfCash.length; i++) { if (netfCash[i] != 0) numAssetsToExtend++; } uint256 newLength = newifCashAssets.length + numAssetsToExtend; finalfCashAssets = new PortfolioAsset[](newLength); uint index = 0; for (; index < newifCashAssets.length; index++) { finalfCashAssets[index] = newifCashAssets[index]; } uint netfCashIndex = 0; for (; index < finalfCashAssets.length; ) { if (netfCash[netfCashIndex] != 0) { PortfolioAsset memory asset = finalfCashAssets[index]; asset.currencyId = liquidityTokens[netfCashIndex].currencyId; asset.maturity = liquidityTokens[netfCashIndex].maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = netfCash[netfCashIndex]; index++; } netfCashIndex++; } return finalfCashAssets; } /// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming /// nTokens to its underlying assets. function _reduceifCashAssetsProportional( address account, uint256 currencyId, uint256 lastInitializedTime, int256 tokensToRedeem, int256 totalSupply, bytes32 assetsBitmap ) internal returns (PortfolioAsset[] memory) { uint256 index = assetsBitmap.totalBitsSet(); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(lastInitializedTime, bitNum); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; int256 notional = fCashSlot.notional; int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply); int256 finalNotional = notional.sub(notionalToTransfer); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notionalToTransfer; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../internal/portfolio/PortfolioHandler.sol"; import "../internal/balances/BalanceHandler.sol"; import "../internal/settlement/SettlePortfolioAssets.sol"; import "../internal/settlement/SettleBitmapAssets.sol"; import "../internal/AccountContextHandler.sol"; /// @notice External library for settling assets library SettleAssetsExternal { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; event AccountSettled(address indexed account); /// @notice Settles an account, returns the new account context object after settlement. /// @dev The memory location of the account context object is not the same as the one returned. function settleAccount( address account, AccountContext memory accountContext ) external returns (AccountContext memory) { // Defensive check to ensure that this is a valid settlement require(accountContext.mustSettleAssets()); SettleAmount[] memory settleAmounts; PortfolioState memory portfolioState; if (accountContext.isBitmapEnabled()) { (int256 settledCash, uint256 blockTimeUTC0) = SettleBitmapAssets.settleBitmappedCashGroup( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, block.timestamp ); require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow accountContext.nextSettleTime = uint40(blockTimeUTC0); settleAmounts = new SettleAmount[](1); settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash); } else { portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp); accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts); emit AccountSettled(account); return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../external/SettleAssetsExternal.sol"; import "../internal/AccountContextHandler.sol"; import "../internal/valuation/FreeCollateral.sol"; /// @title Externally deployed library for free collateral calculations library FreeCollateralExternal { using AccountContextHandler for AccountContext; /// @notice Returns the ETH denominated free collateral of an account, represents the amount of /// debt that the account can incur before liquidation. If an account's assets need to be settled this /// will revert, either settle the account or use the off chain SDK to calculate free collateral. /// @dev Called via the Views.sol method to return an account's free collateral. Does not work /// for the nToken, the nToken does not have an account context. /// @param account account to calculate free collateral for /// @return total free collateral in ETH w/ 8 decimal places /// @return array of net local values in asset values ordered by currency id function getFreeCollateralView(address account) external view returns (int256, int256[] memory) { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); // The internal free collateral function does not account for settled assets. The Notional SDK // can calculate the free collateral off chain if required at this point. require(!accountContext.mustSettleAssets(), "Assets not settled"); return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp); } /// @notice Calculates free collateral and will revert if it falls below zero. If the account context /// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets /// need to be settled first. /// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be /// called before the end of any transaction for accounts where FC can decrease. /// @param account account to calculate free collateral for function checkFreeCollateralAndRevert(address account) external { AccountContext memory accountContext = AccountContextHandler.getAccountContext(account); require(!accountContext.mustSettleAssets(), "Assets not settled"); (int256 ethDenominatedFC, bool updateContext) = FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp); if (updateContext) { accountContext.setAccountContext(account); } require(ethDenominatedFC >= 0, "Insufficient free collateral"); } /// @notice Calculates liquidation factors for an account /// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is /// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then /// liquidation actions will revert. /// @dev an ntoken account will return 0 FC and revert if called /// @param account account to liquidate /// @param localCurrencyId currency that the debts are denominated in /// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation /// @return accountContext the accountContext of the liquidated account /// @return factors struct of relevant factors for liquidation /// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array) function getLiquidationFactors( address account, uint256 localCurrencyId, uint256 collateralCurrencyId ) external returns ( AccountContext memory accountContext, LiquidationFactors memory factors, PortfolioAsset[] memory portfolio ) { accountContext = AccountContextHandler.getAccountContext(account); if (accountContext.mustSettleAssets()) { accountContext = SettleAssetsExternal.settleAccount(account, accountContext); } if (accountContext.isBitmapEnabled()) { // A bitmap currency can only ever hold debt in this currency require(localCurrencyId == accountContext.bitmapCurrencyId); } (factors, portfolio) = FreeCollateral.getLiquidationFactors( account, accountContext, block.timestamp, localCurrencyId, collateralCurrencyId ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../global/Constants.sol"; library SafeInt256 { int256 private constant _INT256_MIN = type(int256).min; /// @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 c) { c = a * b; if (a == -1) require (b == 0 || c / b == a); else require (a == 0 || c / a == b); } /// @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 c) { require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow // NOTE: solidity will automatically revert on divide by zero c = a / b; } function sub(int256 x, int256 y) internal pure returns (int256 z) { // taken from uniswap v3 require((z = x - y) <= x == (y >= 0)); } function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } function neg(int256 x) internal pure returns (int256 y) { return mul(-1, x); } function abs(int256 x) internal pure returns (int256) { if (x < 0) return neg(x); else return x; } function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) { z = sub(x, y); require(z >= 0); // dev: int256 sub to negative return z; } /// @dev Calculates x * RATE_PRECISION / y while checking overflows function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, Constants.RATE_PRECISION), y); } /// @dev Calculates x * y / RATE_PRECISION while checking overflows function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, y), Constants.RATE_PRECISION); } function toUint(int256 x) internal pure returns (uint256) { require(x >= 0); return uint256(x); } function toInt(uint256 x) internal pure returns (int256) { require (x <= uint256(type(int256).max)); // dev: toInt overflow return int256(x); } function max(int256 x, int256 y) internal pure returns (int256) { return x > y ? x : y; } function min(int256 x, int256 y) internal pure returns (int256) { return x < y ? x : y; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; /** * @notice Storage layout for the system. Do not change this file once deployed, future storage * layouts must inherit this and increment the version number. */ contract StorageLayoutV1 { // The current maximum currency id uint16 internal maxCurrencyId; // Sets the state of liquidations being enabled during a paused state. Each of the four lower // bits can be turned on to represent one of the liquidation types being enabled. bytes1 internal liquidationEnabledState; // Set to true once the system has been initialized bool internal hasInitialized; /* Authentication Mappings */ // This is set to the timelock contract to execute governance functions address public owner; // This is set to an address of a router that can only call governance actions address public pauseRouter; // This is set to an address of a router that can only call governance actions address public pauseGuardian; // On upgrades this is set in the case that the pause router is used to pass the rollback check address internal rollbackRouterImplementation; // A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user // to set an allowance on all nTokens for a particular integrating contract system. // owner => spender => transferAllowance mapping(address => mapping(address => uint256)) internal nTokenWhitelist; // Individual transfer allowances for nTokens used for ERC20 // owner => spender => currencyId => transferAllowance mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance; // Transfer operators // Mapping from a global ERC1155 transfer operator contract to an approval value for it mapping(address => bool) internal globalTransferOperator; // Mapping from an account => operator => approval status for that operator. This is a specific // approval between two addresses for ERC1155 transfers. mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator; // Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in // BatchAction.sol, can only be set by governance mapping(address => bool) internal authorizedCallbackContract; // Reverse mapping from token addresses to currency ids, only used for referencing in views // and checking for duplicate token listings. mapping(address => uint16) internal tokenAddressToCurrencyId; // Reentrancy guard uint256 internal reentrancyStatus; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Incentives.sol"; import "./TokenHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/FloatingPoint56.sol"; library BalanceHandler { using SafeInt256 for int256; using TokenHandler for Token; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; /// @notice Emitted when a cash balance changes event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange); /// @notice Emitted when nToken supply changes (not the same as transfers) event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange); /// @notice Emitted when reserve fees are accrued event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee); /// @notice Emitted when reserve balance is updated event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance); /// @notice Emitted when reserve balance is harvested event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount); /// @notice Deposits asset tokens into an account /// @dev Handles two special cases when depositing tokens into an account. /// - If a token has transfer fees then the amount specified does not equal the amount that the contract /// will receive. Complete the deposit here rather than in finalize so that the contract has the correct /// balance to work with. /// - Force a transfer before finalize to allow a different account to deposit into an account /// @return assetAmountInternal which is the converted asset amount accounting for transfer fees function depositAssetToken( BalanceState memory balanceState, address account, int256 assetAmountExternal, bool forceTransfer ) internal returns (int256 assetAmountInternal) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); // dev: deposit asset token amount negative Token memory token = TokenHandler.getAssetToken(balanceState.currencyId); if (token.tokenType == TokenType.aToken) { // Handles special accounting requirements for aTokens assetAmountExternal = AaveHandler.convertToScaledBalanceExternal( balanceState.currencyId, assetAmountExternal ); } // Force transfer is used to complete the transfer before going to finalize if (token.hasTransferFee || forceTransfer) { // If the token has a transfer fee the deposit amount may not equal the actual amount // that the contract will receive. We handle the deposit here and then update the netCashChange // accordingly which is denominated in internal precision. int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal); // Convert the external precision to internal, it's possible that we lose dust amounts here but // this is unavoidable because we do not know how transfer fees are calculated. assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal); // Transfer has been called balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal); return assetAmountInternal; } else { assetAmountInternal = token.convertToInternal(assetAmountExternal); // Otherwise add the asset amount here. It may be net off later and we want to only do // a single transfer during the finalize method. Use internal precision to ensure that internal accounting // and external account remain in sync. // Transfer will be deferred balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .add(assetAmountInternal); // Returns the converted assetAmountExternal to the internal amount return assetAmountInternal; } } /// @notice Handle deposits of the underlying token /// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up /// with any underlying tokens left as dust on the contract. function depositUnderlyingToken( BalanceState memory balanceState, address account, int256 underlyingAmountExternal ) internal returns (int256) { if (underlyingAmountExternal == 0) return 0; require(underlyingAmountExternal > 0); // dev: deposit underlying token negative Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId); // This is the exact amount of underlying tokens the account has in external precision. if (underlyingToken.tokenType == TokenType.Ether) { // Underflow checked above require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance"); } else { underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal); } Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); int256 assetTokensReceivedExternalPrecision = assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal)); // cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different // type of asset token is listed in the future. It's possible if those tokens have a different precision dust may // accrue but that is not relevant now. int256 assetTokensReceivedInternal = assetToken.convertToInternal(assetTokensReceivedExternalPrecision); // Transfer / mint has taken effect balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal); return assetTokensReceivedInternal; } /// @notice Finalizes an account's balances, handling any transfer logic required /// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken /// as the nToken is limited in what types of balances it can hold. function finalize( BalanceState memory balanceState, address account, AccountContext memory accountContext, bool redeemToUnderlying ) internal returns (int256 transferAmountExternal) { bool mustUpdate; if (balanceState.netNTokenTransfer < 0) { require( balanceState.storedNTokenBalance .add(balanceState.netNTokenSupplyChange) .add(balanceState.netNTokenTransfer) >= 0, "Neg nToken" ); } if (balanceState.netAssetTransferInternalPrecision < 0) { require( balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= 0, "Neg Cash" ); } // Transfer amount is checked inside finalize transfers in case when converting to external we // round down to zero. This returns the actual net transfer in internal precision as well. ( transferAmountExternal, balanceState.netAssetTransferInternalPrecision ) = _finalizeTransfers(balanceState, account, redeemToUnderlying); // No changes to total cash after this point int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision); if (totalCashChange != 0) { balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange); mustUpdate = true; emit CashBalanceChange( account, uint16(balanceState.currencyId), totalCashChange ); } if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) { // Final nToken balance is used to calculate the account incentive debt int256 finalNTokenBalance = balanceState.storedNTokenBalance .add(balanceState.netNTokenTransfer) .add(balanceState.netNTokenSupplyChange); // The toUint() call here will ensure that nToken balances never become negative Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint()); balanceState.storedNTokenBalance = finalNTokenBalance; if (balanceState.netNTokenSupplyChange != 0) { emit nTokenSupplyChange( account, uint16(balanceState.currencyId), balanceState.netNTokenSupplyChange ); } mustUpdate = true; } if (mustUpdate) { _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } accountContext.setActiveCurrency( balanceState.currencyId, // Set active currency to true if either balance is non-zero balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (balanceState.storedCashBalance < 0) { // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances // are examined accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } } /// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying /// is specified. function _finalizeTransfers( BalanceState memory balanceState, address account, bool redeemToUnderlying ) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) { Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); // Dust accrual to the protocol is possible if the token decimals is less than internal token precision. // See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal int256 assetTransferAmountExternal = assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision); if (assetTransferAmountExternal == 0) { return (0, 0); } else if (redeemToUnderlying && assetTransferAmountExternal < 0) { // We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than // zero then we will do a normal transfer instead. // We use the internal amount here and then scale it to the external amount so that there is // no loss of precision between our internal accounting and the external account. In this case // there will be no dust accrual in underlying tokens since we will transfer the exact amount // of underlying that was received. actualTransferAmountExternal = assetToken.redeem( balanceState.currencyId, account, // No overflow, checked above uint256(assetTransferAmountExternal.neg()) ); // In this case we're transferring underlying tokens, we want to convert the internal // asset transfer amount to store in cash balances assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal); } else { // NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it // will be converted to balanceOf denomination inside transfer actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal); // Convert the actual transferred amount assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal); } } /// @notice Special method for settling negative current cash debts. This occurs when an account /// has a negative fCash balance settle to cash. A settler may come and force the account to borrow /// at the prevailing 3 month rate /// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary. function setBalanceStorageForSettleCashDebt( address account, CashGroupParameters memory cashGroup, int256 amountToSettleAsset, AccountContext memory accountContext ) internal returns (int256) { require(amountToSettleAsset >= 0); // dev: amount to settle negative (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, cashGroup.currencyId); // Prevents settlement of positive balances require(cashBalance < 0, "Invalid settle balance"); if (amountToSettleAsset == 0) { // Symbolizes that the entire debt should be settled amountToSettleAsset = cashBalance.neg(); cashBalance = 0; } else { // A partial settlement of the debt require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle"); cashBalance = cashBalance.add(amountToSettleAsset); } // NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances // also have cash debts if (cashBalance == 0 && nTokenBalance == 0) { accountContext.setActiveCurrency( cashGroup.currencyId, false, Constants.ACTIVE_IN_BALANCES ); } _setBalanceStorage( account, cashGroup.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); // Emit the event here, we do not call finalize emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset); return amountToSettleAsset; } /** * @notice A special balance storage method for fCash liquidation to reduce the bytecode size. */ function setBalanceStorageForfCashLiquidation( address account, AccountContext memory accountContext, uint16 currencyId, int256 netCashChange ) internal { (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) = getBalanceStorage(account, currencyId); int256 newCashBalance = cashBalance.add(netCashChange); // If a cash balance is negative already we cannot put an account further into debt. In this case // the netCashChange must be positive so that it is coming out of debt. if (newCashBalance < 0) { require(netCashChange > 0, "Neg Cash"); // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check // where all balances are examined. In this case the has cash debt flag should // already be set (cash balances cannot get more negative) but we do it again // here just to be safe. accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } bool isActive = newCashBalance != 0 || nTokenBalance != 0; accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES); // Emit the event here, we do not call finalize emit CashBalanceChange(account, currencyId, netCashChange); _setBalanceStorage( account, currencyId, newCashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } /// @notice Helper method for settling the output of the SettleAssets method function finalizeSettleAmounts( address account, AccountContext memory accountContext, SettleAmount[] memory settleAmounts ) internal { for (uint256 i = 0; i < settleAmounts.length; i++) { SettleAmount memory amt = settleAmounts[i]; if (amt.netCashChange == 0) continue; ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) = getBalanceStorage(account, amt.currencyId); cashBalance = cashBalance.add(amt.netCashChange); accountContext.setActiveCurrency( amt.currencyId, cashBalance != 0 || nTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (cashBalance < 0) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } emit CashBalanceChange( account, uint16(amt.currencyId), amt.netCashChange ); _setBalanceStorage( account, amt.currencyId, cashBalance, nTokenBalance, lastClaimTime, accountIncentiveDebt ); } } /// @notice Special method for setting balance storage for nToken function setBalanceStorageForNToken( address nTokenAddress, uint256 currencyId, int256 cashBalance ) internal { require(cashBalance >= 0); // dev: invalid nToken cash balance _setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0); } /// @notice increments fees to the reserve function incrementFeeToReserve(uint256 currencyId, int256 fee) internal { require(fee >= 0); // dev: invalid fee // prettier-ignore (int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId); totalReserve = totalReserve.add(fee); _setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0); emit ReserveFeeAccrued(uint16(currencyId), fee); } /// @notice harvests excess reserve balance function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal { // parameters are validated by the caller reserve = reserve.subNoNeg(assetInternalRedeemAmount); _setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0); emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount); } /// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal { require(newBalance >= 0); // dev: invalid balance _setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0); emit ReserveBalanceUpdated(currencyId, newBalance); } /// @notice Sets internal balance storage. function _setBalanceStorage( address account, uint256 currencyId, int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) private { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow // Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow if (lastClaimTime == 0) { // In this case the account has migrated and we set the accountIncentiveDebt // The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never // encounter an overflow for accountIncentiveDebt require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt); } else { // In this case the last claim time has not changed and we do not update the last integral supply // (stored in the accountIncentiveDebt position) require(lastClaimTime == balanceStorage.lastClaimTime); } balanceStorage.lastClaimTime = uint32(lastClaimTime); balanceStorage.nTokenBalance = uint80(nTokenBalance); balanceStorage.cashBalance = int88(cashBalance); } /// @notice Gets internal balance storage, nTokens are stored alongside cash balances function getBalanceStorage(address account, uint256 currencyId) internal view returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt ) { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; nTokenBalance = balanceStorage.nTokenBalance; lastClaimTime = balanceStorage.lastClaimTime; if (lastClaimTime > 0) { // NOTE: this is only necessary to support the deprecated integral supply values, which are stored // in the accountIncentiveDebt slot accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt); } else { accountIncentiveDebt = balanceStorage.accountIncentiveDebt; } cashBalance = balanceStorage.cashBalance; } /// @notice Loads a balance state memory object /// @dev Balance state objects occupy a lot of memory slots, so this method allows /// us to reuse them if possible function loadBalanceState( BalanceState memory balanceState, address account, uint16 currencyId, AccountContext memory accountContext ) internal view { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id balanceState.currencyId = currencyId; if (accountContext.isActiveInBalances(currencyId)) { ( balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ) = getBalanceStorage(account, currencyId); } else { balanceState.storedCashBalance = 0; balanceState.storedNTokenBalance = 0; balanceState.lastClaimTime = 0; balanceState.accountIncentiveDebt = 0; } balanceState.netCashChange = 0; balanceState.netAssetTransferInternalPrecision = 0; balanceState.netNTokenTransfer = 0; balanceState.netNTokenSupplyChange = 0; } /// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state /// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts /// are migrated to the new incentive calculation function claimIncentivesManual(BalanceState memory balanceState, address account) internal returns (uint256 incentivesClaimed) { incentivesClaimed = Incentives.claimIncentives( balanceState, account, balanceState.storedNTokenBalance.toUint() ); _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.accountIncentiveDebt ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TransferAssets.sol"; import "../valuation/AssetHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; /// @notice Handles the management of an array of assets including reading from storage, inserting /// updating, deleting and writing back to storage. library PortfolioHandler { using SafeInt256 for int256; using AssetHandler for PortfolioAsset; // Mirror of LibStorage.MAX_PORTFOLIO_ASSETS uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @notice Primarily used by the TransferAssets library function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets) internal pure { for (uint256 i = 0; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; addAsset( portfolioState, asset.currencyId, asset.maturity, asset.assetType, asset.notional ); } } function _mergeAssetIntoArray( PortfolioAsset[] memory assetArray, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) private pure returns (bool) { for (uint256 i = 0; i < assetArray.length; i++) { PortfolioAsset memory asset = assetArray[i]; if ( asset.assetType != assetType || asset.currencyId != currencyId || asset.maturity != maturity ) continue; // Either of these storage states mean that some error in logic has occurred, we cannot // store this portfolio require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: portfolio handler deleted storage int256 newNotional = asset.notional.add(notional); // Liquidity tokens cannot be reduced below zero. if (AssetHandler.isLiquidityToken(assetType)) { require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance } require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow asset.notional = newNotional; asset.storageState = AssetStorageState.Update; return true; } return false; } /// @notice Adds an asset to a portfolio state in memory (does not write to storage) /// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity /// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional. function addAsset( PortfolioState memory portfolioState, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) internal pure { if ( // Will return true if merged _mergeAssetIntoArray( portfolioState.storedAssets, currencyId, maturity, assetType, notional ) ) return; if (portfolioState.lastNewAssetIndex > 0) { bool merged = _mergeAssetIntoArray( portfolioState.newAssets, currencyId, maturity, assetType, notional ); if (merged) return; } // At this point if we have not merged the asset then append to the array // Cannot remove liquidity that the portfolio does not have if (AssetHandler.isLiquidityToken(assetType)) { require(notional >= 0); // dev: portfolio handler negative liquidity token balance } require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow // Need to provision a new array at this point if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) { portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets); } // Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will // check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct. PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex]; newAsset.currencyId = currencyId; newAsset.maturity = maturity; newAsset.assetType = assetType; newAsset.notional = notional; newAsset.storageState = AssetStorageState.NoChange; portfolioState.lastNewAssetIndex += 1; } /// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do /// it too much function _extendNewAssetArray(PortfolioAsset[] memory newAssets) private pure returns (PortfolioAsset[] memory) { // Double the size of the new asset array every time we have to extend to reduce the number of times // that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there). uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2; PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength); for (uint256 i = 0; i < newAssets.length; i++) { extendedArray[i] = newAssets[i]; } return extendedArray; } /// @notice Takes a portfolio state and writes it to storage. /// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via /// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library. /// @return updated variables to update the account context with /// hasDebt: whether or not the portfolio has negative fCash assets /// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio /// uint8: the length of the storage array /// uint40: the new nextSettleTime for the portfolio function storeAssets(PortfolioState memory portfolioState, address account) internal returns ( bool, bytes32, uint8, uint40 ) { bool hasDebt; // NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is // set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate // 7 additional fCash assets for a total of 14 assets. Although even in this case all assets // would be of the same currency so it would not change the end result of the active currency // calculation. bytes32 portfolioActiveCurrencies; uint256 nextSettleTime; for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler // during valuation. require(asset.storageState != AssetStorageState.RevertIfStored); // Mark any zero notional assets as deleted if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) { deleteAsset(portfolioState, i); } } // First delete assets from asset storage to maintain asset storage indexes for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; if (asset.storageState == AssetStorageState.Delete) { // Delete asset from storage uint256 currentSlot = asset.storageSlot; assembly { sstore(currentSlot, 0x00) } } else { if (asset.storageState == AssetStorageState.Update) { PortfolioAssetStorage storage assetStorage; uint256 currentSlot = asset.storageSlot; assembly { assetStorage.slot := currentSlot } _storeAsset(asset, assetStorage); } // Update portfolio context for every asset that is in storage, whether it is // updated in storage or not. (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); } } // Add new assets uint256 assetStorageLength = portfolioState.storedAssetLength; mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; for (uint256 i = 0; i < portfolioState.newAssets.length; i++) { PortfolioAsset memory asset = portfolioState.newAssets[i]; if (asset.notional == 0) continue; require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: store assets deleted storage (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); _storeAsset(asset, storageArray[assetStorageLength]); assetStorageLength += 1; } // 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with // 2 bytes per currency require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow return ( hasDebt, portfolioActiveCurrencies, uint8(assetStorageLength), uint40(nextSettleTime) ); } /// @notice Updates context information during the store assets method function _updatePortfolioContext( PortfolioAsset memory asset, bool hasDebt, bytes32 portfolioActiveCurrencies, uint256 nextSettleTime ) private pure returns ( bool, bytes32, uint256 ) { uint256 settlementDate = asset.getSettlementDate(); // Tis will set it to the minimum settlement date if (nextSettleTime == 0 || nextSettleTime > settlementDate) { nextSettleTime = settlementDate; } hasDebt = hasDebt || asset.notional < 0; require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240); return (hasDebt, portfolioActiveCurrencies, nextSettleTime); } /// @dev Encodes assets for storage function _storeAsset( PortfolioAsset memory asset, PortfolioAssetStorage storage assetStorage ) internal { require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow assetStorage.currencyId = uint16(asset.currencyId); assetStorage.maturity = uint40(asset.maturity); assetStorage.assetType = uint8(asset.assetType); assetStorage.notional = int88(asset.notional); } /// @notice Deletes an asset from a portfolio /// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement /// by adding the offsetting negative position function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure { require(index < portfolioState.storedAssets.length); // dev: stored assets bounds require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index]; require( assetToDelete.storageState != AssetStorageState.Delete && assetToDelete.storageState != AssetStorageState.RevertIfStored ); // dev: cannot delete asset portfolioState.storedAssetLength -= 1; uint256 maxActiveSlotIndex; uint256 maxActiveSlot; // The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the // array so we search for it here. for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory a = portfolioState.storedAssets[i]; if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) { maxActiveSlot = a.storageSlot; maxActiveSlotIndex = i; } } if (index == maxActiveSlotIndex) { // In this case we are deleting the asset with the max storage slot so no swap is necessary. assetToDelete.storageState = AssetStorageState.Delete; return; } // Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly // so that when we call store assets they will be updated appropriately PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex]; ( assetToSwap.storageSlot, assetToDelete.storageSlot ) = ( assetToDelete.storageSlot, assetToSwap.storageSlot ); assetToSwap.storageState = AssetStorageState.Update; assetToDelete.storageState = AssetStorageState.Delete; } /// @notice Returns a portfolio array, will be sorted function getSortedPortfolio(address account, uint8 assetArrayLength) internal view returns (PortfolioAsset[] memory) { PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength); // No sorting required for length of 1 if (assets.length <= 1) return assets; _sortInPlace(assets); return assets; } /// @notice Builds a portfolio array from storage. The new assets hint parameter will /// be used to provision a new array for the new assets. This will increase gas efficiency /// so that we don't have to make copies when we extend the array. function buildPortfolioState( address account, uint8 assetArrayLength, uint256 newAssetsHint ) internal view returns (PortfolioState memory) { PortfolioState memory state; if (assetArrayLength == 0) return state; state.storedAssets = getSortedPortfolio(account, assetArrayLength); state.storedAssetLength = assetArrayLength; state.newAssets = new PortfolioAsset[](newAssetsHint); return state; } function _sortInPlace(PortfolioAsset[] memory assets) private pure { uint256 length = assets.length; uint256[] memory ids = new uint256[](length); for (uint256 k; k < length; k++) { PortfolioAsset memory asset = assets[k]; // Prepopulate the ids to calculate just once ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType); } // Uses insertion sort uint256 i = 1; while (i < length) { uint256 j = i; while (j > 0 && ids[j - 1] > ids[j]) { // Swap j - 1 and j (ids[j - 1], ids[j]) = (ids[j], ids[j - 1]); (assets[j - 1], assets[j]) = (assets[j], assets[j - 1]); j--; } i++; } } function _loadAssetArray(address account, uint8 length) private view returns (PortfolioAsset[] memory) { // This will overflow the storage pointer require(length <= MAX_PORTFOLIO_ASSETS); mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; PortfolioAsset[] memory assets = new PortfolioAsset[](length); for (uint256 i = 0; i < length; i++) { PortfolioAssetStorage storage assetStorage = storageArray[i]; PortfolioAsset memory asset = assets[i]; uint256 slot; assembly { slot := assetStorage.slot } asset.currencyId = assetStorage.currencyId; asset.maturity = assetStorage.maturity; asset.assetType = assetStorage.assetType; asset.notional = assetStorage.notional; asset.storageSlot = slot; } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "./balances/BalanceHandler.sol"; import "./portfolio/BitmapAssetsHandler.sol"; import "./portfolio/PortfolioHandler.sol"; library AccountContextHandler { using PortfolioHandler for PortfolioState; bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF; event AccountContextUpdate(address indexed account); /// @notice Returns the account context of a given account function getAccountContext(address account) internal view returns (AccountContext memory) { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); return store[account]; } /// @notice Sets the account context of a given account function setAccountContext(AccountContext memory accountContext, address account) internal { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); store[account] = accountContext; emit AccountContextUpdate(account); } function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) { return accountContext.bitmapCurrencyId != 0; } /// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows /// an account to hold more fCash than a normal portfolio, except only in a single currency. /// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if /// it has no assets or debt so that we ensure no assets are left stranded. /// @param accountContext refers to the account where the bitmap will be enabled /// @param currencyId the id of the currency to enable /// @param blockTime the current block time to set the next settle time function enableBitmapForAccount( AccountContext memory accountContext, uint16 currencyId, uint256 blockTime ) internal view { require(!isBitmapEnabled(accountContext), "Cannot change bitmap"); require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id"); // Account cannot have assets or debts require(accountContext.assetArrayLength == 0, "Cannot have assets"); require(accountContext.hasDebt == 0x00, "Cannot have debt"); // Ensure that the active currency is set to false in the array so that there is no double // counting during FreeCollateral setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES); accountContext.bitmapCurrencyId = currencyId; // Setting this is required to initialize the assets bitmap uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime); require(nextSettleTime < type(uint40).max); // dev: blockTime overflow accountContext.nextSettleTime = uint40(nextSettleTime); } /// @notice Returns true if the context needs to settle function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) { uint256 blockTime = block.timestamp; if (isBitmapEnabled(accountContext)) { // nextSettleTime will be set to utc0 after settlement so we // settle if this is strictly less than utc0 return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime); } else { // 0 value occurs on an uninitialized account // Assets mature exactly on the blockTime (not one second past) so in this // case we settle on the block timestamp return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime; } } /// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account /// context active currencies list. /// @dev NOTE: this may be more efficient as a binary search since we know that the array /// is sorted function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId) internal pure returns (bool) { require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id bytes18 currencies = accountContext.activeCurrencies; if (accountContext.bitmapCurrencyId == currencyId) return true; while (currencies != 0x00) { uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS); if (cid == currencyId) { // Currency found, return if it is active in balances or not return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES; } currencies = currencies << 16; } return false; } /// @notice Iterates through the active currency list and removes, inserts or does nothing /// to ensure that the active currency list is an ordered byte array of uint16 currency ids /// that refer to the currencies that an account is active in. /// /// This is called to ensure that currencies are active when the account has a non zero cash balance, /// a non zero nToken balance or a portfolio asset. function setActiveCurrency( AccountContext memory accountContext, uint256 currencyId, bool isActive, bytes2 flags ) internal pure { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id // If the bitmapped currency is already set then return here. Turning off the bitmap currency // id requires other logical handling so we will do it elsewhere. if (isActive && accountContext.bitmapCurrencyId == currencyId) return; bytes18 prefix; bytes18 suffix = accountContext.activeCurrencies; uint256 shifts; /// There are six possible outcomes from this search: /// 1. The currency id is in the list /// - it must be set to active, do nothing /// - it must be set to inactive, shift suffix and concatenate /// 2. The current id is greater than the one in the search: /// - it must be set to active, append to prefix and then concatenate the suffix, /// ensure that we do not lose the last 2 bytes if set. /// - it must be set to inactive, it is not in the list, do nothing /// 3. Reached the end of the list: /// - it must be set to active, check that the last two bytes are not set and then /// append to the prefix /// - it must be set to inactive, do nothing while (suffix != 0x00) { uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS)); // if matches and isActive then return, already in list if (cid == currencyId && isActive) { // set flag and return accountContext.activeCurrencies = accountContext.activeCurrencies | (bytes18(flags) >> (shifts * 16)); return; } // if matches and not active then shift suffix to remove if (cid == currencyId && !isActive) { // turn off flag, if both flags are off then remove suffix = suffix & ~bytes18(flags); if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16; accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16)); return; } // if greater than and isActive then insert into prefix if (cid > currencyId && isActive) { prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); // check that the total length is not greater than 9, meaning that the last // two bytes of the active currencies array should be zero require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies // append the suffix accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16)); return; } // if past the point of the currency id and not active, not in list if (cid > currencyId && !isActive) return; prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16)); suffix = suffix << 16; shifts += 1; } // If reached this point and not active then return if (!isActive) return; // if end and isActive then insert into suffix, check max length require(shifts < 9); // dev: AC: too many currencies accountContext.activeCurrencies = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); } function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) { bytes18 result; // This is required to clear the suffix as we append below bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS; uint256 shifts; // This loop will append all currencies that are active in balances into the result. while (suffix != 0x00) { if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { // If any flags are active, then append. result = result | (bytes18(bytes2(suffix)) >> shifts); shifts += 16; } suffix = suffix << 16; } return result; } /// @notice Stores a portfolio array and updates the account context information, this method should /// be used whenever updating a portfolio array except in the case of nTokens function storeAssetsAndUpdateContext( AccountContext memory accountContext, address account, PortfolioState memory portfolioState, bool isLiquidation ) internal { // Each of these parameters is recalculated based on the entire array of assets in store assets, // regardless of whether or not they have been updated. (bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) = portfolioState.storeAssets(account); accountContext.nextSettleTime = nextSettleTime; require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets accountContext.assetArrayLength = assetArrayLength; // During liquidation it is possible for an array to go over the max amount of assets allowed due to // liquidity tokens being withdrawn into fCash. if (!isLiquidation) { require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed } // Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning // a negative fCash balance. if (hasDebt) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } else { // Turns off the ASSET_DEBT flag accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; } // Clear the active portfolio active flags and they will be recalculated in the next step accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies); uint256 lastCurrency; while (portfolioCurrencies != 0) { // Portfolio currencies will not have flags, it is just an byte array of all the currencies found // in a portfolio. They are appended in a sorted order so we can compare to the previous currency // and only set it if they are different. uint256 currencyId = uint16(bytes2(portfolioCurrencies)); if (currencyId != lastCurrency) { setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO); } lastCurrency = currencyId; portfolioCurrencies = portfolioCurrencies << 16; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; interface NotionalCallback { function notionalCallback(address sender, address account, bytes calldata callbackdata) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetRate.sol"; import "./CashGroup.sol"; import "./DateTime.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Market { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; // Max positive value for a ABDK64x64 integer int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF; /// @notice Add liquidity to a market, assuming that it is initialized. If not then /// this method will revert and the market must be initialized first. /// Return liquidityTokens and negative fCash to the portfolio function addLiquidity(MarketParameters memory market, int256 assetCash) internal returns (int256 liquidityTokens, int256 fCash) { require(market.totalLiquidity > 0, "M: zero liquidity"); if (assetCash == 0) return (0, 0); require(assetCash > 0); // dev: negative asset cash liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash); // No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion. fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash); market.totalLiquidity = market.totalLiquidity.add(liquidityTokens); market.totalfCash = market.totalfCash.add(fCash); market.totalAssetCash = market.totalAssetCash.add(assetCash); _setMarketStorageForLiquidity(market); // Flip the sign to represent the LP's net position fCash = fCash.neg(); } /// @notice Remove liquidity from a market, assuming that it is initialized. /// Return assetCash and positive fCash to the portfolio function removeLiquidity(MarketParameters memory market, int256 tokensToRemove) internal returns (int256 assetCash, int256 fCash) { if (tokensToRemove == 0) return (0, 0); require(tokensToRemove > 0); // dev: negative tokens to remove assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity); fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity); market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove); market.totalfCash = market.totalfCash.subNoNeg(fCash); market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash); _setMarketStorageForLiquidity(market); } function executeTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal returns (int256 netAssetCash) { int256 netAssetCashToReserve; (netAssetCash, netAssetCashToReserve) = calculateTrade( market, cashGroup, fCashToAccount, timeToMaturity, marketIndex ); MarketStorage storage marketStorage = _getMarketStoragePointer(market); _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve); } /// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive /// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory. /// @param market the current market state /// @param cashGroup cash group configuration parameters /// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change /// to the market is in the opposite direction. /// @param timeToMaturity number of seconds until maturity /// @return netAssetCash, netAssetCashToReserve function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { // We return false if there is not enough fCash to support this trade. // if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail // if fCashToAccount < 0 and totalfCash > 0 then this will always pass if (market.totalfCash <= fCashToAccount) return (0, 0); // Calculates initial rate factors for the trade (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); // Calculates the exchange rate from cash to fCash before any liquidity fees // are applied int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } // Given the exchange rate, returns the net cash amounts to apply to each of the // three relevant balances. (int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) = _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); // Signifies a failed net cash amount calculation if (netCashToAccount == 0) return (0, 0); { // Set the new implied interest rate after the trade has taken effect, this // will be used to calculate the next trader's interest rate. market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); // It's technically possible that the implied rate is actually exactly zero (or // more accurately the natural log rounds down to zero) but we will still fail // in this case. If this does happen we may assume that markets are not initialized. if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } /// @notice Returns factors for calculating exchange rates /// @return /// rateScalar: a scalar value in rate precision that defines the slope of the line /// totalCashUnderlying: the converted asset cash to underlying cash for calculating /// the exchange rates for the trade /// rateAnchor: an offset from the x axis to maintain interest rate continuity over time function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256, int256, int256 ) { int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity); int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // This would result in a divide by zero if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0); // Get the rate anchor given the market state, this will establish the baseline for where // the exchange rate is set. int256 rateAnchor; { bool success; (rateAnchor, success) = _getRateAnchor( market.totalfCash, market.lastImpliedRate, totalCashUnderlying, rateScalar, timeToMaturity ); if (!success) return (0, 0, 0); } return (rateScalar, totalCashUnderlying, rateAnchor); } /// @dev Returns net asset cash amounts to the account, the market and the reserve /// @return /// netCashToAccount: this is a positive or negative amount of cash change to the account /// netCashToMarket: this is a positive or negative amount of cash change in the market // netCashToReserve: this is always a positive amount of cash accrued to the reserve function _getNetCashAmountsUnderlying( CashGroupParameters memory cashGroup, int256 preFeeExchangeRate, int256 fCashToAccount, uint256 timeToMaturity ) private pure returns ( int256, int256, int256 ) { // Fees are specified in basis points which is an rate precision denomination. We convert this to // an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply // or divide depending on the side of the trade). // tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity) // tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity) // cash = fCash / exchangeRate, exchangeRate > 1 int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg(); int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity); if (fCashToAccount > 0) { // Lending // Dividing reduces exchange rate, lending should receive less fCash for cash int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee); // It's possible that the fee pushes exchange rates into negative territory. This is not possible // when borrowing. If this happens then the trade has failed. if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0); // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate // preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate) // postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate) // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1) // netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1) // netFee = preFeeCashToAccount * (1 - feeExchangeRate) // RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0 fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee)); } else { // Borrowing // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1) // netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate) // NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number // preFee * (1 - fee) / fee will be negative, use neg() to flip to positive // RATE_PRECISION - fee will be negative fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg(); } int256 cashToReserve = fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS); return ( // postFeeCashToAccount = preFeeCashToAccount - fee preFeeCashToAccount.sub(fee), // netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve) (preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(), cashToReserve ); } /// @notice Sets the new market state /// @return /// netAssetCashToAccount: the positive or negative change in asset cash to the account /// assetCashToReserve: the positive amount of cash that accrues to the reserve function _setNewMarketState( MarketParameters memory market, AssetRateParameters memory assetRate, int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve ) private view returns (int256, int256) { int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket); // Set storage checks that total asset cash is above zero market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket); // Sets the trade time for the next oracle update market.previousTradeTime = block.timestamp; int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve); int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount); return (netAssetCashToAccount, assetCashToReserve); } /// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable /// across time or markets but implied rates are. The goal here is to ensure that the implied rate /// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied /// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage /// which will hurt the liquidity providers. /// /// The rate anchor will update as the market rolls down to maturity. The calculation is: /// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME) /// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar /// /// where: /// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity') /// (calculated when the last trade in the market was made) /// @return the new rate anchor and a boolean that signifies success function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity ) internal pure returns (int256, bool) { // This is the exchange rate at the new time to maturity int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity); if (newExchangeRate < Constants.RATE_PRECISION) return (0, false); int256 rateAnchor; { // totalfCash / (totalfCash + totalCashUnderlying) int256 proportion = totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying)); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar)); } return (rateAnchor, true); } /// @notice Calculates the current market implied rate. /// @return the implied rate and a bool that is true on success function getImpliedRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, uint256 timeToMaturity ) internal pure returns (uint256) { // This will check for exchange rates < Constants.RATE_PRECISION (int256 exchangeRate, bool success) = _getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0); if (!success) return 0; // Uses continuous compounding to calculate the implied rate: // ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity int128 rate = ABDKMath64x64.fromInt(exchangeRate); // Scales down to a floating point for LN int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64); // We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION // inside getExchangeRate int128 lnRateScaled = ABDKMath64x64.ln(rateScaled); // Scales up to a fixed point uint256 lnRate = ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64)); // lnRate * IMPLIED_RATE_TIME / ttm uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity); // Implied rates over 429% will overflow, this seems like a safe assumption if (impliedRate > type(uint32).max) return 0; return impliedRate; } /// @notice Converts an implied rate to an exchange rate given a time to maturity. The /// formula is E = e^rt function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt( impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME) ); int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); int128 expResult = ABDKMath64x64.exp(expValueScaled); int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64); return ABDKMath64x64.toInt(expResultScaled); } /// @notice Returns the exchange rate between fCash and cash for the given market /// Calculates the following exchange rate: /// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor /// where: /// proportion = totalfCash / (totalfCash + totalUnderlyingCash) /// @dev has an underscore to denote as private but is marked internal for the mock function _getExchangeRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 fCashToAccount ) internal pure returns (int256, bool) { int256 numerator = totalfCash.subNoNeg(fCashToAccount); // This is the proportion scaled by Constants.RATE_PRECISION // (totalfCash + fCash) / (totalfCash + totalCashUnderlying) int256 proportion = numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying)); // This limit is here to prevent the market from reaching extremely high interest rates via an // excessively large proportion (high amounts of fCash relative to cash). // Market proportion can only increase via borrowing (fCash is added to the market and cash is // removed). Over time, the returns from asset cash will slightly decrease the proportion (the // value of cash underlying in the market must be monotonically increasing). Therefore it is not // possible for the proportion to go over max market proportion unless borrowing occurs. if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // lnProportion / rateScalar + rateAnchor int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor); // Do not succeed if interest rates fall below 1 if (rate < Constants.RATE_PRECISION) { return (0, false); } else { return (rate, true); } } /// @dev This method calculates the log of the proportion inside the logit function which is /// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with /// fixed point precision and the ABDK library. function _logProportion(int256 proportion) internal pure returns (int256, bool) { // This will result in divide by zero, short circuit if (proportion == Constants.RATE_PRECISION) return (0, false); // Convert proportion to what is used inside the logit function (p / (1-p)) int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion)); // ABDK does not handle log of numbers that are less than 1, in order to get the right value // scaled by RATE_PRECISION we use the log identity: // (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION int128 abdkProportion = ABDKMath64x64.fromInt(logitP); // Here, abdk will revert due to negative log so abort if (abdkProportion <= 0) return (0, false); int256 result = ABDKMath64x64.toInt( ABDKMath64x64.mul( ABDKMath64x64.sub( ABDKMath64x64.ln(abdkProportion), Constants.LOG_RATE_PRECISION_64x64 ), Constants.RATE_PRECISION_64x64 ) ); return (result, true); } /// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value /// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example, /// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates. /// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then /// be liquidated. /// /// Oracle rates are calculated when the market is loaded from storage. /// /// The oracle rate is a lagged weighted average over a short term price window. If we are past /// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the /// weighted average: /// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow + /// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow) function _updateRateOracle( uint256 previousTradeTime, uint256 lastImpliedRate, uint256 oracleRate, uint256 rateOracleTimeWindow, uint256 blockTime ) private pure returns (uint256) { require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero // This can occur when using a view function get to a market state in the past if (previousTradeTime > blockTime) return lastImpliedRate; uint256 timeDiff = blockTime.sub(previousTradeTime); if (timeDiff > rateOracleTimeWindow) { // If past the time window just return the lastImpliedRate return lastImpliedRate; } // (currentTs - previousTs) / timeWindow uint256 lastTradeWeight = timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow); // 1 - (currentTs - previousTs) / timeWindow uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight); uint256 newOracleRate = (lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div( uint256(Constants.RATE_PRECISION) ); return newOracleRate; } function getOracleRate( uint256 currencyId, uint256 maturity, uint256 rateOracleTimeWindow, uint256 blockTime ) internal view returns (uint256) { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; uint256 lastImpliedRate = marketStorage.lastImpliedRate; uint256 oracleRate = marketStorage.oracleRate; uint256 previousTradeTime = marketStorage.previousTradeTime; // If the oracle rate is set to zero this can only be because the markets have past their settlement // date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated // during this time, but market initialization can be called by anyone so the actual time that this condition // exists for should be quite short. require(oracleRate > 0, "Market not initialized"); return _updateRateOracle( previousTradeTime, lastImpliedRate, oracleRate, rateOracleTimeWindow, blockTime ); } /// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method /// which ensures that the rate oracle is set properly. function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { // Market object always uses the most current reference time as the settlement date mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; } else { market.totalLiquidity = 0; } } function _getMarketStoragePointer( MarketParameters memory market ) private pure returns (MarketStorage storage marketStorage) { bytes32 slot = market.storageSlot; assembly { marketStorage.slot := slot } } function _setMarketStorageForLiquidity(MarketParameters memory market) internal { MarketStorage storage marketStorage = _getMarketStoragePointer(market); // Oracle rate does not change on liquidity uint32 storedOracleRate = marketStorage.oracleRate; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, storedOracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function setMarketStorageForInitialize( MarketParameters memory market, uint256 currencyId, uint256 settlementDate ) internal { // On initialization we have not yet calculated the storage slot so we get it here. mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate]; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function _setTotalLiquidity( MarketStorage storage marketStorage, int256 totalLiquidity ) internal { require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow marketStorage.totalLiquidity = uint80(totalLiquidity); } function _setMarketStorage( MarketStorage storage marketStorage, int256 totalfCash, int256 totalAssetCash, uint256 lastImpliedRate, uint256 oracleRate, uint256 previousTradeTime ) private { require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow marketStorage.totalfCash = uint80(totalfCash); marketStorage.totalAssetCash = uint80(totalAssetCash); marketStorage.lastImpliedRate = uint32(lastImpliedRate); marketStorage.oracleRate = uint32(oracleRate); marketStorage.previousTradeTime = uint32(previousTradeTime); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately. function loadMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow ) internal view { // Always reference the current settlement date uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; loadMarketWithSettlementDate( market, currencyId, maturity, blockTime, needsLiquidity, rateOracleTimeWindow, settlementDate ); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this /// is mainly used in the InitializeMarketAction contract. function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate); market.oracleRate = _updateRateOracle( market.previousTradeTime, market.lastImpliedRate, market.oracleRate, rateOracleTimeWindow, blockTime ); } function loadSettlementMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, true, settlementDate); } /// Uses Newton's method to converge on an fCash amount given the amount of /// cash. The relation between cash and fcash is: /// cashAmount * exchangeRate * fee + fCash = 0 /// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor /// p = (totalfCash - fCash) / (totalfCash + totalCash) /// if cashAmount < 0: fee = feeRate ^ -1 /// if cashAmount > 0: fee = feeRate /// /// Newton's method is: /// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash) /// /// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash /// /// (totalfCash + totalCash) /// exchangeRate'(fCash) = - ------------------------------------------ /// (totalfCash - fCash) * (totalCash + fCash) /// /// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29 /// /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) /// /// NOTE: each iteration costs about 11.3k so this is only done via a view function. function getfCashGivenCashAmount( int256 totalfCash, int256 netCashToAccount, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 feeRate, int256 maxDelta ) internal pure returns (int256) { require(maxDelta >= 0); int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg(); for (uint8 i = 0; i < 250; i++) { (int256 exchangeRate, bool success) = _getExchangeRate( totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashChangeToAccountGuess ); require(success); // dev: invalid exchange rate int256 delta = _calculateDelta( netCashToAccount, totalfCash, totalCashUnderlying, rateScalar, fCashChangeToAccountGuess, exchangeRate, feeRate ); if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess; fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta); } revert("No convergence"); } /// @dev Calculates: f(fCash) / f'(fCash) /// f(fCash) = cashAmount * exchangeRate * fee + fCash /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) function _calculateDelta( int256 cashAmount, int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 fCashGuess, int256 exchangeRate, int256 feeRate ) private pure returns (int256) { int256 derivative; // rateScalar * (totalfCash - fCash) * (totalCash + fCash) // Precision: TOKEN_PRECISION ^ 2 int256 denominator = rateScalar.mulInRatePrecision( (totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess)) ); if (fCashGuess > 0) { // Lending exchangeRate = exchangeRate.divInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount / fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount .mul(totalfCash.add(totalCashUnderlying)) .divInRatePrecision(feeRate); } else { // Borrowing exchangeRate = exchangeRate.mulInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount * fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount.mulInRatePrecision( feeRate.mul(totalfCash.add(totalCashUnderlying)) ); } // 1 - numerator / denominator // Precision: TOKEN_PRECISION derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator)); // f(fCash) = cashAmount * exchangeRate * fee + fCash // NOTE: exchangeRate at this point already has the fee taken into account int256 numerator = cashAmount.mulInRatePrecision(exchangeRate); numerator = numerator.add(fCashGuess); // f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION // here instead of RATE_PRECISION return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Market.sol"; import "./AssetRate.sol"; import "./DateTime.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library CashGroup { using SafeMath for uint256; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; // Bit number references for each parameter in the 32 byte word (0-indexed) uint256 private constant MARKET_INDEX_BIT = 31; uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30; uint256 private constant TOTAL_FEE_BIT = 29; uint256 private constant RESERVE_FEE_SHARE_BIT = 28; uint256 private constant DEBT_BUFFER_BIT = 27; uint256 private constant FCASH_HAIRCUT_BIT = 26; uint256 private constant SETTLEMENT_PENALTY_BIT = 25; uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24; uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23; // 7 bytes allocated, one byte per market for the liquidity token haircut uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22; // 7 bytes allocated, one byte per market for the rate scalar uint256 private constant RATE_SCALAR_FIRST_BIT = 15; // Offsets for the bytes of the different parameters uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8; uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8; uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8; uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8; uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8; uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8; uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8; uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8; uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8; uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8; uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8; /// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies /// the ln() portion of the liquidity curve as an inverse so it increases with time to /// maturity. The effect of the rate scalar on slippage must decrease with time to maturity. function getRateScalar( CashGroupParameters memory cashGroup, uint256 marketIndex, uint256 timeToMaturity ) internal pure returns (int256) { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1); int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION; int256 rateScalar = scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity)); // Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the // division above. require(rateScalar > 0); // dev: rate scalar underflow return rateScalar; } /// @notice Haircut on liquidity tokens to account for the risk associated with changes in the /// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100. function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType) internal pure returns (uint8) { require( Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX ); // dev: liquidity haircut invalid asset type uint256 offset = LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX); return uint8(uint256(cashGroup.data >> offset)); } /// @notice Total trading fee denominated in RATE_PRECISION with basis point increments function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT; } /// @notice Percentage of the total trading fee that goes to the reserve function getReserveFeeShare(CashGroupParameters memory cashGroup) internal pure returns (int256) { return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE)); } /// @notice fCash haircut for valuation denominated in rate precision with five basis point increments function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } /// @notice Time window factor for the rate oracle denominated in seconds with five minute increments. function getRateOracleTimeWindow(CashGroupParameters memory cashGroup) internal pure returns (uint256) { // This is denominated in 5 minute increments in storage return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES; } /// @notice Penalty rate for settling cash debts denominated in basis points function getSettlementPenalty(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for positive fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for negative fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } function loadMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 marketIndex, bool needsLiquidity, uint256 blockTime ) internal view { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market"); uint256 maturity = DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex)); market.loadMarket( cashGroup.currencyId, maturity, blockTime, needsLiquidity, getRateOracleTimeWindow(cashGroup) ); } /// @notice Returns the linear interpolation between two market rates. The formula is /// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity) /// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate function interpolateOracleRate( uint256 shortMaturity, uint256 longMaturity, uint256 shortRate, uint256 longRate, uint256 assetMaturity ) internal pure returns (uint256) { require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity // It's possible that the rates are inverted where the short market rate > long market rate and // we will get an underflow here so we check for that if (longRate >= shortRate) { return (longRate - shortRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) .add(shortRate); } else { // In this case the slope is negative so: // interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity) // NOTE: this subtraction should never overflow, the linear interpolation between two points above zero // cannot go below zero return shortRate.sub( // This is reversed to keep it it positive (shortRate - longRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) ); } } /// @dev Gets an oracle rate given any valid maturity. function calculateOracleRate( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime ) internal view returns (uint256) { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime); uint256 timeWindow = getRateOracleTimeWindow(cashGroup); if (!idiosyncratic) { return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime); } else { uint256 referenceTime = DateTime.getReferenceTime(blockTime); // DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex)); uint256 longRate = Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime); uint256 shortMaturity; uint256 shortRate; if (marketIndex == 1) { // In this case the short market is the annualized asset supply rate shortMaturity = blockTime; shortRate = cashGroup.assetRate.getSupplyRate(); } else { // Minimum value for marketIndex here is 2 shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1)); shortRate = Market.getOracleRate( cashGroup.currencyId, shortMaturity, timeWindow, blockTime ); } return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity); } } function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) { mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); return store[currencyId]; } /// @dev Helper method for validating maturities in ERC1155Action function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) { bytes32 data = _getCashGroupStorageBytes(currencyId); return uint8(data[MARKET_INDEX_BIT]); } /// @notice Checks all cash group settings for invalid values and sets them into storage function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup) internal { // Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market. // The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month // fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash // groups with 0 market index, it has no effect. require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: invalid market index" ); require( cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS, "CG: invalid reserve share" ); require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex); require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex); // This is required so that fCash liquidation can proceed correctly require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS); require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS); // Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId); require( previousMaxMarketIndex <= cashGroup.maxMarketIndex, "CG: market index cannot decrease" ); // Per cash group settings bytes32 data = (bytes32(uint256(cashGroup.maxMarketIndex)) | (bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) | (bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) | (bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) | (bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) | (bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) | (bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) << LIQUIDATION_FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER)); // Per market group settings for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) { require( cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS, "CG: invalid token haircut" ); data = data | (bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) << (LIQUIDITY_TOKEN_HAIRCUT + i * 8)); } for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) { // Causes a divide by zero error require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar"); data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8)); } mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); store[currencyId] = data; } /// @notice Deserialize the cash group storage bytes into a user friendly object function deserializeCashGroupStorage(uint256 currencyId) internal view returns (CashGroupSettings memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex)); uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex)); for (uint8 i = 0; i < maxMarketIndex; i++) { tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]); rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]); } return CashGroupSettings({ maxMarketIndex: maxMarketIndex, rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]), totalFeeBPS: uint8(data[TOTAL_FEE_BIT]), reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]), debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]), fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]), settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]), liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]), liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]), liquidityTokenHaircuts: tokenHaircuts, rateScalars: rateScalars }); } function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate) private view returns (CashGroupParameters memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); return CashGroupParameters({ currencyId: currencyId, maxMarketIndex: maxMarketIndex, assetRate: assetRate, data: data }); } /// @notice Builds a cash group using a view version of the asset rate function buildCashGroupView(uint16 currencyId) internal view returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId); return _buildCashGroup(currencyId, assetRate); } /// @notice Builds a cash group using a stateful version of the asset rate function buildCashGroupStateful(uint16 currencyId) internal returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId); return _buildCashGroup(currencyId, assetRate); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/notional/AssetRateAdapter.sol"; library AssetRate { using SafeInt256 for int256; event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate); // Asset rates are in 1e18 decimals (cToken exchange rates), internal balances // are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10 int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10; /// @notice Converts an internal asset cash value to its underlying token value. /// @param ar exchange rate object between asset and underlying /// @param assetBalance amount to convert to underlying function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance) internal pure returns (int256) { // Calculation here represents: // rate * balance * internalPrecision / rateDecimals * underlyingPrecision int256 underlyingBalance = ar.rate .mul(assetBalance) .div(ASSET_RATE_DECIMAL_DIFFERENCE) .div(ar.underlyingDecimals); return underlyingBalance; } /// @notice Converts an internal underlying cash value to its asset cash value /// @param ar exchange rate object between asset and underlying /// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance) internal pure returns (int256) { // Calculation here represents: // rateDecimals * balance * underlyingPrecision / rate * internalPrecision int256 assetBalance = underlyingBalance .mul(ASSET_RATE_DECIMAL_DIFFERENCE) .mul(ar.underlyingDecimals) .div(ar.rate); return assetBalance; } /// @notice Returns the current per block supply rate, is used when calculating oracle rates /// for idiosyncratic fCash with a shorter duration than the 3 month maturity. function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) { // If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero. if (address(ar.rateOracle) == address(0)) return 0; uint256 rate = ar.rateOracle.getAnnualizedSupplyRate(); // Zero supply rate is valid since this is an interest rate, we do not divide by // the supply rate so we do not get div by zero errors. require(rate >= 0); // dev: invalid supply rate return rate; } function _getAssetRateStorage(uint256 currencyId) private view returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) { mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage(); AssetRateStorage storage ar = store[currencyId]; rateOracle = AssetRateAdapter(ar.rateOracle); underlyingDecimalPlaces = ar.underlyingDecimalPlaces; } /// @notice Gets an asset rate using a view function, does not accrue interest so the /// exchange rate will not be up to date. Should only be used for non-stateful methods function _getAssetRateView(uint256 currencyId) private view returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateView(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Gets an asset rate using a stateful function, accrues interest so the /// exchange rate will be up to date for the current block. function _getAssetRateStateful(uint256 currencyId) private returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateStateful(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Returns an asset rate object using the view method function buildAssetRateView(uint256 currencyId) internal view returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateView(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @notice Returns an asset rate object using the stateful method function buildAssetRateStateful(uint256 currencyId) internal returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStateful(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @dev Gets a settlement rate object function _getSettlementRateStorage(uint256 currencyId, uint256 maturity) private view returns ( int256 settlementRate, uint8 underlyingDecimalPlaces ) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); SettlementRateStorage storage rateStorage = store[currencyId][maturity]; settlementRate = rateStorage.settlementRate; underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces; } /// @notice Returns a settlement rate object using the view method function buildSettlementRateView(uint256 currencyId, uint256 maturity) internal view returns (AssetRateParameters memory) { // prettier-ignore ( int256 settlementRate, uint8 underlyingDecimalPlaces ) = _getSettlementRateStorage(currencyId, maturity); // Asset exchange rates cannot be zero if (settlementRate == 0) { // If settlement rate has not been set then we need to fetch it // prettier-ignore ( settlementRate, /* address */, underlyingDecimalPlaces ) = _getAssetRateView(currencyId); } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } /// @notice Returns a settlement rate object and sets the rate if it has not been set yet function buildSettlementRateStateful( uint256 currencyId, uint256 maturity, uint256 blockTime ) internal returns (AssetRateParameters memory) { (int256 settlementRate, uint8 underlyingDecimalPlaces) = _getSettlementRateStorage(currencyId, maturity); if (settlementRate == 0) { // Settlement rate has not yet been set, set it in this branch AssetRateAdapter rateOracle; // If rate oracle == 0 then this will return the identity settlement rate // prettier-ignore ( settlementRate, rateOracle, underlyingDecimalPlaces ) = _getAssetRateStateful(currencyId); if (address(rateOracle) != address(0)) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); // Only need to set settlement rates when the rate oracle is set (meaning the asset token has // a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1 // rate since they are the same. require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow SettlementRateStorage storage rateStorage = store[currencyId][maturity]; rateStorage.blockTime = uint40(blockTime); rateStorage.settlementRate = uint128(settlementRate); rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces; emit SetSettlementRate(currencyId, maturity, uint128(settlementRate)); } } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./PortfolioHandler.sol"; import "./BitmapAssetsHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../math/SafeInt256.sol"; /// @notice Helper library for transferring assets from one portfolio to another library TransferAssets { using AccountContextHandler for AccountContext; using PortfolioHandler for PortfolioState; using SafeInt256 for int256; /// @notice Decodes asset ids function decodeAssetId(uint256 id) internal pure returns ( uint256 currencyId, uint256 maturity, uint256 assetType ) { assetType = uint8(id); maturity = uint40(id >> 8); currencyId = uint16(id >> 48); } /// @notice Encodes asset ids function encodeAssetId( uint256 currencyId, uint256 maturity, uint256 assetType ) internal pure returns (uint256) { require(currencyId <= Constants.MAX_CURRENCIES); require(maturity <= type(uint40).max); require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); return uint256( (bytes32(uint256(uint16(currencyId))) << 48) | (bytes32(uint256(uint40(maturity))) << 8) | bytes32(uint256(uint8(assetType))) ); } /// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure { for (uint256 i; i < assets.length; i++) { assets[i].notional = assets[i].notional.neg(); } } /// @dev Useful method for hiding the logic of updating an account. WARNING: the account /// context returned from this method may not be the same memory location as the account /// context provided if the account is settled. function placeAssetsInAccount( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal returns (AccountContext memory) { // If an account has assets that require settlement then placing assets inside it // may cause issues. require(!accountContext.mustSettleAssets(), "Account must settle"); if (accountContext.isBitmapEnabled()) { // Adds fCash assets into the account and finalized storage BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets); } else { PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, assets.length ); // This will add assets in memory portfolioState.addMultipleAssets(assets); // This will store assets and update the account context in memory accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } return accountContext; } } // 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: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetHandler.sol"; import "./ExchangeRate.sol"; import "../markets/CashGroup.sol"; import "../AccountContextHandler.sol"; import "../balances/BalanceHandler.sol"; import "../portfolio/PortfolioHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenCalculations.sol"; import "../../math/SafeInt256.sol"; library FreeCollateral { using SafeInt256 for int256; using Bitmap for bytes; using ExchangeRate for ETHRate; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; using nTokenHandler for nTokenPortfolio; /// @dev This is only used within the library to clean up the stack struct FreeCollateralFactors { int256 netETHValue; bool updateContext; uint256 portfolioIndex; CashGroupParameters cashGroup; MarketParameters market; PortfolioAsset[] portfolio; AssetRateParameters assetRate; nTokenPortfolio nToken; } /// @notice Checks if an asset is active in the portfolio function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) { return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO; } /// @notice Checks if currency balances are active in the account returns them if true /// @return cash balance, nTokenBalance function _getCurrencyBalances(address account, bytes2 currencyBytes) private view returns (int256, int256) { if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // prettier-ignore ( int256 cashBalance, int256 nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, currencyId); return (cashBalance, nTokenBalance); } return (0, 0); } /// @notice Calculates the nToken asset value with a haircut set by governance /// @return the value of the account's nTokens after haircut, the nToken parameters function _getNTokenHaircutAssetPV( CashGroupParameters memory cashGroup, nTokenPortfolio memory nToken, int256 tokenBalance, uint256 blockTime ) internal view returns (int256, bytes6) { nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId); nToken.cashGroup = cashGroup; int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime); // (tokenBalance * nTokenValue * haircut) / totalSupply int256 nTokenHaircutAssetPV = tokenBalance .mul(nTokenAssetPV) .mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE])) .div(Constants.PERCENTAGE_DECIMALS) .div(nToken.totalSupply); // nToken.parameters is returned for use in liquidation return (nTokenHaircutAssetPV, nToken.parameters); } /// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and /// markets. The reason these are grouped together is because they both require storage reads of the same /// values. function _getPortfolioAndNTokenAssetValue( FreeCollateralFactors memory factors, int256 nTokenBalance, uint256 blockTime ) private view returns ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { // If the next asset matches the currency id then we need to calculate the cash group value if ( factors.portfolioIndex < factors.portfolio.length && factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId ) { // netPortfolioValue is in asset cash (netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue( factors.portfolio, factors.cashGroup, factors.market, blockTime, factors.portfolioIndex ); } else { netPortfolioValue = 0; } if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; nTokenParameters = 0; } } /// @notice Returns balance values for the bitmapped currency function _getBitmapBalanceValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns ( int256 cashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters ) { int256 nTokenBalance; // prettier-ignore ( cashBalance, nTokenBalance, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId); if (nTokenBalance > 0) { (nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV( factors.cashGroup, factors.nToken, nTokenBalance, blockTime ); } else { nTokenHaircutAssetValue = 0; } } /// @notice Returns portfolio value for the bitmapped currency function _getBitmapPortfolioValue( address account, uint256 blockTime, AccountContext memory accountContext, FreeCollateralFactors memory factors ) private view returns (int256) { (int256 netPortfolioValueUnderlying, bool bitmapHasDebt) = BitmapAssetsHandler.getifCashNetPresentValue( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, blockTime, factors.cashGroup, true // risk adjusted ); // Turns off has debt flag if it has changed bool contextHasAssetDebt = accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT; if (bitmapHasDebt && !contextHasAssetDebt) { // Turn on has debt accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; factors.updateContext = true; } else if (!bitmapHasDebt && contextHasAssetDebt) { // Turn off has debt accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; factors.updateContext = true; } // Return asset cash value return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying); } function _updateNetETHValue( uint256 currencyId, int256 netLocalAssetValue, FreeCollateralFactors memory factors ) private view returns (ETHRate memory) { ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId); // Converts to underlying first, ETH exchange rates are in underlying factors.netETHValue = factors.netETHValue.add( ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue)) ); return ethRate; } /// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account /// context needs to be updated. function getFreeCollateralStateful( address account, AccountContext memory accountContext, uint256 blockTime ) internal returns (int256, bool) { FreeCollateralFactors memory factors; bool hasCashDebt; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); if (netCashBalance < 0) hasCashDebt = true; int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(account, currencyBytes); if (netLocalAssetValue < 0) hasCashDebt = true; if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); // prettier-ignore ( int256 netPortfolioAssetValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioAssetValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { // NOTE: we must set the proper assetRate when we updateNetETHValue factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValue, factors); currencies = currencies << 16; } // Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e. // they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of // sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing // an account to do an extra free collateral check to turn off this setting. if ( accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT && !hasCashDebt ) { accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT; factors.updateContext = true; } return (factors.netETHValue, factors.updateContext); } /// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips /// all the update context logic. function getFreeCollateralView( address account, AccountContext memory accountContext, uint256 blockTime ) internal view returns (int256, int256[] memory) { FreeCollateralFactors memory factors; uint256 netLocalIndex; int256[] memory netLocalAssetValues = new int256[](10); if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId); // prettier-ignore ( int256 netCashBalance, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioAssetValue = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); netLocalAssetValues[netLocalIndex] = netCashBalance .add(nTokenHaircutAssetValue) .add(portfolioAssetValue); factors.assetRate = factors.cashGroup.assetRate; _updateNetETHValue( accountContext.bitmapCurrencyId, netLocalAssetValues[netLocalIndex], factors ); netLocalIndex++; } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); // Explicitly ensures that bitmap currency cannot be double counted require(currencyId != accountContext.bitmapCurrencyId); int256 nTokenBalance; (netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances( account, currencyBytes ); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupView(currencyId); // prettier-ignore ( int256 netPortfolioValue, int256 nTokenHaircutAssetValue, /* nTokenParameters */ ) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex] .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; } else { factors.assetRate = AssetRate.buildAssetRateView(currencyId); } _updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors); netLocalIndex++; currencies = currencies << 16; } return (factors.netETHValue, netLocalAssetValues); } /// @notice Calculates the net value of a currency within a portfolio, this is a bit /// convoluted to fit into the stack frame function _calculateLiquidationAssetValue( FreeCollateralFactors memory factors, LiquidationFactors memory liquidationFactors, bytes2 currencyBytes, bool setLiquidationFactors, uint256 blockTime ) private returns (int256) { uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS); (int256 netLocalAssetValue, int256 nTokenBalance) = _getCurrencyBalances(liquidationFactors.account, currencyBytes); if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) { factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId); (int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime); netLocalAssetValue = netLocalAssetValue .add(netPortfolioValue) .add(nTokenHaircutAssetValue); factors.assetRate = factors.cashGroup.assetRate; // If collateralCurrencyId is set to zero then this is a local currency liquidation if (setLiquidationFactors) { liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenParameters = nTokenParameters; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; } } else { factors.assetRate = AssetRate.buildAssetRateStateful(currencyId); } return netLocalAssetValue; } /// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information. function getLiquidationFactors( address account, AccountContext memory accountContext, uint256 blockTime, uint256 localCurrencyId, uint256 collateralCurrencyId ) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) { FreeCollateralFactors memory factors; LiquidationFactors memory liquidationFactors; // This is only set to reduce the stack size liquidationFactors.account = account; if (accountContext.isBitmapEnabled()) { factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId); (int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) = _getBitmapBalanceValue(account, blockTime, accountContext, factors); int256 portfolioBalance = _getBitmapPortfolioValue(account, blockTime, accountContext, factors); int256 netLocalAssetValue = netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance); factors.assetRate = factors.cashGroup.assetRate; ETHRate memory ethRate = _updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors); // If the bitmap currency id can only ever be the local currency where debt is held. // During enable bitmap we check that the account has no assets in their portfolio and // no cash debts. if (accountContext.bitmapCurrencyId == localCurrencyId) { liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // This will be the case during local currency or local fCash liquidation if (collateralCurrencyId == 0) { // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers. liquidationFactors.collateralCashGroup = factors.cashGroup; liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue; liquidationFactors.nTokenParameters = nTokenParameters; } } } else { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } bytes18 currencies = accountContext.activeCurrencies; while (currencies != 0) { bytes2 currencyBytes = bytes2(currencies); // This next bit of code here is annoyingly structured to get around stack size issues bool setLiquidationFactors; { uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); // Explicitly ensures that bitmap currency cannot be double counted require(tempId != accountContext.bitmapCurrencyId); setLiquidationFactors = (tempId == localCurrencyId && collateralCurrencyId == 0) || tempId == collateralCurrencyId; } int256 netLocalAssetValue = _calculateLiquidationAssetValue( factors, liquidationFactors, currencyBytes, setLiquidationFactors, blockTime ); uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS)); ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors); if (currencyId == collateralCurrencyId) { // Ensure that this is set even if the cash group is not loaded, it will not be // loaded if the account only has a cash balance and no nTokens or assets liquidationFactors.collateralCashGroup.assetRate = factors.assetRate; liquidationFactors.collateralAssetAvailable = netLocalAssetValue; liquidationFactors.collateralETHRate = ethRate; } else if (currencyId == localCurrencyId) { // This branch will not be entered if bitmap is enabled liquidationFactors.localAssetAvailable = netLocalAssetValue; liquidationFactors.localETHRate = ethRate; liquidationFactors.localAssetRate = factors.assetRate; // If this is local fCash liquidation, the cash group information is required // to calculate fCash haircuts and buffers and it will have been set in // _calculateLiquidationAssetValue above because the account must have fCash assets, // there is no need to set cash group in this branch. } currencies = currencies << 16; } liquidationFactors.netETHValue = factors.netETHValue; require(liquidationFactors.netETHValue < 0, "Sufficient collateral"); // Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash // netting which will make further calculations incorrect. if (accountContext.assetArrayLength > 0) { factors.portfolio = PortfolioHandler.getSortedPortfolio( account, accountContext.assetArrayLength ); } return (liquidationFactors, factors.portfolio); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../valuation/AssetHandler.sol"; import "../markets/Market.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; library SettlePortfolioAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; using PortfolioHandler for PortfolioState; using AssetHandler for PortfolioAsset; /// @dev Returns a SettleAmount array for the assets that will be settled function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime) private pure returns (SettleAmount[] memory) { uint256 currenciesSettled; uint256 lastCurrencyId = 0; if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0); // Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio // NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause // a revert, must wrap in an unchecked. for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // Assets settle on exactly blockTime if (asset.getSettlementDate() > blockTime) continue; // Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this // will work for the first asset if (lastCurrencyId != asset.currencyId) { lastCurrencyId = asset.currencyId; currenciesSettled++; } } // Actual currency ids will be set as we loop through the portfolio and settle assets SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled); if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId; return settleAmounts; } /// @notice Settles a portfolio array function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime) internal returns (SettleAmount[] memory) { AssetRateParameters memory settlementRate; SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime); MarketParameters memory market; if (settleAmounts.length == 0) return settleAmounts; uint256 settleAmountIndex; for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; uint256 settleDate = asset.getSettlementDate(); // Settlement date is on block time exactly if (settleDate > blockTime) continue; // On the first loop the lastCurrencyId is already set. if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) { // New currency in the portfolio settleAmountIndex += 1; settleAmounts[settleAmountIndex].currencyId = asset.currencyId; } int256 assetCash; if (asset.assetType == Constants.FCASH_ASSET_TYPE) { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); assetCash = settlementRate.convertFromUnderlying(asset.notional); portfolioState.deleteAsset(i); } else if (AssetHandler.isLiquidityToken(asset.assetType)) { Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate); int256 fCash; (assetCash, fCash) = market.removeLiquidity(asset.notional); // Assets mature exactly on block time if (asset.maturity > blockTime) { // If fCash has not yet matured then add it to the portfolio _settleLiquidityTokenTofCash(portfolioState, i, fCash); } else { // Gets or sets the settlement rate, only do this before settling fCash settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); // If asset has matured then settle fCash to asset cash assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash)); portfolioState.deleteAsset(i); } } settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex] .netCashChange .add(assetCash); } return settleAmounts; } /// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future function _settleLiquidityTokenTofCash( PortfolioState memory portfolioState, uint256 index, int256 fCash ) private pure { PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index]; // If the liquidity token's maturity is still in the future then we change the entry to be // an idiosyncratic fCash entry with the net fCash amount. if (index != 0) { // Check to see if the previous index is the matching fCash asset, this will be the case when the // portfolio is sorted PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1]; if ( fCashAsset.currencyId == liquidityToken.currencyId && fCashAsset.maturity == liquidityToken.maturity && fCashAsset.assetType == Constants.FCASH_ASSET_TYPE ) { // This fCash asset has not matured if we are settling to fCash fCashAsset.notional = fCashAsset.notional.add(fCash); fCashAsset.storageState = AssetStorageState.Update; portfolioState.deleteAsset(index); } } // We are going to delete this asset anyway, convert to an fCash position liquidityToken.assetType = Constants.FCASH_ASSET_TYPE; liquidityToken.notional = fCash; liquidityToken.storageState = AssetStorageState.Update; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../markets/AssetRate.sol"; import "../../global/LibStorage.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; /** * Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash * at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues * to correctly reference all actual maturities. fCash asset notional values are stored in *absolute* * time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime. * Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on * newSettleTime and the absolute times (maturities) that the previous bitmap references. */ library SettleBitmapAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Bitmap for bytes32; /// @notice Given a bitmap for a cash group and timestamps, will settle all assets /// that have matured and remap the bitmap to correspond to the current time. function settleBitmappedCashGroup( address account, uint256 currencyId, uint256 oldSettleTime, uint256 blockTime ) internal returns (int256 totalAssetCash, uint256 newSettleTime) { bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId); // This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and // `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason // that lastSettleBit is inclusive is that it refers to newSettleTime which always less // than the current block time. newSettleTime = DateTime.getTimeUTC0(blockTime); // If newSettleTime == oldSettleTime lastSettleBit will be zero require(newSettleTime >= oldSettleTime); // dev: new settle time before previous // Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until // the closest maturity that is less than newSettleTime. (uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime); if (lastSettleBit == 0) return (totalAssetCash, newSettleTime); // Returns the next bit that is set in the bitmap uint256 nextBitNum = bitmap.getNextBitNum(); while (nextBitNum != 0 && nextBitNum <= lastSettleBit) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); totalAssetCash = totalAssetCash.add( _settlefCashAsset(account, currencyId, maturity, blockTime) ); // Turn the bit off now that it is settled bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } bytes32 newBitmap; while (nextBitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); (uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity); require(isValid); // dev: invalid new bit num newBitmap = newBitmap.setBit(newBitNum, true); // Turn the bit off now that it is remapped bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap); } /// @dev Stateful settlement function to settle a bitmapped asset. Deletes the /// asset from storage after calculating it. function _settlefCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 blockTime ) private returns (int256 assetCash) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); int256 notional = store[account][currencyId][maturity].notional; // Gets the current settlement rate or will store a new settlement rate if it does not // yet exist. AssetRateParameters memory rate = AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime); assetCash = rate.convertFromUnderlying(notional); delete store[account][currencyId][maturity]; return assetCash; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../markets/DateTime.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AssetHandler { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; function isLiquidityToken(uint256 assetType) internal pure returns (bool) { return assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX; } /// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method /// calculates the settlement date for any PortfolioAsset. function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) { require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type // 3 month tokens and fCash tokens settle at maturity if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1); // Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is: // maturity = tRef + marketLength // Here we calculate: // tRef = (maturity - marketLength) + 90 days return asset.maturity.sub(marketLength).add(Constants.QUARTER); } /// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity. /// The formula is: e^(-rate * timeToMaturity). function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)); expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue)); expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64); int256 discountFactor = ABDKMath64x64.toInt(expValue); return discountFactor; } /// @notice Present value of an fCash asset without any risk adjustments. function getPresentfCashValue( int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate); require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more /// heavily than the oracle rate given and vice versa for negative fCash. function getRiskAdjustedPresentfCashValue( CashGroupParameters memory cashGroup, int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor; if (notional > 0) { // If fCash is positive then discounting by a higher rate will result in a smaller // discount factor (e ^ -x), meaning a lower positive fCash value. discountFactor = getDiscountFactor( timeToMaturity, oracleRate.add(cashGroup.getfCashHaircut()) ); } else { uint256 debtBuffer = cashGroup.getDebtBuffer(); // If the adjustment exceeds the oracle rate we floor the value of the fCash // at the notional value. We don't want to require the account to hold more than // absolutely required. if (debtBuffer >= oracleRate) return notional; discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer); } require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Returns the non haircut claims on cash and fCash by the liquidity token. function getCashClaims(PortfolioAsset memory token, MarketParameters memory market) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity); fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity); } /// @notice Returns the haircut claims on cash and fCash function getHaircutCashClaims( PortfolioAsset memory token, MarketParameters memory market, CashGroupParameters memory cashGroup ) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch // This won't overflow, the liquidity token haircut is stored as an uint8 int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType)); assetCash = _calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity); fCash = _calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity); return (assetCash, fCash); } /// @dev This is here to clean up the stack in getHaircutCashClaims function _calcToken( int256 numerator, int256 tokens, int256 haircut, int256 liquidity ) private pure returns (int256) { return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity); } /// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists) function getLiquidityTokenValue( uint256 index, CashGroupParameters memory cashGroup, MarketParameters memory market, PortfolioAsset[] memory assets, uint256 blockTime, bool riskAdjusted ) internal view returns (int256, int256) { PortfolioAsset memory liquidityToken = assets[index]; { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex( cashGroup.maxMarketIndex, liquidityToken.maturity, blockTime ); // Liquidity tokens can never be idiosyncratic require(!idiosyncratic); // dev: idiosyncratic liquidity token // This market will always be initialized, if a liquidity token exists that means the // market has some liquidity in it. cashGroup.loadMarket(market, marketIndex, true, blockTime); } int256 assetCashClaim; int256 fCashClaim; if (riskAdjusted) { (assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup); } else { (assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market); } // Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and // in that case we know the previous asset will be the matching fCash asset if (index > 0) { PortfolioAsset memory maybefCash = assets[index - 1]; if ( maybefCash.assetType == Constants.FCASH_ASSET_TYPE && maybefCash.currencyId == liquidityToken.currencyId && maybefCash.maturity == liquidityToken.maturity ) { // Net off the fCashClaim here and we will discount it to present value in the second pass. // WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio! maybefCash.notional = maybefCash.notional.add(fCashClaim); // This state will prevent the fCash asset from being stored. maybefCash.storageState = AssetStorageState.RevertIfStored; return (assetCashClaim, 0); } } // If not matching fCash asset found then get the pv directly if (riskAdjusted) { int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate ); return (assetCashClaim, pv); } else { int256 pv = getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate); return (assetCashClaim, pv); } } /// @notice Returns present value of all assets in the cash group as asset cash and the updated /// portfolio index where the function has ended. /// @return the value of the cash group in asset cash function getNetCashGroupValue( PortfolioAsset[] memory assets, CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 blockTime, uint256 portfolioIndex ) internal view returns (int256, uint256) { int256 presentValueAsset; int256 presentValueUnderlying; // First calculate value of liquidity tokens because we need to net off fCash value // before discounting to present value for (uint256 i = portfolioIndex; i < assets.length; i++) { if (!isLiquidityToken(assets[i].assetType)) continue; if (assets[i].currencyId != cashGroup.currencyId) break; (int256 assetCashClaim, int256 pv) = getLiquidityTokenValue( i, cashGroup, market, assets, blockTime, true // risk adjusted ); presentValueAsset = presentValueAsset.add(assetCashClaim); presentValueUnderlying = presentValueUnderlying.add(pv); } uint256 j = portfolioIndex; for (; j < assets.length; j++) { PortfolioAsset memory a = assets[j]; if (a.assetType != Constants.FCASH_ASSET_TYPE) continue; // If we hit a different currency id then we've accounted for all assets in this currency // j will mark the index where we don't have this currency anymore if (a.currencyId != cashGroup.currencyId) break; uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime); int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, a.notional, a.maturity, blockTime, oracleRate ); presentValueUnderlying = presentValueUnderlying.add(pv); } presentValueAsset = presentValueAsset.add( cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying) ); return (presentValueAsset, j); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; import "./Constants.sol"; import "../../interfaces/notional/IRewarder.sol"; import "../../interfaces/aave/ILendingPool.sol"; library LibStorage { /// @dev Offset for the initial slot in lib storage, gives us this number of storage slots /// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it. uint256 private constant STORAGE_SLOT_BASE = 1000000; /// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX /// in practice. It is possible to exceed that value during liquidation up to 14 potential assets. uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @dev Storage IDs for storage buckets. Each id maps to an internal storage /// slot used for a particular mapping /// WARNING: APPEND ONLY enum StorageId { Unused, AccountStorage, nTokenContext, nTokenAddress, nTokenDeposit, nTokenInitialization, Balance, Token, SettlementRate, CashGroup, Market, AssetsBitmap, ifCashBitmap, PortfolioArray, // WARNING: this nTokenTotalSupply storage object was used for a buggy version // of the incentives calculation. It should only be used for accounts who have // not claimed before the migration nTokenTotalSupply_deprecated, AssetRate, ExchangeRate, nTokenTotalSupply, SecondaryIncentiveRewarder, LendingPool } /// @dev Mapping from an account address to account context function getAccountStorage() internal pure returns (mapping(address => AccountContext) storage store) { uint256 slot = _getStorageSlot(StorageId.AccountStorage); assembly { store.slot := slot } } /// @dev Mapping from an nToken address to nTokenContext function getNTokenContextStorage() internal pure returns (mapping(address => nTokenContext) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenContext); assembly { store.slot := slot } } /// @dev Mapping from currency id to nTokenAddress function getNTokenAddressStorage() internal pure returns (mapping(uint256 => address) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenAddress); assembly { store.slot := slot } } /// @dev Mapping from currency id to uint32 fixed length array of /// deposit factors. Deposit shares and leverage thresholds are stored striped to /// reduce the number of storage reads. function getNTokenDepositStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenDeposit); assembly { store.slot := slot } } /// @dev Mapping from currency id to fixed length array of initialization factors, /// stored striped like deposit shares. function getNTokenInitStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenInitialization); assembly { store.slot := slot } } /// @dev Mapping from account to currencyId to it's balance storage for that currency function getBalanceStorage() internal pure returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Balance); assembly { store.slot := slot } } /// @dev Mapping from currency id to a boolean for underlying or asset token to /// the TokenStorage function getTokenStorage() internal pure returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Token); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its corresponding SettlementRate function getSettlementRateStorage() internal pure returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.SettlementRate); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its tightly packed cash group parameters function getCashGroupStorage() internal pure returns (mapping(uint256 => bytes32) storage store) { uint256 slot = _getStorageSlot(StorageId.CashGroup); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to settlement date for a market function getMarketStorage() internal pure returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.Market); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its assets bitmap function getAssetsBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => bytes32)) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetsBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance function getifCashBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.ifCashBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to its fixed length array of portfolio assets function getPortfolioArrayStorage() internal pure returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store) { uint256 slot = _getStorageSlot(StorageId.PortfolioArray); assembly { store.slot := slot } } function getDeprecatedNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated); assembly { store.slot := slot } } /// @dev Mapping from nToken address to its total supply values function getNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and asset for trading /// and free collateral. Mapping is from currency id to rate storage object. function getAssetRateStorage() internal pure returns (mapping(uint256 => AssetRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetRate); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and ETH for free /// collateral purposes. Mapping is from currency id to rate storage object. function getExchangeRateStorage() internal pure returns (mapping(uint256 => ETHRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.ExchangeRate); assembly { store.slot := slot } } /// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists function getSecondaryIncentiveRewarder() internal pure returns (mapping(address => IRewarder) storage store) { uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder); assembly { store.slot := slot } } /// @dev Returns the address of the lending pool function getLendingPool() internal pure returns (LendingPoolStorage storage store) { uint256 slot = _getStorageSlot(StorageId.LendingPool); assembly { store.slot := slot } } /// @dev Get the storage slot given a storage ID. /// @param storageId An entry in `StorageId` /// @return slot The storage slot. function _getStorageSlot(StorageId storageId) private pure returns (uint256 slot) { // This should never overflow with a reasonable `STORAGE_SLOT_EXP` // because Solidity will do a range check on `storageId` during the cast. return uint256(storageId) + STORAGE_SLOT_BASE; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../AccountContextHandler.sol"; import "../markets/CashGroup.sol"; import "../valuation/AssetHandler.sol"; import "../../math/Bitmap.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library BitmapAssetsHandler { using SafeMath for uint256; using SafeInt256 for int256; using Bitmap for bytes32; using CashGroup for CashGroupParameters; using AccountContextHandler for AccountContext; function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) { mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); return store[account][currencyId]; } function setAssetsBitmap( address account, uint256 currencyId, bytes32 assetsBitmap ) internal { require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets"); mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); store[account][currencyId] = assetsBitmap; } function getifCashNotional( address account, uint256 currencyId, uint256 maturity ) internal view returns (int256 notional) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); return store[account][currencyId][maturity].notional; } /// @notice Adds multiple assets to a bitmap portfolio function addMultipleifCashAssets( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal { require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set uint256 currencyId = accountContext.bitmapCurrencyId; for (uint256 i; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets int256 finalNotional; finalNotional = addifCashAsset( account, currencyId, asset.maturity, accountContext.nextSettleTime, asset.notional ); if (finalNotional < 0) accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } } /// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory /// but not in storage. /// @return the updated assets bitmap and the final notional amount function addifCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 nextSettleTime, int256 notional ) internal returns (int256) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; (uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity); require(isExact); // dev: invalid maturity in set ifcash asset if (assetsBitmap.isBitSet(bitNum)) { // Bit is set so we read and update the notional amount int256 finalNotional = notional.add(fCashSlot.notional); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); // If the new notional is zero then turn off the bit if (finalNotional == 0) { assetsBitmap = assetsBitmap.setBit(bitNum, false); } setAssetsBitmap(account, currencyId, assetsBitmap); return finalNotional; } if (notional != 0) { // Bit is not set so we turn it on and update the mapping directly, no read required. require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(notional); assetsBitmap = assetsBitmap.setBit(bitNum, true); setAssetsBitmap(account, currencyId, assetsBitmap); } return notional; } /// @notice Returns the present value of an asset function getPresentValue( address account, uint256 currencyId, uint256 maturity, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256) { int256 notional = getifCashNotional(account, currencyId, maturity); // In this case the asset has matured and the total value is just the notional amount if (maturity <= blockTime) { return notional; } else { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); if (riskAdjusted) { return AssetHandler.getRiskAdjustedPresentfCashValue( cashGroup, notional, maturity, blockTime, oracleRate ); } else { return AssetHandler.getPresentfCashValue( notional, maturity, blockTime, oracleRate ); } } } function getNetPresentValueFromBitmap( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted, bytes32 assetsBitmap ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 pv = getPresentValue( account, currencyId, maturity, blockTime, cashGroup, riskAdjusted ); totalValueUnderlying = totalValueUnderlying.add(pv); if (pv < 0) hasDebt = true; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } } /// @notice Get the net present value of all the ifCash assets function getifCashNetPresentValue( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); return getNetPresentValueFromBitmap( account, currencyId, nextSettleTime, blockTime, cashGroup, riskAdjusted, assetsBitmap ); } /// @notice Returns the ifCash assets as an array function getifCashArray( address account, uint256 currencyId, uint256 nextSettleTime ) internal view returns (PortfolioAsset[] memory) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 index = assetsBitmap.totalBitsSet(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 notional = getifCashNotional(account, currencyId, maturity); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notional; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../interfaces/chainlink/AggregatorV2V3Interface.sol"; import "../../interfaces/notional/AssetRateAdapter.sol"; /// @notice Different types of internal tokens /// - UnderlyingToken: underlying asset for a cToken (except for Ether) /// - cToken: Compound interest bearing token /// - cETH: Special handling for cETH tokens /// - Ether: the one and only /// - NonMintable: tokens that do not have an underlying (therefore not cTokens) /// - aToken: Aave interest bearing tokens enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken} /// @notice Specifies the different trade action types in the system. Each trade action type is /// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the /// 32 byte trade action object. The schemas for each trade action type are defined below. enum TradeActionType { // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused) Lend, // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused) Borrow, // (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) AddLiquidity, // (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) RemoveLiquidity, // (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused) PurchaseNTokenResidual, // (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle) SettleCashDebt } /// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades enum DepositActionType { // No deposit action None, // Deposit asset cash, depositActionAmount is specified in asset cash external precision DepositAsset, // Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token // external precision DepositUnderlying, // Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of // nTokens into the account DepositAssetAndMintNToken, // Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens DepositUnderlyingAndMintNToken, // Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action // because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert. RedeemNToken, // Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in // Notional internal 8 decimal precision. ConvertCashToNToken } /// @notice Used internally for PortfolioHandler state enum AssetStorageState {NoChange, Update, Delete, RevertIfStored} /****** Calldata objects ******/ /// @notice Defines a balance action for batchAction struct BalanceAction { // Deposit action to take (if any) DepositActionType actionType; uint16 currencyId; // Deposit action amount must correspond to the depositActionType, see documentation above. uint256 depositActionAmount; // Withdraw an amount of asset cash specified in Notional internal 8 decimal precision uint256 withdrawAmountInternalPrecision; // If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash // residual left from trading. bool withdrawEntireCashBalance; // If set to true, will redeem asset cash to the underlying token on withdraw. bool redeemToUnderlying; } /// @notice Defines a balance action with a set of trades to do as well struct BalanceActionWithTrades { DepositActionType actionType; uint16 currencyId; uint256 depositActionAmount; uint256 withdrawAmountInternalPrecision; bool withdrawEntireCashBalance; bool redeemToUnderlying; // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation bytes32[] trades; } /****** In memory objects ******/ /// @notice Internal object that represents settled cash balances struct SettleAmount { uint256 currencyId; int256 netCashChange; } /// @notice Internal object that represents a token struct Token { address tokenAddress; bool hasTransferFee; int256 decimals; TokenType tokenType; uint256 maxCollateralBalance; } /// @notice Internal object that represents an nToken portfolio struct nTokenPortfolio { CashGroupParameters cashGroup; PortfolioState portfolioState; int256 totalSupply; int256 cashBalance; uint256 lastInitializedTime; bytes6 parameters; address tokenAddress; } /// @notice Internal object used during liquidation struct LiquidationFactors { address account; // Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision int256 netETHValue; // Amount of net local currency asset cash before haircuts and buffers available int256 localAssetAvailable; // Amount of net collateral currency asset cash before haircuts and buffers available int256 collateralAssetAvailable; // Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based // on liquidation type int256 nTokenHaircutAssetValue; // nToken parameters for calculating liquidation amount bytes6 nTokenParameters; // ETH exchange rate from local currency to ETH ETHRate localETHRate; // ETH exchange rate from collateral currency to ETH ETHRate collateralETHRate; // Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required AssetRateParameters localAssetRate; // Used during currency liquidations if the account has liquidity tokens CashGroupParameters collateralCashGroup; // Used during currency liquidations if it is only a calculation, defaults to false bool isCalculation; } /// @notice Internal asset array portfolio state struct PortfolioState { // Array of currently stored assets PortfolioAsset[] storedAssets; // Array of new assets to add PortfolioAsset[] newAssets; uint256 lastNewAssetIndex; // Holds the length of stored assets after accounting for deleted assets uint256 storedAssetLength; } /// @notice In memory ETH exchange rate used during free collateral calculation. struct ETHRate { // The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle int256 rateDecimals; // The exchange rate from base to ETH (if rate invert is required it is already done) int256 rate; // Amount of buffer as a multiple with a basis of 100 applied to negative balances. int256 buffer; // Amount of haircut as a multiple with a basis of 100 applied to positive balances int256 haircut; // Liquidation discount as a multiple with a basis of 100 applied to the exchange rate // as an incentive given to liquidators. int256 liquidationDiscount; } /// @notice Internal object used to handle balance state during a transaction struct BalanceState { uint16 currencyId; // Cash balance stored in balance state at the beginning of the transaction int256 storedCashBalance; // nToken balance stored at the beginning of the transaction int256 storedNTokenBalance; // The net cash change as a result of asset settlement or trading int256 netCashChange; // Net asset transfers into or out of the account int256 netAssetTransferInternalPrecision; // Net token transfers into or out of the account int256 netNTokenTransfer; // Net token supply change from minting or redeeming int256 netNTokenSupplyChange; // The last time incentives were claimed for this currency uint256 lastClaimTime; // Accumulator for incentives that the account no longer has a claim over uint256 accountIncentiveDebt; } /// @dev Asset rate used to convert between underlying cash and asset cash struct AssetRateParameters { // Address of the asset rate oracle AssetRateAdapter rateOracle; // The exchange rate from base to quote (if invert is required it is already done) int256 rate; // The decimals of the underlying, the rate converts to the underlying decimals int256 underlyingDecimals; } /// @dev Cash group when loaded into memory struct CashGroupParameters { uint16 currencyId; uint256 maxMarketIndex; AssetRateParameters assetRate; bytes32 data; } /// @dev A portfolio asset when loaded in memory struct PortfolioAsset { // Asset currency id uint256 currencyId; uint256 maturity; // Asset type, fCash or liquidity token. uint256 assetType; // fCash amount or liquidity token amount int256 notional; // Used for managing portfolio asset state uint256 storageSlot; // The state of the asset for when it is written to storage AssetStorageState storageState; } /// @dev Market object as represented in memory struct MarketParameters { bytes32 storageSlot; uint256 maturity; // Total amount of fCash available for purchase in the market. int256 totalfCash; // Total amount of cash available for purchase in the market. int256 totalAssetCash; // Total amount of liquidity tokens (representing a claim on liquidity) in the market. int256 totalLiquidity; // This is the previous annualized interest rate in RATE_PRECISION that the market traded // at. This is used to calculate the rate anchor to smooth interest rates over time. uint256 lastImpliedRate; // Time lagged version of lastImpliedRate, used to value fCash assets at market rates while // remaining resistent to flash loan attacks. uint256 oracleRate; // This is the timestamp of the previous trade uint256 previousTradeTime; } /****** Storage objects ******/ /// @dev Token object in storage: /// 20 bytes for token address /// 1 byte for hasTransferFee /// 1 byte for tokenType /// 1 byte for tokenDecimals /// 9 bytes for maxCollateralBalance (may not always be set) struct TokenStorage { // Address of the token address tokenAddress; // Transfer fees will change token deposit behavior bool hasTransferFee; TokenType tokenType; uint8 decimalPlaces; // Upper limit on how much of this token the contract can hold at any time uint72 maxCollateralBalance; } /// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes. struct ETHRateStorage { // Address of the rate oracle AggregatorV2V3Interface rateOracle; // The decimal places of precision that the rate oracle uses uint8 rateDecimalPlaces; // True of the exchange rate must be inverted bool mustInvert; // NOTE: both of these governance values are set with BUFFER_DECIMALS precision // Amount of buffer to apply to the exchange rate for negative balances. uint8 buffer; // Amount of haircut to apply to the exchange rate for positive balances uint8 haircut; // Liquidation discount in percentage point terms, 106 means a 6% discount uint8 liquidationDiscount; } /// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes. struct AssetRateStorage { // Address of the rate oracle AssetRateAdapter rateOracle; // The decimal places of the underlying asset uint8 underlyingDecimalPlaces; } /// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts /// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there /// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the /// length. struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; } /// @dev Holds account level context information used to determine settlement and /// free collateral actions. Total storage is 28 bytes struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account's asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; } /// @dev Holds nToken context information mapped via the nToken address, total storage is /// 16 bytes struct nTokenContext { // Currency id that the nToken represents uint16 currencyId; // Annual incentive emission rate denominated in WHOLE TOKENS (multiply by // INTERNAL_TOKEN_PRECISION to get the actual rate) uint32 incentiveAnnualEmissionRate; // The last block time at utc0 that the nToken was initialized at, zero if it // has never been initialized uint32 lastInitializedTime; // Length of the asset array, refers to the number of liquidity tokens an nToken // currently holds uint8 assetArrayLength; // Each byte is a specific nToken parameter bytes5 nTokenParameters; // Reserved bytes for future usage bytes15 _unused; // Set to true if a secondary rewarder is set bool hasSecondaryRewarder; } /// @dev Holds account balance information, total storage 32 bytes struct BalanceStorage { // Number of nTokens held by the account uint80 nTokenBalance; // Last time the account claimed their nTokens uint32 lastClaimTime; // Incentives that the account no longer has a claim over uint56 accountIncentiveDebt; // Cash balance of the account int88 cashBalance; } /// @dev Holds information about a settlement rate, total storage 25 bytes struct SettlementRateStorage { uint40 blockTime; uint128 settlementRate; uint8 underlyingDecimalPlaces; } /// @dev Holds information about a market, total storage is 42 bytes so this spans /// two storage words struct MarketStorage { // Total fCash in the market uint80 totalfCash; // Total asset cash in the market uint80 totalAssetCash; // Last annualized interest rate the market traded at uint32 lastImpliedRate; // Last recorded oracle rate for the market uint32 oracleRate; // Last time a trade was made uint32 previousTradeTime; // This is stored in slot + 1 uint80 totalLiquidity; } struct ifCashStorage { // Notional amount of fCash at the slot, limited to int128 to allow for // future expansion int128 notional; } /// @dev A single portfolio asset in storage, total storage of 19 bytes struct PortfolioAssetStorage { // Currency Id for the asset uint16 currencyId; // Maturity of the asset uint40 maturity; // Asset type (fCash or Liquidity Token marker) uint8 assetType; // Notional int88 notional; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. This is the deprecated version struct nTokenTotalSupplyStorage_deprecated { // Total supply of the nToken uint96 totalSupply; // Integral of the total supply used for calculating the average total supply uint128 integralTotalSupply; // Last timestamp the supply value changed, used for calculating the integralTotalSupply uint32 lastSupplyChangeTime; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes. struct nTokenTotalSupplyStorage { // Total supply of the nToken uint96 totalSupply; // How many NOTE incentives should be issued per nToken in 1e18 precision uint128 accumulatedNOTEPerNToken; // Last timestamp when the accumulation happened uint32 lastAccumulatedTime; } /// @dev Used in view methods to return account balances in a developer friendly manner struct AccountBalance { uint16 currencyId; int256 cashBalance; int256 nTokenBalance; uint256 lastClaimTime; uint256 accountIncentiveDebt; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title All shared constants for the Notional system should be declared here. library Constants { uint8 internal constant CETH_DECIMAL_PLACES = 8; // Token precision used for all internal balances, TokenHandler library ensures that we // limit the dust amount caused by precision mismatches int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8; uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18; // ETH will be initialized as the first currency uint256 internal constant ETH_CURRENCY_ID = 1; uint8 internal constant ETH_DECIMAL_PLACES = 18; int256 internal constant ETH_DECIMALS = 1e18; // Used to prevent overflow when converting decimal places to decimal precision values via // 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this // constraint when storing decimal places in governance. uint256 internal constant MAX_DECIMAL_PLACES = 36; // Address of the reserve account address internal constant RESERVE = address(0); // Most significant bit bytes32 internal constant MSB = 0x8000000000000000000000000000000000000000000000000000000000000000; // Each bit set in this mask marks where an active market should be in the bitmap // if the first bit refers to the reference time. Used to detect idiosyncratic // fcash in the nToken accounts bytes32 internal constant ACTIVE_MARKETS_MASK = ( MSB >> ( 90 - 1) | // 3 month MSB >> (105 - 1) | // 6 month MSB >> (135 - 1) | // 1 year MSB >> (147 - 1) | // 2 year MSB >> (183 - 1) | // 5 year MSB >> (211 - 1) | // 10 year MSB >> (251 - 1) // 20 year ); // Basis for percentages int256 internal constant PERCENTAGE_DECIMALS = 100; // Max number of traded markets, also used as the maximum number of assets in a portfolio array uint256 internal constant MAX_TRADED_MARKET_INDEX = 7; // Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral // for a bitmap portfolio uint256 internal constant MAX_BITMAP_ASSETS = 20; uint256 internal constant FIVE_MINUTES = 300; // Internal date representations, note we use a 6/30/360 week/month/year convention here uint256 internal constant DAY = 86400; // We use six day weeks to ensure that all time references divide evenly uint256 internal constant WEEK = DAY * 6; uint256 internal constant MONTH = WEEK * 5; uint256 internal constant QUARTER = MONTH * 3; uint256 internal constant YEAR = QUARTER * 4; // These constants are used in DateTime.sol uint256 internal constant DAYS_IN_WEEK = 6; uint256 internal constant DAYS_IN_MONTH = 30; uint256 internal constant DAYS_IN_QUARTER = 90; // Offsets for each time chunk denominated in days uint256 internal constant MAX_DAY_OFFSET = 90; uint256 internal constant MAX_WEEK_OFFSET = 360; uint256 internal constant MAX_MONTH_OFFSET = 2160; uint256 internal constant MAX_QUARTER_OFFSET = 7650; // Offsets for each time chunk denominated in bits uint256 internal constant WEEK_BIT_OFFSET = 90; uint256 internal constant MONTH_BIT_OFFSET = 135; uint256 internal constant QUARTER_BIT_OFFSET = 195; // This is a constant that represents the time period that all rates are normalized by, 360 days uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY; // Number of decimal places that rates are stored in, equals 100% int256 internal constant RATE_PRECISION = 1e9; // One basis point in RATE_PRECISION terms uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000); // Used to when calculating the amount to deleverage of a market when minting nTokens uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT; // Used for scaling cash group factors uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT; // Used for residual purchase incentive and cash withholding buffer uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT; // This is the ABDK64x64 representation of RATE_PRECISION // RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION) int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000; int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176; // Limit the market proportion so that borrowing cannot hit extremely high interest rates int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100; uint8 internal constant FCASH_ASSET_TYPE = 1; // Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed) uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2; uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8; // Used for converting bool to bytes1, solidity does not have a native conversion // method for this bytes1 internal constant BOOL_FALSE = 0x00; bytes1 internal constant BOOL_TRUE = 0x01; // Account context flags bytes1 internal constant HAS_ASSET_DEBT = 0x01; bytes1 internal constant HAS_CASH_DEBT = 0x02; bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000; bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000; bytes2 internal constant UNMASK_FLAGS = 0x3FFF; uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS); // Equal to 100% of all deposit amounts for nToken liquidity across fCash markets. int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8; // nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned // in nTokenHandler. Each constant represents a position in the byte array. uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0; uint8 internal constant CASH_WITHHOLDING_BUFFER = 1; uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2; uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3; uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4; // Liquidation parameters // Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account // requires more collateral to be liquidated int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40; // Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30; // Pause Router liquidation enabled states bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01; bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02; bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04; bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library DateTime { using SafeMath for uint256; /// @notice Returns the current reference time which is how all the AMM dates are calculated. function getReferenceTime(uint256 blockTime) internal pure returns (uint256) { require(blockTime >= Constants.QUARTER); return blockTime - (blockTime % Constants.QUARTER); } /// @notice Truncates a date to midnight UTC time function getTimeUTC0(uint256 time) internal pure returns (uint256) { require(time >= Constants.DAY); return time - (time % Constants.DAY); } /// @notice These are the predetermined market offsets for trading /// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group. function getTradedMarket(uint256 index) internal pure returns (uint256) { if (index == 1) return Constants.QUARTER; if (index == 2) return 2 * Constants.QUARTER; if (index == 3) return Constants.YEAR; if (index == 4) return 2 * Constants.YEAR; if (index == 5) return 5 * Constants.YEAR; if (index == 6) return 10 * Constants.YEAR; if (index == 7) return 20 * Constants.YEAR; revert("Invalid index"); } /// @notice Determines if the maturity falls on one of the valid on chain market dates. function isValidMarketMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); if (maturity % Constants.QUARTER != 0) return false; uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true; } return false; } /// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case. function isValidMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { uint256 tRef = DateTime.getReferenceTime(blockTime); uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex)); // Cannot trade past max maturity if (maturity > maxMaturity) return false; // prettier-ignore (/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity); return isValid; } /// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic /// will return the nearest market index that is larger than the maturity. /// @return uint marketIndex, bool isIdiosyncratic function getMarketIndex( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (uint256, bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i)); // If market matches then is not idiosyncratic if (marketMaturity == maturity) return (i, false); // Returns the market that is immediately greater than the maturity if (marketMaturity > maturity) return (i, true); } revert("CG: no market found"); } /// @notice Given a bit number and the reference time of the first bit, returns the bit number /// of a given maturity. /// @return bitNum and a true or false if the maturity falls on the exact bit function getBitNumFromMaturity(uint256 blockTime, uint256 maturity) internal pure returns (uint256, bool) { uint256 blockTimeUTC0 = getTimeUTC0(blockTime); // Maturities must always divide days evenly if (maturity % Constants.DAY != 0) return (0, false); // Maturity cannot be in the past if (blockTimeUTC0 >= maturity) return (0, false); // Overflow check done above // daysOffset has no remainders, checked above uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY; // These if statements need to fall through to the next one if (daysOffset <= Constants.MAX_DAY_OFFSET) { return (daysOffset, true); } else if (daysOffset <= Constants.MAX_WEEK_OFFSET) { // (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0 // (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion // This returns the offset from the previous max offset in days uint256 offsetInDays = daysOffset - Constants.MAX_DAY_OFFSET + (blockTimeUTC0 % Constants.WEEK) / Constants.DAY; return ( // This converts the offset in days to its corresponding bit position, truncating down // if it does not divide evenly into DAYS_IN_WEEK Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK, (offsetInDays % Constants.DAYS_IN_WEEK) == 0 ); } else if (daysOffset <= Constants.MAX_MONTH_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_WEEK_OFFSET + (blockTimeUTC0 % Constants.MONTH) / Constants.DAY; return ( Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH, (offsetInDays % Constants.DAYS_IN_MONTH) == 0 ); } else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_MONTH_OFFSET + (blockTimeUTC0 % Constants.QUARTER) / Constants.DAY; return ( Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER, (offsetInDays % Constants.DAYS_IN_QUARTER) == 0 ); } // This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20 // year max maturity return (256, false); } /// @notice Given a bit number and a block time returns the maturity that the bit number /// should reference. Bit numbers are one indexed. function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum) internal pure returns (uint256) { require(bitNum != 0); // dev: cash group get maturity from bit num is zero require(bitNum <= 256); // dev: cash group get maturity from bit num overflow uint256 blockTimeUTC0 = getTimeUTC0(blockTime); uint256 firstBit; if (bitNum <= Constants.WEEK_BIT_OFFSET) { return blockTimeUTC0 + bitNum * Constants.DAY; } else if (bitNum <= Constants.MONTH_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_DAY_OFFSET * Constants.DAY - // This backs up to the day that is divisible by a week (blockTimeUTC0 % Constants.WEEK); return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK; } else if (bitNum <= Constants.QUARTER_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_WEEK_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.MONTH); return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH; } else { firstBit = blockTimeUTC0 + Constants.MAX_MONTH_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.QUARTER); return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER; } } } // 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.5.0 || ^0.6.0 || ^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) { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * 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 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 pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: GPL-v3 pragma solidity >=0.7.0; /// @notice Used as a wrapper for tokens that are interest bearing for an /// underlying token. Follows the cToken interface, however, can be adapted /// for other interest bearing tokens. interface AssetRateAdapter { function token() external view returns (address); function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function underlying() external view returns (address); function getExchangeRateStateful() external returns (int256); function getExchangeRateView() external view returns (int256); function getAnnualizedSupplyRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; interface IRewarder { function claimRewards( address account, uint16 currencyId, uint256 nTokenBalanceBefore, uint256 nTokenBalanceAfter, int256 netNTokenSupplyChange, uint256 NOTETokensClaimed ) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; struct LendingPoolStorage { ILendingPool lendingPool; } interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (ReserveData memory); // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TokenHandler.sol"; import "../nToken/nTokenHandler.sol"; import "../nToken/nTokenSupply.sol"; import "../../math/SafeInt256.sol"; import "../../external/MigrateIncentives.sol"; import "../../../interfaces/notional/IRewarder.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Incentives { using SafeMath for uint256; using SafeInt256 for int256; /// @notice Calculates the total incentives to claim including those claimed under the previous /// less accurate calculation. Once an account is migrated it will only claim incentives under /// the more accurate regime function calculateIncentivesToClaim( BalanceState memory balanceState, address tokenAddress, uint256 accumulatedNOTEPerNToken, uint256 finalNTokenBalance ) internal view returns (uint256 incentivesToClaim) { if (balanceState.lastClaimTime > 0) { // If lastClaimTime is set then the account had incentives under the // previous regime. Will calculate the final amount of incentives to claim here // under the previous regime. incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation( tokenAddress, balanceState.storedNTokenBalance.toUint(), balanceState.lastClaimTime, // In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under // the old calculation balanceState.accountIncentiveDebt ); // This marks the account as migrated and lastClaimTime will no longer be used balanceState.lastClaimTime = 0; // This value will be set immediately after this, set this to zero so that the calculation // establishes a new baseline. balanceState.accountIncentiveDebt = 0; } // If an account was migrated then they have no accountIncentivesDebt and should accumulate // incentives based on their share since the new regime calculation started. // If an account is just initiating their nToken balance then storedNTokenBalance will be zero // and they will have no incentives to claim. // This calculation uses storedNTokenBalance which is the balance of the account up until this point, // this is important to ensure that the account does not claim for nTokens that they will mint or // redeem on a going forward basis. // The calculation below has the following precision: // storedNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION incentivesToClaim = incentivesToClaim.add( balanceState.storedNTokenBalance.toUint() .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION) .sub(balanceState.accountIncentiveDebt) ); // Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion // of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance // here instead of storedNTokenBalance to mark the overall incentives claim that the account // does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt // because accumulatedNOTEPerNToken is already an aggregated value. // The calculation below has the following precision: // finalNTokenBalance (INTERNAL_TOKEN_PRECISION) // MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION) // DIV INCENTIVE_ACCUMULATION_PRECISION // = INTERNAL_TOKEN_PRECISION balanceState.accountIncentiveDebt = finalNTokenBalance .mul(accumulatedNOTEPerNToken) .div(Constants.INCENTIVE_ACCUMULATION_PRECISION); } /// @notice Incentives must be claimed every time nToken balance changes. /// @dev BalanceState.accountIncentiveDebt is updated in place here function claimIncentives( BalanceState memory balanceState, address account, uint256 finalNTokenBalance ) internal returns (uint256 incentivesToClaim) { uint256 blockTime = block.timestamp; address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId); // This will updated the nToken storage and return what the accumulatedNOTEPerNToken // is up until this current block time in 1e18 precision uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply( tokenAddress, balanceState.netNTokenSupplyChange, blockTime ); incentivesToClaim = calculateIncentivesToClaim( balanceState, tokenAddress, accumulatedNOTEPerNToken, finalNTokenBalance ); // If a secondary incentive rewarder is set, then call it IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress); if (address(rewarder) != address(0)) { rewarder.claimRewards( account, balanceState.currencyId, // When this method is called from finalize, the storedNTokenBalance has not // been updated to finalNTokenBalance yet so this is the balance before the change. balanceState.storedNTokenBalance.toUint(), finalNTokenBalance, // When the rewarder is called, totalSupply has been updated already so may need to // adjust its calculation using the net supply change figure here. Supply change // may be zero when nTokens are transferred. balanceState.netNTokenSupplyChange, incentivesToClaim ); } if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../global/Deployments.sol"; import "./protocols/AaveHandler.sol"; import "./protocols/CompoundHandler.sol"; import "./protocols/GenericToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @notice Handles all external token transfers and events library TokenHandler { using SafeInt256 for int256; using SafeMath for uint256; function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][false]; tokenStorage.maxCollateralBalance = maxCollateralBalance; } function getAssetToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, false); } function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, true); } /// @notice Gets token data for a particular currency id, if underlying is set to true then returns /// the underlying token. (These may not always exist) function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][underlying]; return Token({ tokenAddress: tokenStorage.tokenAddress, hasTransferFee: tokenStorage.hasTransferFee, // No overflow, restricted on storage decimals: int256(10**tokenStorage.decimalPlaces), tokenType: tokenStorage.tokenType, maxCollateralBalance: tokenStorage.maxCollateralBalance }); } /// @notice Sets a token for a currency id. function setToken( uint256 currencyId, bool underlying, TokenStorage memory tokenStorage ) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) { // Hardcoded parameters for ETH just to make sure we don't get it wrong. TokenStorage storage ts = store[currencyId][true]; ts.tokenAddress = address(0); ts.hasTransferFee = false; ts.tokenType = TokenType.Ether; ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES; ts.maxCollateralBalance = 0; return; } // Check token address require(tokenStorage.tokenAddress != address(0), "TH: address is zero"); // Once a token is set we cannot override it. In the case that we do need to do change a token address // then we should explicitly upgrade this method to allow for a token to be changed. Token memory token = _getToken(currencyId, underlying); require( token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0), "TH: token cannot be reset" ); require(0 < tokenStorage.decimalPlaces && tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals"); // Validate token type require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once if (underlying) { // Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily // during mint and redeem actions. require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent } else { require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent } if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) { // Set the approval for the underlying so that we can mint cTokens or aTokens Token memory underlyingToken = getUnderlyingToken(currencyId); // cTokens call transfer from the tokenAddress, but aTokens use the LendingPool // to initiate all transfers address approvalAddress = tokenStorage.tokenType == TokenType.cToken ? tokenStorage.tokenAddress : address(LibStorage.getLendingPool().lendingPool); // ERC20 tokens should return true on success for an approval, but Tether // does not return a value here so we use the NonStandard interface here to // check that the approval was successful. IEIP20NonStandard(underlyingToken.tokenAddress).approve( approvalAddress, type(uint256).max ); GenericToken.checkReturnCode(); } store[currencyId][underlying] = tokenStorage; } /** * @notice If a token is mintable then will mint it. At this point we expect to have the underlying * balance in the contract already. * @param assetToken the asset token to mint * @param underlyingAmountExternal the amount of underlying to transfer to the mintable token * @return the amount of asset tokens minted, will always be a positive integer */ function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) { // aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this // value in internal accounting since it will not allow individual users to accrue aToken interest. Use the // scaledBalanceOf function call instead for internal accounting. bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); if (assetToken.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); AaveHandler.mint(underlyingToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { CompoundHandler.mint(assetToken, underlyingAmountExternal); } else if (assetToken.tokenType == TokenType.cETH) { CompoundHandler.mintCETH(assetToken); } else { revert(); // dev: non mintable token } uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector); // This is the starting and ending balance in external precision return SafeInt256.toInt(endingBalance.sub(startingBalance)); } /** * @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance * to the account * @param assetToken asset token to redeem * @param currencyId the currency id of the token * @param account account to transfer the underlying to * @param assetAmountExternal the amount to transfer in asset token denomination and external precision * @return the actual amount of underlying tokens transferred. this is used as a return value back to the * user, is not used for internal accounting purposes */ function redeem( Token memory assetToken, uint256 currencyId, address account, uint256 assetAmountExternal ) internal returns (int256) { uint256 transferAmount; if (assetToken.tokenType == TokenType.cETH) { transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal); } else { Token memory underlyingToken = getUnderlyingToken(currencyId); if (assetToken.tokenType == TokenType.aToken) { transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal); } else if (assetToken.tokenType == TokenType.cToken) { transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal); } else { revert(); // dev: non redeemable token } } // Use the negative value here to signify that assets have left the protocol return SafeInt256.toInt(transferAmount).neg(); } /// @notice Handles transfers into and out of the system denominated in the external token decimal /// precision. function transfer( Token memory token, address account, uint256 currencyId, int256 netTransferExternal ) internal returns (int256 actualTransferExternal) { // This will be true in all cases except for deposits where the token has transfer fees. For // aTokens this value is set before convert from scaled balances to principal plus interest actualTransferExternal = netTransferExternal; if (token.tokenType == TokenType.aToken) { Token memory underlyingToken = getUnderlyingToken(currencyId); // aTokens need to be converted when we handle the transfer since the external balance format // is not the same as the internal balance format that we use netTransferExternal = AaveHandler.convertFromScaledBalanceExternal( underlyingToken.tokenAddress, netTransferExternal ); } if (netTransferExternal > 0) { // Deposits must account for transfer fees. int256 netDeposit = _deposit(token, account, uint256(netTransferExternal)); // If an aToken has a transfer fee this will still return a balance figure // in scaledBalanceOf terms due to the selector if (token.hasTransferFee) actualTransferExternal = netDeposit; } else if (token.tokenType == TokenType.Ether) { // netTransferExternal can only be negative or zero at this point GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg())); } else { GenericToken.safeTransferOut( token.tokenAddress, account, // netTransferExternal is zero or negative here uint256(netTransferExternal.neg()) ); } } /// @notice Handles token deposits into Notional. If there is a transfer fee then we must /// calculate the net balance after transfer. Amounts are denominated in the destination token's /// precision. function _deposit( Token memory token, address account, uint256 amount ) private returns (int256) { uint256 startingBalance; uint256 endingBalance; bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ? AaveHandler.scaledBalanceOfSelector : GenericToken.defaultBalanceOfSelector; if (token.hasTransferFee) { startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } GenericToken.safeTransferIn(token.tokenAddress, account, amount); if (token.hasTransferFee || token.maxCollateralBalance > 0) { // If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably // the correct behavior because if collateral accrues interest over time we should not somehow go over the // maxCollateralBalance due to the passage of time. endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector); } if (token.maxCollateralBalance > 0) { int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance)); // Max collateral balance is stored as uint72, no overflow require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance } // Math is done in uint inside these statements and will revert on negative if (token.hasTransferFee) { return SafeInt256.toInt(endingBalance.sub(startingBalance)); } else { return SafeInt256.toInt(amount); } } function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) { // If token decimals > INTERNAL_TOKEN_PRECISION: // on deposit: resulting dust will accumulate to protocol // on withdraw: protocol may lose dust amount. However, withdraws are only calculated based // on a conversion from internal token precision to external token precision so therefore dust // amounts cannot be specified for withdraws. // If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the // end of amount and will not result in dust. if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals); } function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) { if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; // If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount // by adding a number of zeros to the end and will not result in dust. // If token decimals < INTERNAL_TOKEN_PRECISION: // on deposit: Deposits are specified in external token precision and there is no loss of precision when // tokens are converted from external to internal precision // on withdraw: this calculation will round down such that the protocol retains the residual cash balance return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION); } function transferIncentive(address account, uint256 tokensToTransfer) internal { GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "./Bitmap.sol"; /** * Packs an uint value into a "floating point" storage slot. Used for storing * lastClaimIntegralSupply values in balance storage. For these values, we don't need * to maintain exact precision but we don't want to be limited by storage size overflows. * * A floating point value is defined by the 48 most significant bits and an 8 bit number * of bit shifts required to restore its precision. The unpacked value will always be less * than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1. */ library FloatingPoint56 { function packTo56Bits(uint256 value) internal pure returns (uint56) { uint256 bitShift; // If the value is over the uint48 max value then we will shift it down // given the index of the most significant bit. We store this bit shift // in the least significant byte of the 56 bit slot available. if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47); uint256 shiftedValue = value >> bitShift; return uint56((shiftedValue << 8) | bitShift); } function unpackFrom56Bits(uint256 value) internal pure returns (uint256) { // The least significant 8 bits will be the amount to bit shift uint256 bitShift = uint256(uint8(value)); return ((value >> 8) << bitShift); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenSupply.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenHandler { using SafeInt256 for int256; /// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning /// two constants to each other. uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @notice Returns an account context object that is specific to nTokens. function getNTokenContext(address tokenAddress) internal view returns ( uint16 currencyId, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; currencyId = context.currencyId; incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate; lastInitializedTime = context.lastInitializedTime; assetArrayLength = context.assetArrayLength; parameters = context.nTokenParameters; } /// @notice Returns the nToken token address for a given currency function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) { mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage(); return store[currencyId]; } /// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be /// reset once this is set. function setNTokenAddress(uint16 currencyId, address tokenAddress) internal { mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage(); require(addressStore[currencyId] == address(0), "PT: token address exists"); mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage(); nTokenContext storage context = contextStore[tokenAddress]; require(context.currencyId == 0, "PT: currency exists"); // This will initialize all other context slots to zero context.currencyId = currencyId; addressStore[currencyId] = tokenAddress; } /// @notice Set nToken token collateral parameters function setNTokenCollateralParameters( address tokenAddress, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) internal { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut"); // The pv haircut percentage must be less than the liquidation percentage or else liquidators will not // get profit for liquidating nToken. require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut"); // Ensure that the cash withholding buffer is greater than the residual purchase incentive or // the nToken may not have enough cash to pay accounts to buy its negative ifCash require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts"); bytes5 parameters = (bytes5(uint40(residualPurchaseIncentive10BPS)) | (bytes5(uint40(pvHaircutPercentage)) << 8) | (bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) | (bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) | (bytes5(uint40(liquidationHaircutPercentage)) << 32)); // Set the parameters context.nTokenParameters = parameters; } /// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different /// contract, aside from the native NOTE token incentives. function setSecondaryRewarder( uint16 currencyId, IRewarder rewarder ) internal { address tokenAddress = nTokenAddress(currencyId); // nToken must exist for a secondary rewarder require(tokenAddress != address(0)); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; // Setting the rewarder to address(0) will disable it. We use a context setting here so that // we can save a storage read before getting the rewarder context.hasSecondaryRewarder = (address(rewarder) != address(0)); LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder; } /// @notice Returns the secondary rewarder if it is set function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; if (context.hasSecondaryRewarder) { return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress]; } else { return IRewarder(address(0)); } } function setArrayLengthAndInitializedTime( address tokenAddress, uint8 arrayLength, uint256 lastInitializedTime ) internal { require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.lastInitializedTime = uint32(lastInitializedTime); context.assetArrayLength = arrayLength; } /// @notice Returns the array of deposit shares and leverage thresholds for nTokens function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory depositShares, int256[] memory leverageThresholds) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; (depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false); } /// @notice Sets the deposit parameters /// @dev We pack the values in alternating between the two parameters into either one or two // storage slots depending on the number of markets. This is to save storage reads when we use the parameters. function setDepositParameters( uint256 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) internal { require( depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: deposit share length" ); require(depositShares.length == leverageThresholds.length, "PT: leverage share length"); uint256 shareSum; for (uint256 i; i < depositShares.length; i++) { // This cannot overflow in uint 256 with 9 max slots shareSum = shareSum + depositShares[i]; require( leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION, "PT: leverage threshold" ); } // Total deposit share must add up to 100% require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum"); mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; _setParameters(depositParameters, depositShares, leverageThresholds); } /// @notice Sets the initialization parameters for the markets, these are read only when markets /// are initialized function setInitializationParameters( uint256 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) internal { require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length"); require(proportions.length == annualizedAnchorRates.length, "PT: proportions length"); for (uint256 i; i < proportions.length; i++) { // Proportions must be between zero and the rate precision require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero"); require( proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION, "PT: invalid proportion" ); } mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; _setParameters(initParameters, annualizedAnchorRates, proportions); } /// @notice Returns the array of initialization parameters for a given currency. function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory annualizedAnchorRates, int256[] memory proportions) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; (annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true); } function _getParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint256 maxMarketIndex, bool noUnset ) private view returns (int256[] memory, int256[] memory) { uint256 index = 0; int256[] memory array1 = new int256[](maxMarketIndex); int256[] memory array2 = new int256[](maxMarketIndex); for (uint256 i; i < maxMarketIndex; i++) { array1[i] = slot[index]; index++; array2[i] = slot[index]; index++; if (noUnset) { require(array1[i] > 0 && array2[i] > 0, "PT: init value zero"); } } return (array1, array2); } function _setParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint32[] calldata array1, uint32[] calldata array2 ) private { uint256 index = 0; for (uint256 i = 0; i < array1.length; i++) { slot[index] = array1[i]; index++; slot[index] = array2[i]; index++; } } function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId) internal view { nToken.tokenAddress = nTokenAddress(currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) = getNTokenContext(nToken.tokenAddress); // prettier-ignore ( uint256 totalSupply, /* accumulatedNOTEPerNToken */, /* lastAccumulatedTime */ ) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress); nToken.lastInitializedTime = lastInitializedTime; nToken.totalSupply = int256(totalSupply); nToken.parameters = parameters; nToken.portfolioState = PortfolioHandler.buildPortfolioState( nToken.tokenAddress, assetArrayLength, 0 ); // prettier-ignore ( nToken.cashBalance, /* nTokenBalance */, /* lastClaimTime */, /* accountIncentiveDebt */ ) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId); } /// @notice Uses buildCashGroupStateful function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId) internal { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId); } /// @notice Uses buildCashGroupView function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId) internal view { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupView(currencyId); } /// @notice Returns the next settle time for the nToken which is 1 quarter away function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) { if (nToken.lastInitializedTime == 0) return 0; return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../../global/LibStorage.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library nTokenSupply { using SafeInt256 for int256; using SafeMath for uint256; /// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating /// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead. function getStoredNTokenSupplyFactors(address tokenAddress) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; totalSupply = nTokenStorage.totalSupply; // NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken // must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken; lastAccumulatedTime = nTokenStorage.lastAccumulatedTime; } /// @notice Returns the updated accumulated NOTE per nToken for calculating incentives function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime) internal view returns ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, uint256 lastAccumulatedTime ) { ( totalSupply, accumulatedNOTEPerNToken, lastAccumulatedTime ) = getStoredNTokenSupplyFactors(tokenAddress); // nToken totalSupply is never allowed to drop to zero but we check this here to avoid // divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not // zero to avoid a massive accumulation amount on initialization. if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) { // prettier-ignore ( /* currencyId */, uint256 emissionRatePerYear, /* initializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(tokenAddress); uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE( // Emission rate is denominated in whole tokens, scale to 1e8 decimals here emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)), // Time since last accumulation (overflow checked above) blockTime - lastAccumulatedTime, totalSupply ); accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken); require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow } } /// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision function _calculateAdditionalNOTE( uint256 emissionRatePerYear, uint256 timeSinceLastAccumulation, uint256 totalSupply ) private pure returns (uint256) { // If we use 18 decimal places as the accumulation precision then we will overflow uint128 when // a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max // NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe // using 18 decimal places and uint128 storage slot // timeSinceLastAccumulation (SECONDS) // accumulatedNOTEPerSharePrecision (1e18) // emissionRatePerYear (INTERNAL_TOKEN_PRECISION) // DIVIDE BY // YEAR (SECONDS) // totalSupply (INTERNAL_TOKEN_PRECISION) return timeSinceLastAccumulation .mul(Constants.INCENTIVE_ACCUMULATION_PRECISION) .mul(emissionRatePerYear) .div(Constants.YEAR) // totalSupply > 0 is checked in the calling function .div(totalSupply); } /// @notice Updates the nToken token supply amount when minting or redeeming. /// @param tokenAddress address of the nToken /// @param netChange positive or negative change to the total nToken supply /// @param blockTime current block time /// @return accumulatedNOTEPerNToken updated to the given block time function changeNTokenSupply( address tokenAddress, int256 netChange, uint256 blockTime ) internal returns (uint256) { ( uint256 totalSupply, uint256 accumulatedNOTEPerNToken, /* uint256 lastAccumulatedTime */ ) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime); // Update storage variables mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; int256 newTotalSupply = int256(totalSupply).add(netChange); // We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to // exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check. require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow nTokenStorage.totalSupply = uint96(newTotalSupply); // NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what // the user would see if querying the view function nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken); require(blockTime < type(uint32).max); // dev: block time overflow nTokenStorage.lastAccumulatedTime = uint32(blockTime); return accumulatedNOTEPerNToken; } /// @notice Called by governance to set the new emission rate function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal { // Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the // emission rate changeNTokenSupply(tokenAddress, 0, blockTime); mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.incentiveAnnualEmissionRate = newEmissionsRate; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "../internal/nToken/nTokenHandler.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @notice Deployed library for migration of incentives from the old (inaccurate) calculation * to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate * calculation is inside `Incentives.sol` and this library holds the legacy calculation. System * migration code can be found in `MigrateIncentivesFix.sol` */ library MigrateIncentives { using SafeMath for uint256; /// @notice Calculates the claimable incentives for a particular nToken and account in the /// previous regime. This should only ever be called ONCE for an account / currency combination /// to get the incentives accrued up until the migration date. function migrateAccountFromPreviousCalculation( address tokenAddress, uint256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) external view returns (uint256) { ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) = _getMigratedIncentiveValues(tokenAddress); // This if statement should never be true but we return 0 just in case if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0; // No overflow here, checked above. All incentives are claimed up until finalMigrationTime // using the finalTotalIntegralSupply. Both these values are set on migration and will not // change. uint256 timeSinceMigration = finalMigrationTime - lastClaimTime; // (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR uint256 incentiveRate = timeSinceMigration .mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) // Migration emission rate is stored as is, denominated in whole tokens .mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) .div(Constants.YEAR); // Returns the average supply using the integral of the total supply. uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration); if (avgTotalSupply == 0) return 0; uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply); // incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8 incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION)); return incentivesToClaim; } function _getMigratedIncentiveValues( address tokenAddress ) private view returns ( uint256 finalEmissionRatePerYear, uint256 finalTotalIntegralSupply, uint256 finalMigrationTime ) { mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress]; // The total supply value is overridden as emissionRatePerYear during the initialization finalEmissionRatePerYear = d_nTokenStorage.totalSupply; finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply; finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce /// gas costs for immutable addresses. They must be updated per environment that Notional /// is deployed to. library Deployments { address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../../global/Types.sol"; import "../../../global/LibStorage.sol"; import "../../../math/SafeInt256.sol"; import "../TokenHandler.sol"; import "../../../../interfaces/aave/IAToken.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AaveHandler { using SafeMath for uint256; using SafeInt256 for int256; int256 internal constant RAY = 1e27; int256 internal constant halfRAY = RAY / 2; bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector; /** * @notice Mints an amount of aTokens corresponding to the the underlying. * @param underlyingToken address of the underlying token to pass to Aave * @param underlyingAmountExternal amount of underlying to deposit, in external precision */ function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal { // In AaveV3 this method is renamed to supply() but deposit() is still available for // backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755 // We use deposit here so that mainnet-fork tests against Aave v2 will pass. LibStorage.getLendingPool().lendingPool.deposit( underlyingToken.tokenAddress, underlyingAmountExternal, address(this), 0 ); } /** * @notice Redeems and sends an amount of aTokens to the specified account * @param underlyingToken address of the underlying token to pass to Aave * @param account account to receive the underlying * @param assetAmountExternal amount of aTokens in scaledBalanceOf terms */ function redeem( Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { underlyingAmountExternal = convertFromScaledBalanceExternal( underlyingToken.tokenAddress, SafeInt256.toInt(assetAmountExternal) ).toUint(); LibStorage.getLendingPool().lendingPool.withdraw( underlyingToken.tokenAddress, underlyingAmountExternal, account ); } /** * @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest) * and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional * claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will * receive future Aave interest. * @dev There is no loss of precision within this function since it does the exact same calculation as Aave. * @param currencyId is the currency id * @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must * be positive in this function, this method is only called when depositing aTokens directly * @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will * be in external precision. */ function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId); // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress); // Mimic the WadRay math performed by Aave (but do it in int256 instead) int256 halfIndex = index / 2; // Overflow will occur when: (a * RAY + halfIndex) > int256.max require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY); // if index is zero then this will revert return (assetAmountExternal * RAY + halfIndex) / index; } /** * @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision) * and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest * that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions. * @dev There is no loss of precision because this does exactly what Aave's calculation would do * @param underlyingToken token address of the underlying asset * @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from * Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or * withdrawn (negative). * @return netBalanceExternal the Aave balanceOf equivalent as a signed integer */ function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) { if (netScaledBalanceExternal == 0) return 0; // We know that this value must be positive int256 index = _getReserveNormalizedIncome(underlyingToken); // Use the absolute value here so that the halfRay rounding is applied correctly for negative values int256 abs = netScaledBalanceExternal.abs(); // Mimic the WadRay math performed by Aave (but do it in int256 instead) // Overflow will occur when: (abs * index + halfRay) > int256.max // Here the first term is computed at compile time so it just does a division. If index is zero then // solidity will revert. require(abs <= (type(int256).max - halfRAY) / index); int256 absScaled = (abs * index + halfRAY) / RAY; return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg(); } /// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is /// always positive even though we are converting to a signed int function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) { return SafeInt256.toInt( LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./GenericToken.sol"; import "../../../../interfaces/compound/CErc20Interface.sol"; import "../../../../interfaces/compound/CEtherInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../global/Types.sol"; library CompoundHandler { using SafeMath for uint256; // Return code for cTokens that represents no error uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0; function mintCETH(Token memory token) internal { // Reverts on error CEtherInterface(token.tokenAddress).mint{value: msg.value}(); } function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) { uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint"); } function redeemCETH( Token memory assetToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = address(this).balance; uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = address(this).balance; underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.transferNativeTokenOut(account, underlyingAmountExternal); } function redeem( Token memory assetToken, Token memory underlyingToken, address account, uint256 assetAmountExternal ) internal returns (uint256 underlyingAmountExternal) { // Although the contract should never end with any ETH or underlying token balances, we still do this // starting and ending check in the case that tokens are accidentally sent to the contract address. They // will not be sent to some lucky address in a windfall. uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector); underlyingAmountExternal = endingBalance.sub(startingBalance); // Withdraws the underlying amount out to the destination account GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../../../../interfaces/IEIP20NonStandard.sol"; library GenericToken { bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector; /** * @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows * for overriding the balanceOf selector to use scaledBalanceOf for aTokens */ function checkBalanceViaSelector( address token, address account, bytes4 balanceOfSelector ) internal returns (uint256 balance) { (bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account)); require(success); (balance) = abi.decode(returnData, (uint256)); } function transferNativeTokenOut( address account, uint256 amount ) internal { // This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying // ETH they will have to withdraw the cETH token and then redeem it manually. payable(account).transfer(amount); } function safeTransferOut( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transfer(account, amount); checkReturnCode(); } function safeTransferIn( address token, address account, uint256 amount ) internal { IEIP20NonStandard(token).transferFrom(account, address(this), amount); checkReturnCode(); } function checkReturnCode() internal pure { bool success; uint256[1] memory result; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := 1 // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(result, 0, 32) success := mload(result) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "ERC20"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); function UNDERLYING_ASSET_ADDRESS() external view returns (address); function symbol() external view returns (string memory); } interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } interface IATokenFull is IScaledBalanceToken, IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; import "./CTokenInterface.sol"; interface CErc20Interface { /*** User Interface ***/ function mint(uint mintAmount) 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); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CEtherInterface { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @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 IEIP20NonStandard { /** * @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 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` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @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 */ function approve(address spender, uint256 amount) external; /** * @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 remaining 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); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CTokenInterface { /*** User Interface ***/ function underlying() external view returns (address); 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 balanceOfUnderlying(address owner) external 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) external view returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function getCash() external view returns (uint); function accrueInterest() external returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/Types.sol"; import "../global/Constants.sol"; /// @notice Helper methods for bitmaps, they are big-endian and 1-indexed. library Bitmap { /// @notice Set a bit on or off in a bitmap, index is 1-indexed function setBit( bytes32 bitmap, uint256 index, bool setOn ) internal pure returns (bytes32) { require(index >= 1 && index <= 256); // dev: set bit index bounds if (setOn) { return bitmap | (Constants.MSB >> (index - 1)); } else { return bitmap & ~(Constants.MSB >> (index - 1)); } } /// @notice Check if a bit is set function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) { require(index >= 1 && index <= 256); // dev: set bit index bounds return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB; } /// @notice Count the total bits set function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) { uint256 x = uint256(bitmap); x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555); x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333); x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4); x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F); x = x + (x >> 16); x = x + (x >> 32); x = x + (x >> 64); return (x & 0xFF) + (x >> 128 & 0xFF); } // Does a binary search over x to get the position of the most significant bit function getMSB(uint256 x) internal pure returns (uint256 msb) { // If x == 0 then there is no MSB and this method will return zero. That would // be the same as the return value when x == 1 (MSB is zero indexed), so instead // we have this require here to ensure that the values don't get mixed up. require(x != 0); // dev: get msb zero value if (x >= 0x100000000000000000000000000000000) { x >>= 128; msb += 128; } if (x >= 0x10000000000000000) { x >>= 64; msb += 64; } if (x >= 0x100000000) { x >>= 32; msb += 32; } if (x >= 0x10000) { x >>= 16; msb += 16; } if (x >= 0x100) { x >>= 8; msb += 8; } if (x >= 0x10) { x >>= 4; msb += 4; } if (x >= 0x4) { x >>= 2; msb += 2; } if (x >= 0x2) msb += 1; // No need to shift xc anymore } /// @dev getMSB returns a zero indexed bit number where zero is the first bit counting /// from the right (little endian). Asset Bitmaps are counted from the left (big endian) /// and one indexed. function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) { // Short circuit the search if bitmap is all zeros if (bitmap == 0x00) return 0; return 255 - getMSB(uint256(bitmap)) + 1; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../balances/TokenHandler.sol"; import "../../math/SafeInt256.sol"; import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol"; library ExchangeRate { using SafeInt256 for int256; /// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are /// always applied in this method. /// @param er exchange rate object from base to ETH /// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) { int256 multiplier = balance > 0 ? er.haircut : er.buffer; // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals) // Therefore the result is in ethDecimals int256 result = balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div( er.rateDecimals ); return result; } /// @notice Converts the balance denominated in ETH to the equivalent value in a base currency. /// Buffers and haircuts ARE NOT applied in this method. /// @param er exchange rate object from base to ETH /// @param balance amount (denominated in ETH) to convert function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) { // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals / rateDecimals int256 result = balance.mul(er.rateDecimals).div(er.rate); return result; } /// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in /// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals /// @param baseER base exchange rate struct /// @param quoteER quote exchange rate struct function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER) internal pure returns (int256) { return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate); } /// @notice Returns an ETHRate object used to calculate free collateral function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) { mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage(); ETHRateStorage storage ethStorage = store[currencyId]; int256 rateDecimals; int256 rate; if (currencyId == Constants.ETH_CURRENCY_ID) { // ETH rates will just be 1e18, but will still have buffers, haircuts, // and liquidation discounts rateDecimals = Constants.ETH_DECIMALS; rate = Constants.ETH_DECIMALS; } else { // prettier-ignore ( /* roundId */, rate, /* uint256 startedAt */, /* updatedAt */, /* answeredInRound */ ) = ethStorage.rateOracle.latestRoundData(); require(rate > 0, "Invalid rate"); // No overflow, restricted on storage rateDecimals = int256(10**ethStorage.rateDecimalPlaces); if (ethStorage.mustInvert) { rate = rateDecimals.mul(rateDecimals).div(rate); } } return ETHRate({ rateDecimals: rateDecimals, rate: rate, buffer: ethStorage.buffer, haircut: ethStorage.haircut, liquidationDiscount: ethStorage.liquidationDiscount }); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./nTokenHandler.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; library nTokenCalculations { using Bitmap for bytes32; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using CashGroup for CashGroupParameters; /// @notice Returns the nToken present value denominated in asset terms. function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256) { int256 totalAssetPV; int256 totalUnderlyingPV; { uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken); // If the first asset maturity has passed (the 3 month), this means that all the LTs must // be settled except the 6 month (which is now the 3 month). We don't settle LTs except in // initialize markets so we calculate the cash value of the portfolio here. if (nextSettleTime <= blockTime) { // NOTE: this condition should only be present for a very short amount of time, which is the window between // when the markets are no longer tradable at quarter end and when the new markets have been initialized. // We time travel back to one second before maturity to value the liquidity tokens. Although this value is // not strictly correct the different should be quite slight. We do this to ensure that free collateral checks // for withdraws and liquidations can still be processed. If this condition persists for a long period of time then // the entire protocol will have serious problems as markets will not be tradable. blockTime = nextSettleTime - 1; } } // This is the total value in liquid assets (int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime); // Then get the total value in any idiosyncratic fCash residuals (if they exist) bytes32 ifCashBits = getNTokenifCashBits( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup.maxMarketIndex ); int256 ifCashResidualUnderlyingPV = 0; if (ifCashBits != 0) { // Non idiosyncratic residuals have already been accounted for (ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, false, // nToken present value calculation does not use risk adjusted values ifCashBits ); } // Return the total present value denominated in asset terms return totalAssetValueInMarkets .add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV)) .add(nToken.cashBalance); } /** * @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts * in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken * portfolio. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to * the account's share of the total supply * @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually * withdrawn from markets */ function _getProportionalLiquidityTokens( nTokenPortfolio memory nToken, int256 nTokensToRedeem ) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; tokensToWithdraw = new int256[](numMarkets); netfCash = new int256[](numMarkets); for (uint256 i = 0; i < numMarkets; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply); } } /** * @notice Returns the number of liquidity tokens to withdraw from each market if the nToken * has idiosyncratic residuals during nToken redeem. In this case the redeemer will take * their cash from the rest of the fCash markets, redeeming around the nToken. * @param nToken portfolio object for nToken * @param nTokensToRedeem amount of nTokens to redeem * @param blockTime block time * @param ifCashBits the bits in the bitmap that represent ifCash assets * @return tokensToWithdraw array of tokens to withdraw from each corresponding market * @return netfCash array of netfCash amounts to go back to the account */ function getLiquidityTokenWithdraw( nTokenPortfolio memory nToken, int256 nTokensToRedeem, uint256 blockTime, bytes32 ifCashBits ) internal view returns (int256[] memory, int256[] memory) { // If there are no ifCash bits set then this will just return the proportion of all liquidity tokens if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem); ( int256 totalAssetValueInMarkets, int256[] memory netfCash ) = getNTokenMarketValue(nToken, blockTime); int256[] memory tokensToWithdraw = new int256[](netfCash.length); // NOTE: this total portfolio asset value does not include any cash balance the nToken may hold. // The redeemer will always get a proportional share of this cash balance and therefore we don't // need to account for it here when we calculate the share of liquidity tokens to withdraw. We are // only concerned with the nToken's portfolio assets in this method. int256 totalPortfolioAssetValue; { // Returns the risk adjusted net present value for the idiosyncratic residuals (int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, true, // use risk adjusted here to assess a penalty for withdrawing around the residual ifCashBits ); // NOTE: we do not include cash balance here because the account will always take their share // of the cash balance regardless of the residuals totalPortfolioAssetValue = totalAssetValueInMarkets.add( nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV) ); } // Loops through each liquidity token and calculates how much the redeemer can withdraw to get // the requisite amount of present value after adjusting for the ifCash residual value that is // not accessible via redemption. for (uint256 i = 0; i < tokensToWithdraw.length; i++) { int256 totalTokens = nToken.portfolioState.storedAssets[i].notional; // Redeemer's baseline share of the liquidity tokens based on total supply: // redeemerShare = totalTokens * nTokensToRedeem / totalSupply // Scalar factor to account for residual value (need to inflate the tokens to withdraw // proportional to the value locked up in ifCash residuals): // scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets // Final math equals: // tokensToWithdraw = redeemerShare * scalarFactor // tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue) // / (totalAssetValueInMarkets * totalSupply) tokensToWithdraw[i] = totalTokens .mul(nTokensToRedeem) .mul(totalPortfolioAssetValue); tokensToWithdraw[i] = tokensToWithdraw[i] .div(totalAssetValueInMarkets) .div(nToken.totalSupply); // This is the share of net fcash that will be credited back to the account netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens); } return (tokensToWithdraw, netfCash); } /// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by /// the liquidity tokens held in each market and their corresponding fCash positions. The formula /// can be described as: /// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash)) /// where netfCash = fCashClaim + fCash /// and fCash refers the the fCash position at the corresponding maturity function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256 totalAssetValue, int256[] memory netfCash) { uint256 numMarkets = nToken.portfolioState.storedAssets.length; netfCash = new int256[](numMarkets); MarketParameters memory market; for (uint256 i = 0; i < numMarkets; i++) { // Load the corresponding market into memory nToken.cashGroup.loadMarket(market, i + 1, true, blockTime); PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i]; uint256 maturity = liquidityToken.maturity; // Get the fCash claims and fCash assets. We do not use haircut versions here because // nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied // at the end of the calculation to the entire PV instead). (int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market); // fCash is denominated in underlying netfCash[i] = fCashClaim.add( BitmapAssetsHandler.getifCashNotional( nToken.tokenAddress, nToken.cashGroup.currencyId, maturity ) ); // This calculates for a single liquidity token: // assetCashClaim + convertToAssetCash(pv(netfCash)) int256 netAssetValueInMarket = assetCashClaim.add( nToken.cashGroup.assetRate.convertFromUnderlying( AssetHandler.getPresentfCashValue( netfCash[i], maturity, blockTime, // No need to call cash group for oracle rate, it is up to date here // and we are assured to be referring to this market. market.oracleRate ) ) ); // Calculate the running total totalAssetValue = totalAssetValue.add(netAssetValueInMarket); } } /// @notice Returns just the bits in a bitmap that are idiosyncratic function getNTokenifCashBits( address tokenAddress, uint256 currencyId, uint256 lastInitializedTime, uint256 blockTime, uint256 maxMarketIndex ) internal view returns (bytes32) { // If max market index is less than or equal to 2, there are never ifCash assets by construction if (maxMarketIndex <= 2) return bytes32(0); bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId); // Handles the case when there are no assets at the first initialization if (assetsBitmap == 0) return assetsBitmap; uint256 tRef = DateTime.getReferenceTime(blockTime); if (tRef == lastInitializedTime) { // This is a more efficient way to turn off ifCash assets in the common case when the market is // initialized immediately return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK); } else { // In this branch, initialize markets has occurred past the time above. It would occur in these // two scenarios (both should be exceedingly rare): // 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef) // 2. somehow initialize markets has been delayed for more than 24 hours for (uint i = 1; i <= maxMarketIndex; i++) { // In this loop we get the maturity of each active market and turn off the corresponding bit // one by one. It is less efficient than the option above. uint256 maturity = tRef + DateTime.getTradedMarket(i); (uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity); assetsBitmap = assetsBitmap.setBit(bitNum, false); } return assetsBitmap; } } }
Gets an oracle rate given any valid maturity. DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic In this case the short market is the annualized asset supply rate Minimum value for marketIndex here is 2
function calculateOracleRate( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime ) internal view returns (uint256) { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime); uint256 timeWindow = getRateOracleTimeWindow(cashGroup); if (!idiosyncratic) { return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime); uint256 referenceTime = DateTime.getReferenceTime(blockTime); uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex)); uint256 longRate = Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime); uint256 shortMaturity; uint256 shortRate; if (marketIndex == 1) { shortMaturity = blockTime; shortRate = cashGroup.assetRate.getSupplyRate(); shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1)); shortRate = Market.getOracleRate( cashGroup.currencyId, shortMaturity, timeWindow, blockTime ); } return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity); } }
12,285
./full_match/1/0xcDA39B74054EFFB230156f21b334E50295Ca8df4/sources/contracts/strategies/AaveFlashloanStrategy/AaveFlashloanStrategy.sol
Get Aave ratios for a token in order to compute later our collateral ratio token Address of the token for which to check the ratios (usually `want` token) `getReserveConfigurationData` returns values in base 4. So here `ltv` and `liquidationThreshold` are returned in base 18 convert bps to wad
function _getProtocolCollatRatios(address token) internal view returns (uint256 ltv, uint256 liquidationThreshold) { (, ltv, liquidationThreshold, , , , , , , ) = _protocolDataProvider.getReserveConfigurationData(token); ltv = ltv * _BPS_WAD_RATIO; liquidationThreshold = liquidationThreshold * _BPS_WAD_RATIO; }
9,603,156
./full_match/1/0xb05F299ed72A385B09d91312323dBF068158b5D5/sources/contracts/PassengerNFTContract_IMP1.sol
Handle the receipt of an NFT The ERC721 smart contract calls this function on the recipient after a `safetransfer`. This function MAY throw to revert and reject the transfer. This function MUST use 50,000 gas or less. Return of other than the magic value MUST result in the transaction being reverted. Note: the contract address is always the message sender.
function onERC721Received( address, address, uint256, bytes memory ) public pure virtual returns (bytes4) { return this.onERC721Received.selector; }
9,637,151
./full_match/1/0x6569A9faC7218249887bc41B2DbCA982dCC8Cf46/sources/SpaceD/SaleMarket.sol
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); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); pragma solidity >=0.6.9; }
16,457,773
pragma solidity 0.5.15; contract IAugur { function createChildUniverse(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); function isKnownUniverse(IUniverse _universe) public view returns (bool); function trustedCashTransfer(address _from, address _to, uint256 _amount) public returns (bool); function isTrustedSender(address _address) public returns (bool); function onCategoricalMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); function onYesNoMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); function onScalarMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); function logInitialReportSubmitted(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); function disputeCrowdsourcerCreated(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); function logDisputeCrowdsourcerContribution(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); function logDisputeCrowdsourcerCompleted(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); function logInitialReporterRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); function logDisputeCrowdsourcerRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); function logMarketFinalized(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); function logMarketMigrated(IMarket _market, IUniverse _originalUniverse) public returns (bool); function logReportingParticipantDisavowed(IUniverse _universe, IMarket _market) public returns (bool); function logMarketParticipantsDisavowed(IUniverse _universe) public returns (bool); function logCompleteSetsPurchased(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); function logCompleteSetsSold(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); function logMarketOIChanged(IUniverse _universe, IMarket _market) public returns (bool); function logTradingProceedsClaimed(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); function logUniverseForked(IMarket _forkingMarket) public returns (bool); function logReputationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); function logReputationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logReputationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logShareTokensBalanceChanged(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); function logDisputeCrowdsourcerTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); function logDisputeCrowdsourcerTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logDisputeCrowdsourcerTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logDisputeWindowCreated(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); function logParticipationTokensRedeemed(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); function logTimestampSet(uint256 _newTimestamp) public returns (bool); function logInitialReporterTransferred(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); function logMarketTransferred(IUniverse _universe, address _from, address _to) public returns (bool); function logParticipationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); function logParticipationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logParticipationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logMarketRepBondTransferred(address _universe, address _from, address _to) public returns (bool); function logWarpSyncDataUpdated(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); function isKnownFeeSender(address _feeSender) public view returns (bool); function lookup(bytes32 _key) public view returns (address); function getTimestamp() public view returns (uint256); function getMaximumMarketEndDate() public returns (uint256); function isKnownMarket(IMarket _market) public view returns (bool); function derivePayoutDistributionHash(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); function logValidityBondChanged(uint256 _validityBond) public returns (bool); function logDesignatedReportStakeChanged(uint256 _designatedReportStake) public returns (bool); function logNoShowBondChanged(uint256 _noShowBond) public returns (bool); function logReportingFeeChanged(uint256 _reportingFee) public returns (bool); function getUniverseForkIndex(IUniverse _universe) public view returns (uint256); } interface IAugurWallet { function initialize(address _owner, address _referralAddress, bytes32 _fingerprint, address _augur, address _registry, address _registryV2, IERC20 _cash, IAffiliates _affiliates, IERC1155 _shareToken, address _createOrder, address _fillOrder, address _zeroXTrade) external; function transferCash(address _to, uint256 _amount) external; function executeTransaction(address _to, bytes calldata _data, uint256 _value) external returns (bool); } interface IAugurWalletRegistry { function ethExchange() external returns (IUniswapV2Pair); function WETH() external returns (IWETH); function token0IsCash() external returns (bool); } contract IAugurWalletFactory { function getCreate2WalletAddress(address _owner) external view returns (address); function createAugurWallet(address _owner, address _referralAddress, bytes32 _fingerprint) public returns (IAugurWallet); } contract Context { function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IRelayHub { // Relay management /** * @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller * of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay * cannot be its own owner. * * All Ether in this function call will be added to the relay's stake. * Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one. * * Emits a {Staked} event. */ function stake(address relayaddr, uint256 unstakeDelay) external payable; /** * @dev Emitted when a relay's stake or unstakeDelay are increased */ event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay); /** * @dev Registers the caller as a relay. * The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA). * * This function can be called multiple times, emitting new {RelayAdded} events. Note that the received * `transactionFee` is not enforced by {relayCall}. * * Emits a {RelayAdded} event. */ function registerRelay(uint256 transactionFee, string calldata url) external; /** * @dev Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out * {RelayRemoved} events) lets a client discover the list of available relays. */ event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url); /** * @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed. * * Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be * callable. * * Emits a {RelayRemoved} event. */ function removeRelayByOwner(address relay) external; /** * @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable. */ event RelayRemoved(address indexed relay, uint256 unstakeTime); /** Deletes the relay from the system, and gives back its stake to the owner. * * Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called. * * Emits an {Unstaked} event. */ function unstake(address relay) external; /** * @dev Emitted when a relay is unstaked for, including the returned stake. */ event Unstaked(address indexed relay, uint256 stake); // States a relay can be in enum RelayState { Unknown, // The relay is unknown to the system: it has never been staked for Staked, // The relay has been staked for, but it is not yet active Registered, // The relay has registered itself, and is active (can relay calls) Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake } /** * @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function * to return an empty entry. */ function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state); // Balance management /** * @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions. * * Unused balance can only be withdrawn by the contract itself, by calling {withdraw}. * * Emits a {Deposited} event. */ function depositFor(address target) external payable; /** * @dev Emitted when {depositFor} is called, including the amount and account that was funded. */ event Deposited(address indexed recipient, address indexed from, uint256 amount); /** * @dev Returns an account's deposits. These can be either a contracts's funds, or a relay owner's revenue. */ function balanceOf(address target) external view returns (uint256); /** * Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and * contracts can use it to reduce their funding. * * Emits a {Withdrawn} event. */ function withdraw(uint256 amount, address payable dest) external; /** * @dev Emitted when an account withdraws funds from `RelayHub`. */ event Withdrawn(address indexed account, address indexed dest, uint256 amount); // Relaying /** * @dev Checks if the `RelayHub` will accept a relayed operation. * Multiple things must be true for this to happen: * - all arguments must be signed for by the sender (`from`) * - the sender's nonce must be the current one * - the recipient must accept this transaction (via {acceptRelayedCall}) * * Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error * code if it returns one in {acceptRelayedCall}. */ function canRelay( address relay, address from, address to, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata signature, bytes calldata approvalData ) external view returns (uint256 status, bytes memory recipientContext); // Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values. enum PreconditionCheck { OK, // All checks passed, the call can be relayed WrongSignature, // The transaction to relay is not signed by requested sender WrongNonce, // The provided nonce has already been used by the sender AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code } /** * @dev Relays a transaction. * * For this to succeed, multiple conditions must be met: * - {canRelay} must `return PreconditionCheck.OK` * - the sender must be a registered relay * - the transaction's gas price must be larger or equal to the one that was requested by the sender * - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the * recipient) use all gas available to them * - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is * spent) * * If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded * function and {postRelayedCall} will be called in that order. * * Parameters: * - `from`: the client originating the request * - `to`: the target {IRelayRecipient} contract * - `encodedFunction`: the function call to relay, including data * - `transactionFee`: fee (%) the relay takes over actual gas cost * - `gasPrice`: gas price the client is willing to pay * - `gasLimit`: gas to forward when calling the encoded function * - `nonce`: client's nonce * - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses * - `approvalData`: dapp-specific data forwared to {acceptRelayedCall}. This value is *not* verified by the * `RelayHub`, but it still can be used for e.g. a signature. * * Emits a {TransactionRelayed} event. */ function relayCall( address from, address to, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata signature, bytes calldata approvalData ) external; /** * @dev Emitted when an attempt to relay a call failed. * * This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The * actual relayed call was not executed, and the recipient not charged. * * The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values * over 10 are custom recipient error codes returned from {acceptRelayedCall}. */ event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason); /** * @dev Emitted when a transaction is relayed. * Useful when monitoring a relay's operation and relayed calls to a contract * * Note that the actual encoded function might be reverted: this is indicated in the `status` parameter. * * `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner. */ event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge); // Reason error codes for the TransactionRelayed event enum RelayCallStatus { OK, // The transaction was successfully relayed and execution successful - never included in the event RelayedCallFailed, // The transaction was relayed, but the relayed call failed PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing } /** * @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will * spend up to `relayedCallStipend` gas. */ function requiredGas(uint256 relayedCallStipend) external view returns (uint256); /** * @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee. */ function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external view returns (uint256); // Relay penalization. // Any account can penalize relays, removing them from the system immediately, and rewarding the // reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it // still loses half of its stake. /** * @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and * different data (gas price, gas limit, etc. may be different). * * The (unsigned) transaction data and signature for both transactions must be provided. */ function penalizeRepeatedNonce(bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external; /** * @dev Penalize a relay that sent a transaction that didn't target `RelayHub`'s {registerRelay} or {relayCall}. */ function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external; /** * @dev Emitted when a relay is penalized. */ event Penalized(address indexed relay, address sender, uint256 amount); /** * @dev Returns an account's nonce in `RelayHub`. */ function getNonce(address from) external view returns (uint256); } interface IRelayRecipient { /** * @dev Returns the address of the {IRelayHub} instance this recipient interacts with. */ function getHubAddr() external view returns (address); /** * @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the * recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not). * * The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call * calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas, * and the transaction executed with a gas price of at least `gasPrice`. `relay`'s fee is `transactionFee`, and the * recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for * replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold a signature * over all or some of the previous values. * * Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code, * values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions. * * {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered * rejected. A regular revert will also trigger a rejection. */ function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 maxPossibleCharge ) external view returns (uint256, bytes memory); /** * @dev Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g. * pre-charge the sender of the transaction. * * `context` is the second value returned in the tuple by {acceptRelayedCall}. * * Returns a value to be passed to {postRelayedCall}. * * {preRelayedCall} is called with 100k gas: if it runs out during exection or otherwise reverts, the relayed call * will not be executed, but the recipient will still be charged for the transaction's cost. */ function preRelayedCall(bytes calldata context) external returns (bytes32); /** * @dev Called by {IRelayHub} on approved relay call requests, after the relayed call is executed. This allows to e.g. * charge the user for the relayed call costs, return any overcharges from {preRelayedCall}, or perform * contract-specific bookkeeping. * * `context` is the second value returned in the tuple by {acceptRelayedCall}. `success` is the execution status of * the relayed call. `actualCharge` is an estimate of how much the recipient will be charged for the transaction, * not including any gas used by {postRelayedCall} itself. `preRetVal` is {preRelayedCall}'s return value. * * * {postRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call * and the call to {preRelayedCall} will be reverted retroactively, but the recipient will still be charged for the * transaction's cost. */ function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external; } contract GSNRecipient is IRelayRecipient, Context { // Default RelayHub address, deployed on mainnet and all testnets at the same address address private _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494; uint256 constant private RELAYED_CALL_ACCEPTED = 0; uint256 constant private RELAYED_CALL_REJECTED = 11; // How much gas is forwarded to postRelayedCall uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000; /** * @dev Emitted when a contract changes its {IRelayHub} contract to a new one. */ event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub); /** * @dev Returns the address of the {IRelayHub} contract for this recipient. */ function getHubAddr() public view returns (address) { return _relayHub; } /** * @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not * use the default instance. * * IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old * {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}. */ function _upgradeRelayHub(address newRelayHub) internal { address currentRelayHub = _relayHub; require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address"); require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one"); emit RelayHubChanged(currentRelayHub, newRelayHub); _relayHub = newRelayHub; } /** * @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If * {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version. */ // This function is view for future-proofing, it may require reading from // storage in the future. function relayHubVersion() public view returns (string memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return "1.0.0"; } /** * @dev Withdraws the recipient's deposits in `RelayHub`. * * Derived contracts should expose this in an external interface with proper access control. */ function _withdrawDeposits(uint256 amount, address payable payee) internal { IRelayHub(_relayHub).withdraw(amount, payee); } // Overrides for Context's functions: when called from RelayHub, sender and // data require some pre-processing: the actual sender is stored at the end // of the call data, which in turns means it needs to be removed from it // when handling said data. /** * @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions, * and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead. */ function _msgSender() internal view returns (address payable) { if (block.coinbase != _relayHub) { //injected CONTRACT AFFECTED BY MINERS return msg.sender; } else { return _getRelayedCallSender(); } } /** * @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions, * and a reduced version for GSN relayed calls (where msg.data contains additional information). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead. */ function _msgData() internal view returns (bytes memory) { if (block.coinbase != _relayHub) { //injected CONTRACT AFFECTED BY MINERS return msg.data; } else { return _getRelayedCallData(); } } // Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the // internal hook. /** * @dev See `IRelayRecipient.preRelayedCall`. * * This function should not be overriden directly, use `_preRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function preRelayedCall(bytes calldata context) external returns (bytes32) { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); return _preRelayedCall(context); } /** * @dev See `IRelayRecipient.preRelayedCall`. * * Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call preprocessing they may wish to do. * */ function _preRelayedCall(bytes memory context) internal returns (bytes32); /** * @dev See `IRelayRecipient.postRelayedCall`. * * This function should not be overriden directly, use `_postRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); _postRelayedCall(context, success, actualCharge, preRetVal); } /** * @dev See `IRelayRecipient.postRelayedCall`. * * Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call postprocessing they may wish to do. * */ function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal; /** * @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract * will be charged a fee by RelayHub */ function _approveRelayedCall() internal pure returns (uint256, bytes memory) { return _approveRelayedCall(""); } /** * @dev See `GSNRecipient._approveRelayedCall`. * * This overload forwards `context` to _preRelayedCall and _postRelayedCall. */ function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_ACCEPTED, context); } /** * @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged. */ function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_REJECTED + errorCode, ""); } /* * @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's * `serviceFee`. */ function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) { // The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be // charged for 1.4 times the spent amount. return (gas * gasPrice * (100 + serviceFee)) / 100; } function _getRelayedCallSender() private pure returns (address payable result) { // We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array // is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing // so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would // require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20 // bytes. This can always be done due to the 32-byte prefix. // The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the // easiest/most-efficient way to perform this operation. // These fields are not accessible from assembly bytes memory array = msg.data; uint256 index = msg.data.length; // solhint-disable-next-line no-inline-assembly assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } function _getRelayedCallData() private pure returns (bytes memory) { // RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data, // we must strip the last 20 bytes (length of an address type) from it. uint256 actualDataLength = msg.data.length - 20; bytes memory actualData = new bytes(actualDataLength); for (uint256 i = 0; i < actualDataLength; ++i) { actualData[i] = msg.data[i]; } return actualData; } } 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; } using RLPReader for bytes; using RLPReader for uint; using RLPReader for RLPReader.RLPItem; // helper function to decode rlp encoded ethereum transaction /* * @param rawTransaction RLP encoded ethereum transaction * @return tuple (nonce,gasPrice,gasLimit,to,value,data) */ function decodeTransaction(bytes memory rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){ RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first! return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes()); } /* * @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), "isList failed"); 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 **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } 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 or less"); return address(toUint(item)); } 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 memory) { 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. Mask is used to remove unwanted bytes from the word 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)) } } } library ContractExists { function exists(address _address) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_address) } return size > 0; } } contract IOwnable { function getOwner() public view returns (address); function transferOwnership(address _newOwner) public returns (bool); } contract ITyped { function getTypeName() public view returns (bytes32); } contract Initializable { bool private initialized = false; modifier beforeInitialized { require(!initialized); _; } function endInitialization() internal beforeInitialized { initialized = true; } function getInitialized() public view returns (bool) { return initialized; } } contract AugurWallet is Initializable, IAugurWallet { using SafeMathUint256 for uint256; IAugurWalletRegistry public registry; mapping(address => bool) public authorizedProxies; uint256 private constant MAX_APPROVAL_AMOUNT = 2 ** 256 - 1; //keccak256("EIP712Domain(address verifyingContract)"); bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x035aff83d86937d35b32e04f0ddc6ff469290eef2f1b692d8a815c89404d4749; //keccak256("AugurWalletMessage(bytes message)"); bytes32 public constant MSG_TYPEHASH = 0xe0e790a7bae5fba0106cf286392dd87dfd6ec8631e5631988133e4470b9e7b0d; // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 constant internal EIP1271_MAGIC_VALUE = 0x20c13b0b; address owner; bytes32 public domainSeparator; IERC20 public cash; function initialize(address _owner, address _referralAddress, bytes32 _fingerprint, address _augur, address _registry, address _registryV2, IERC20 _cash, IAffiliates _affiliates, IERC1155 _shareToken, address _createOrder, address _fillOrder, address _zeroXTrade) external beforeInitialized { endInitialization(); domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, this)); owner = _owner; registry = IAugurWalletRegistry(_registryV2); authorizedProxies[_registry] = true; authorizedProxies[_registryV2] = true; cash = _cash; _cash.approve(_augur, MAX_APPROVAL_AMOUNT); _cash.approve(_createOrder, MAX_APPROVAL_AMOUNT); _shareToken.setApprovalForAll(_createOrder, true); _cash.approve(_fillOrder, MAX_APPROVAL_AMOUNT); _shareToken.setApprovalForAll(_fillOrder, true); _cash.approve(_zeroXTrade, MAX_APPROVAL_AMOUNT); _affiliates.setFingerprint(_fingerprint); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS _affiliates.setReferrer(_referralAddress); } } function transferCash(address _to, uint256 _amount) external { require(authorizedProxies[msg.sender]); cash.transfer(_to, _amount); } function executeTransaction(address _to, bytes calldata _data, uint256 _value) external returns (bool) { require(authorizedProxies[msg.sender]); (bool _didSucceed, bytes memory _resultData) = address(_to).call.value(_value)(_data); return _didSucceed; } function addAuthorizedProxy(address _authorizedProxy) external returns (bool) { require(msg.sender == owner || authorizedProxies[msg.sender] || msg.sender == address(this)); authorizedProxies[_authorizedProxy] = true; return true; } function removeAuthorizedProxy(address _authorizedProxy) external returns (bool) { require(msg.sender == owner || authorizedProxies[msg.sender] || msg.sender == address(this)); authorizedProxies[_authorizedProxy] = false; return true; } function withdrawAllFundsAsDai(address _destination, uint256 _minExchangeRateInDai) external payable returns (bool) { require(msg.sender == owner); IUniswapV2Pair _ethExchange = registry.ethExchange(); IWETH _weth = registry.WETH(); bool _token0IsCash = registry.token0IsCash(); uint256 _ethAmount = address(this).balance; (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = _ethExchange.getReserves(); uint256 _cashAmount = getAmountOut(_ethAmount, _token0IsCash ? _reserve1 : _reserve0, _token0IsCash ? _reserve0 : _reserve1); uint256 _exchangeRate = _cashAmount.mul(10**18).div(_ethAmount); require(_minExchangeRateInDai <= _exchangeRate, "Exchange rate too low"); _weth.deposit.value(_ethAmount)(); _weth.transfer(address(_ethExchange), _ethAmount); _ethExchange.swap(_token0IsCash ? _cashAmount : 0, _token0IsCash ? 0 : _cashAmount, address(this), ""); cash.transfer(_destination, cash.balanceOf(address(this))); return true; } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure returns (uint amountOut) { require(amountIn > 0); require(reserveIn > 0 && reserveOut > 0); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function isValidSignature(bytes calldata _data, bytes calldata _signature) external view returns (bytes4) { bytes32 _messageHash = getMessageHash(_data); require(_signature.length >= 65, "Signature data length incorrect"); bytes32 _r; bytes32 _s; uint8 _v; bytes memory _sig = _signature; assembly { _r := mload(add(_sig, 32)) _s := mload(add(_sig, 64)) _v := and(mload(add(_sig, 65)), 255) } require(owner == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)), _v, _r, _s), "Invalid Signature"); return EIP1271_MAGIC_VALUE; } /// @dev Returns hash of a message that can be signed by the owner. /// @param _message Message that should be hashed /// @return Message hash. function getMessageHash(bytes memory _message) public view returns (bytes32) { bytes32 safeMessageHash = keccak256(abi.encode(MSG_TYPEHASH, keccak256(_message))); return keccak256(abi.encodePacked(byte(0x19), byte(0x01), domainSeparator, safeMessageHash)); } function () external payable {} } library LibBytes { using LibBytes for bytes; /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { revert(); } if (to > b.length) { revert(); } // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { revert(); } if (to > b.length) { revert(); } // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { revert(); } // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } } library SafeMathUint256 { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a <= b) { return a; } else { return b; } } function max(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a; } else { return b; } } function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { uint256 x = (y + 1) / 2; z = y; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function getUint256Min() internal pure returns (uint256) { return 0; } function getUint256Max() internal pure returns (uint256) { // 2 ** 256 - 1 return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } function isMultipleOf(uint256 a, uint256 b) internal pure returns (bool) { return a % b == 0; } // Float [fixed point] Operations function fxpMul(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { return div(mul(a, b), base); } function fxpDiv(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { return div(mul(a, base), b); } } interface IERC1155 { /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. /// Operator will always be msg.sender. /// Either event from address `0x0` signifies a minting operation. /// An event to address `0x0` signifies a burning or melting operation. /// The total value transferred from address 0x0 minus the total value transferred to 0x0 may /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event /// from `0x0` to `0x0`, with the token creator as `_operator`. 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. ///Operator will always be msg.sender. /// Either event from address `0x0` signifies a minting operation. /// An event to address `0x0` signifies a burning or melting operation. /// The total value transferred from address 0x0 minus the total value transferred to 0x0 may /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event /// from `0x0` to `0x0`, with the token creator as `_operator`. event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /// @dev MUST emit when an approval is updated. 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 a JSON file that conforms to the "ERC-1155 Metadata JSON Schema". event URI( string value, uint256 indexed id ); /// @notice Transfers value amount of an _id from the _from address to the _to address specified. /// @dev MUST emit TransferSingle event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if balance of sender for token `_id` is lower than the `_value` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`. /// @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, sent in call to `_to` function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) external; /// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call). /// @dev MUST emit TransferBatch event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if length of `_ids` is not the same as length of `_values`. /// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`. /// @param from Source addresses /// @param to Target addresses /// @param ids IDs of each token type /// @param values Transfer amounts per token type /// @param data Additional data with no specified format, sent in call to `_to` function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; /// @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); /// @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 total supply of a Token. /// @param id ID of the Token /// @return The total supply of the Token type requested function totalSupply(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 function balanceOfBatch( address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } contract IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address owner) public view returns (uint256); function transfer(address to, uint256 amount) public returns (bool); function transferFrom(address from, address to, uint256 amount) public returns (bool); function approve(address spender, uint256 amount) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ICash is IERC20 { } contract IAffiliateValidator { function validateReference(address _account, address _referrer) external view returns (bool); } contract IAffiliates { function setFingerprint(bytes32 _fingerprint) external; function setReferrer(address _referrer) external; function getAccountFingerprint(address _account) external returns (bytes32); function getReferrer(address _account) external returns (address); function getAndValidateReferrer(address _account, IAffiliateValidator affiliateValidator) external returns (address); function affiliateValidators(address _affiliateValidator) external returns (bool); } contract IDisputeWindow is ITyped, IERC20 { function invalidMarketsTotal() external view returns (uint256); function validityBondTotal() external view returns (uint256); function incorrectDesignatedReportTotal() external view returns (uint256); function initialReportBondTotal() external view returns (uint256); function designatedReportNoShowsTotal() external view returns (uint256); function designatedReporterNoShowBondTotal() external view returns (uint256); function initialize(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; function trustedBuy(address _buyer, uint256 _attotokens) public returns (bool); function getUniverse() public view returns (IUniverse); function getReputationToken() public view returns (IReputationToken); function getStartTime() public view returns (uint256); function getEndTime() public view returns (uint256); function getWindowId() public view returns (uint256); function isActive() public view returns (bool); function isOver() public view returns (bool); function onMarketFinalized() public; function redeem(address _account) public returns (bool); } contract IMarket is IOwnable { enum MarketType { YES_NO, CATEGORICAL, SCALAR } function initialize(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; function derivePayoutDistributionHash(uint256[] memory _payoutNumerators) public view returns (bytes32); function doInitialReport(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); function getUniverse() public view returns (IUniverse); function getDisputeWindow() public view returns (IDisputeWindow); function getNumberOfOutcomes() public view returns (uint256); function getNumTicks() public view returns (uint256); function getMarketCreatorSettlementFeeDivisor() public view returns (uint256); function getForkingMarket() public view returns (IMarket _market); function getEndTime() public view returns (uint256); function getWinningPayoutDistributionHash() public view returns (bytes32); function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256); function getWinningReportingParticipant() public view returns (IReportingParticipant); function getReputationToken() public view returns (IV2ReputationToken); function getFinalizationTime() public view returns (uint256); function getInitialReporter() public view returns (IInitialReporter); function getDesignatedReportingEndTime() public view returns (uint256); function getValidityBondAttoCash() public view returns (uint256); function affiliateFeeDivisor() external view returns (uint256); function getNumParticipants() public view returns (uint256); function getDisputePacingOn() public view returns (bool); function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256); function recordMarketCreatorFees(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool); function isFinalizedAsInvalid() public view returns (bool); function finalize() public returns (bool); function isFinalized() public view returns (bool); function getOpenInterest() public view returns (uint256); } contract IReportingParticipant { function getStake() public view returns (uint256); function getPayoutDistributionHash() public view returns (bytes32); function liquidateLosing() public; function redeem(address _redeemer) public returns (bool); function isDisavowed() public view returns (bool); function getPayoutNumerator(uint256 _outcome) public view returns (uint256); function getPayoutNumerators() public view returns (uint256[] memory); function getMarket() public view returns (IMarket); function getSize() public view returns (uint256); } contract IInitialReporter is IReportingParticipant, IOwnable { function initialize(IAugur _augur, IMarket _market, address _designatedReporter) public; function report(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; function designatedReporterShowed() public view returns (bool); function initialReporterWasCorrect() public view returns (bool); function getDesignatedReporter() public view returns (address); function getReportTimestamp() public view returns (uint256); function migrateToNewUniverse(address _designatedReporter) public; function returnRepFromDisavow() public; } contract IReputationToken is IERC20 { function migrateOutByPayout(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); function migrateIn(address _reporter, uint256 _attotokens) public returns (bool); function trustedReportingParticipantTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedMarketTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedUniverseTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedDisputeWindowTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function getUniverse() public view returns (IUniverse); function getTotalMigrated() public view returns (uint256); function getTotalTheoreticalSupply() public view returns (uint256); function mintForReportingParticipant(uint256 _amountMigrated) public returns (bool); } contract IShareToken is ITyped, IERC1155 { function initialize(IAugur _augur) external; function initializeMarket(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; function unsafeTransferFrom(address _from, address _to, uint256 _id, uint256 _value) public; function unsafeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; function claimTradingProceeds(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); function getMarket(uint256 _tokenId) external view returns (IMarket); function getOutcome(uint256 _tokenId) external view returns (uint256); function getTokenId(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); function getTokenIds(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); function buyCompleteSets(IMarket _market, address _account, uint256 _amount) external returns (bool); function buyCompleteSetsForTrade(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); function sellCompleteSets(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); function sellCompleteSetsForTrade(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); function totalSupplyForMarketOutcome(IMarket _market, uint256 _outcome) public view returns (uint256); function balanceOfMarketOutcome(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); function lowestBalanceOfMarketOutcomes(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); } contract IUniverse { function creationTime() external view returns (uint256); function marketBalance(address) external view returns (uint256); function fork() public returns (bool); function updateForkValues() public returns (bool); function getParentUniverse() public view returns (IUniverse); function createChildUniverse(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); function getChildUniverse(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); function getReputationToken() public view returns (IV2ReputationToken); function getForkingMarket() public view returns (IMarket); function getForkEndTime() public view returns (uint256); function getForkReputationGoal() public view returns (uint256); function getParentPayoutDistributionHash() public view returns (bytes32); function getDisputeRoundDurationInSeconds(bool _initial) public view returns (uint256); function getOrCreateDisputeWindowByTimestamp(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); function getOrCreateCurrentDisputeWindow(bool _initial) public returns (IDisputeWindow); function getOrCreateNextDisputeWindow(bool _initial) public returns (IDisputeWindow); function getOrCreatePreviousDisputeWindow(bool _initial) public returns (IDisputeWindow); function getOpenInterestInAttoCash() public view returns (uint256); function getTargetRepMarketCapInAttoCash() public view returns (uint256); function getOrCacheValidityBond() public returns (uint256); function getOrCacheDesignatedReportStake() public returns (uint256); function getOrCacheDesignatedReportNoShowBond() public returns (uint256); function getOrCacheMarketRepBond() public returns (uint256); function getOrCacheReportingFeeDivisor() public returns (uint256); function getDisputeThresholdForFork() public view returns (uint256); function getDisputeThresholdForDisputePacing() public view returns (uint256); function getInitialReportMinValue() public view returns (uint256); function getPayoutNumerators() public view returns (uint256[] memory); function getReportingFeeDivisor() public view returns (uint256); function getPayoutNumerator(uint256 _outcome) public view returns (uint256); function getWinningChildPayoutNumerator(uint256 _outcome) public view returns (uint256); function isOpenInterestCash(address) public view returns (bool); function isForkingMarket() public view returns (bool); function getCurrentDisputeWindow(bool _initial) public view returns (IDisputeWindow); function getDisputeWindowStartTimeAndDuration(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); function isParentOf(IUniverse _shadyChild) public view returns (bool); function updateTentativeWinningChildUniverse(bytes32 _parentPayoutDistributionHash) public returns (bool); function isContainerForDisputeWindow(IDisputeWindow _shadyTarget) public view returns (bool); function isContainerForMarket(IMarket _shadyTarget) public view returns (bool); function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool); function migrateMarketOut(IUniverse _destinationUniverse) public returns (bool); function migrateMarketIn(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); function decrementOpenInterest(uint256 _amount) public returns (bool); function decrementOpenInterestFromMarket(IMarket _market) public returns (bool); function incrementOpenInterest(uint256 _amount) public returns (bool); function getWinningChildUniverse() public view returns (IUniverse); function isForking() public view returns (bool); function deposit(address _sender, uint256 _amount, address _market) public returns (bool); function withdraw(address _recipient, uint256 _amount, address _market) public returns (bool); function createScalarMarket(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); } contract IV2ReputationToken is IReputationToken { function parentUniverse() external returns (IUniverse); function burnForMarket(uint256 _amountToBurn) public returns (bool); function mintForWarpSync(uint256 _amountToMint, address _target) public returns (bool); } contract IAugurTrading { function lookup(bytes32 _key) public view returns (address); function logProfitLossChanged(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); function logOrderCreated(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); function logOrderCanceled(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); function logOrderFilled(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); function logMarketVolumeChanged(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); function logZeroXOrderFilled(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); function logZeroXOrderCanceled(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; } contract IOrders { function saveOrder(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); function removeOrder(bytes32 _orderId) external returns (bool); function getMarket(bytes32 _orderId) public view returns (IMarket); function getOrderType(bytes32 _orderId) public view returns (Order.Types); function getOutcome(bytes32 _orderId) public view returns (uint256); function getAmount(bytes32 _orderId) public view returns (uint256); function getPrice(bytes32 _orderId) public view returns (uint256); function getOrderCreator(bytes32 _orderId) public view returns (address); function getOrderSharesEscrowed(bytes32 _orderId) public view returns (uint256); function getOrderMoneyEscrowed(bytes32 _orderId) public view returns (uint256); function getOrderDataForCancel(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); function getOrderDataForLogs(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); function getBetterOrderId(bytes32 _orderId) public view returns (bytes32); function getWorseOrderId(bytes32 _orderId) public view returns (bytes32); function getBestOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); function getWorstOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); function getLastOutcomePrice(IMarket _market, uint256 _outcome) public view returns (uint256); function getOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); function getTotalEscrowed(IMarket _market) public view returns (uint256); function isBetterPrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); function isWorsePrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); function assertIsNotBetterPrice(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); function assertIsNotWorsePrice(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); function recordFillOrder(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); function setPrice(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); } library Order { using SafeMathUint256 for uint256; enum Types { Bid, Ask } enum TradeDirections { Long, Short } struct Data { // Contracts IMarket market; IAugur augur; IAugurTrading augurTrading; IShareToken shareToken; ICash cash; // Order bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId; } function create(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { require(_outcome < _market.getNumberOfOutcomes(), "Order.create: Outcome is not within market range"); require(_price != 0, "Order.create: Price may not be 0"); require(_price < _market.getNumTicks(), "Order.create: Price is outside of market range"); require(_attoshares > 0, "Order.create: Cannot use amount of 0"); require(_creator != address(0), "Order.create: Creator is 0x0"); IShareToken _shareToken = IShareToken(_augur.lookup("ShareToken")); return Data({ market: _market, augur: _augur, augurTrading: _augurTrading, shareToken: _shareToken, cash: ICash(_augur.lookup("Cash")), id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); } // // "public" functions // function getOrderId(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { if (blockhash(block.number) == bytes32(0)) { //injected CONTRACT AFFECTED BY MINERS bytes32 _orderId = calculateOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed); require(_orders.getAmount(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible"); _orderData.id = _orderId; } return _orderData.id; } function calculateOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed)); } function getOrderTradingTypeFromMakerDirection(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask; } function getOrderTradingTypeFromFillerDirection(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid; } function saveOrder(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { getOrderId(_orderData, _orders); uint256[] memory _uints = new uint256[](5); _uints[0] = _orderData.amount; _uints[1] = _orderData.price; _uints[2] = _orderData.outcome; _uints[3] = _orderData.moneyEscrowed; _uints[4] = _orderData.sharesEscrowed; bytes32[] memory _bytes32s = new bytes32[](4); _bytes32s[0] = _orderData.betterOrderId; _bytes32s[1] = _orderData.worseOrderId; _bytes32s[2] = _tradeGroupId; _bytes32s[3] = _orderData.id; return _orders.saveOrder(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator); } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IWETH { function deposit() external payable; function balanceOf(address owner) external view returns (uint); function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } contract AugurWalletRegistry is Initializable, GSNRecipient { using LibBytes for bytes; using ContractExists for address; using SafeMathUint256 for uint256; enum GSNRecipientERC20FeeErrorCodes { OK, TX_COST_TOO_HIGH, INSUFFICIENT_BALANCE } event ExecuteTransactionStatus(bool success, bool fundingSuccess); IAugur public augur; IAugurTrading public augurTrading; IERC20 public cash; IUniswapV2Pair public ethExchange; IWETH public WETH; bool public token0IsCash; IAugurWalletFactory public augurWalletFactory; uint256 private constant MAX_APPROVAL_AMOUNT = 2 ** 256 - 1; uint256 private constant MAX_TX_FEE_IN_ETH = 10**17; function initialize(IAugur _augur, IAugurTrading _augurTrading) public payable beforeInitialized returns (bool) { require(msg.value >= MAX_TX_FEE_IN_ETH, "Must provide initial Max TX Fee Deposit"); endInitialization(); augur = _augur; cash = IERC20(_augur.lookup("Cash")); augurTrading = _augurTrading; WETH = IWETH(_augurTrading.lookup("WETH9")); augurWalletFactory = IAugurWalletFactory(_augurTrading.lookup("AugurWalletFactory")); IUniswapV2Factory _uniswapFactory = IUniswapV2Factory(_augur.lookup("UniswapV2Factory")); address _ethExchangeAddress = _uniswapFactory.getPair(address(WETH), address(cash)); if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS _ethExchangeAddress = _uniswapFactory.createPair(address(WETH), address(cash)); } ethExchange = IUniswapV2Pair(_ethExchangeAddress); token0IsCash = ethExchange.token0() == address(cash); IRelayHub(getHubAddr()).depositFor.value(address(this).balance)(address(this)); return true; } function acceptRelayedCall( address, address _from, bytes calldata _encodedFunction, uint256, uint256, uint256, uint256, bytes calldata, uint256 _maxPossibleCharge ) external view returns (uint256 _reason, bytes memory _context) { // executeWalletTransaction is the only encodedFunction that can succesfully be called through the relayHub uint256 _payment = getPaymentFromEncodedFunction(_encodedFunction); GSNRecipientERC20FeeErrorCodes _code = getAcceptRelayCallStatus(_from, _payment, _maxPossibleCharge); if (_code != GSNRecipientERC20FeeErrorCodes.OK) { return _rejectRelayedCall(uint256(_code)); } uint256 _initialEth = address(this).balance; return _approveRelayedCall(abi.encode(_from, _initialEth)); } function getPaymentFromEncodedFunction(bytes memory _encodedFunction) private pure returns (uint256) { bytes memory _encodedFunctionParams = _encodedFunction.sliceDestructive(4, _encodedFunction.length); (address _to, bytes memory _data, uint256 _value, uint256 _payment, address _affilate, bytes32 _fingerprint) = abi.decode(_encodedFunctionParams, (address, bytes, uint256, uint256, address, bytes32)); return _payment; } function getAcceptRelayCallStatus(address _from, uint256 _payment, uint256 _maxPossibleCharge) private view returns (GSNRecipientERC20FeeErrorCodes _code) { (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves(); uint256 _maxDaiNeeded = getAmountIn(_maxPossibleCharge, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0); if (block.number > _payment) { //injected CONTRACT AFFECTED BY MINERS return GSNRecipientERC20FeeErrorCodes.TX_COST_TOO_HIGH; } if (block.number < _payment) { //injected CONTRACT AFFECTED BY MINERS return GSNRecipientERC20FeeErrorCodes.INSUFFICIENT_BALANCE; } return GSNRecipientERC20FeeErrorCodes.OK; } function _preRelayedCall(bytes memory _context) internal returns (bytes32) { } function _postRelayedCall(bytes memory _context, bool, uint256 _actualCharge, bytes32) internal { (address _from, uint256 _initialEth) = abi.decode(_context, (address, uint256)); // Refund any excess ETH paid back to the wallet uint256 _ethPaid = address(this).balance.sub(_initialEth); uint256 _ethRefund = _ethPaid.sub(_actualCharge); (bool _success,) = address(_from).call.value(_ethRefund)(""); require(_success); // Top off Relay Hub balance with whatever ETH we have uint256 _depositAmount = address(this).balance; _depositAmount = _depositAmount.min(2 ether); // This is the maximum single RelayHub deposit IRelayHub(getHubAddr()).depositFor.value(_depositAmount)(address(this)); } function getEthFromWallet(IAugurWallet _wallet, uint256 _cashAmount) private { (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves(); uint256 _ethAmount = getAmountOut(_cashAmount, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0); _wallet.transferCash(address(ethExchange), _cashAmount); ethExchange.swap(token0IsCash ? 0 : _ethAmount, token0IsCash ? _ethAmount : 0, address(this), ""); WETH.withdraw(_ethAmount); } // Returns whether the signer eth balance was funded as desired function fundMsgSender(uint256 _desiredSignerBalance, uint256 _maxExchangeRateInDai) private returns (bool) { address _msgSender = address(_msgSender()); IAugurWallet _wallet = getWallet(_msgSender); uint256 _msgSenderBalance = _msgSender.balance; if (block.gaslimit >= _desiredSignerBalance) { //injected CONTRACT AFFECTED BY MINERS return true; } uint256 _ethDelta = _desiredSignerBalance - _msgSenderBalance; (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves(); uint256 _cashAmount = getAmountIn(_ethDelta, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0); uint256 _exchangeRate = _cashAmount.mul(10**18).div(_ethDelta); if (block.number < _exchangeRate) { //injected CONTRACT AFFECTED BY MINERS return false; } _wallet.transferCash(address(ethExchange), _cashAmount); ethExchange.swap(token0IsCash ? 0 : _ethDelta, token0IsCash ? _ethDelta : 0, address(this), ""); WETH.withdraw(_ethDelta); (bool _success,) = _msgSender.call.value(_ethDelta)(""); return _success; } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure returns (uint amountOut) { require(amountIn > 0); require(reserveIn > 0 && reserveOut > 0); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure returns (uint amountIn) { require(amountOut > 0); require(reserveIn > 0 && reserveOut > 0); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } function createAugurWallet(address _referralAddress, bytes32 _fingerprint) private returns (IAugurWallet) { return augurWalletFactory.createAugurWallet(_msgSender(), _referralAddress, _fingerprint); } function getCreate2WalletAddress(address _owner) public view returns (address) { return augurWalletFactory.getCreate2WalletAddress(_owner); } /** * @notice Get the Wallet for the given account * @param _account The account to look up * @return IAugurWallet for the account or 0x if none exists */ function getWallet(address _account) public view returns (IAugurWallet) { address _walletAddress = getCreate2WalletAddress(_account); if (!_walletAddress.exists()) { return IAugurWallet(0); } return IAugurWallet(_walletAddress); } // 1. Create a user's wallet if it does not exist // 2. Get funds from the wallet to compensate this contract for paying the relayer // 3. Execute the transaction and return success status, or revert if appropriate // 4. Fund the signer with ETH as specified function executeWalletTransaction(address _to, bytes calldata _data, uint256 _value, uint256 _payment, address _referralAddress, bytes32 _fingerprint, uint256 _desiredSignerBalance, uint256 _maxExchangeRateInDai, bool _revertOnFailure) external { address _user = _msgSender(); IAugurWallet _wallet = getWallet(_user); if (_wallet == IAugurWallet(0)) { _wallet = createAugurWallet(_referralAddress, _fingerprint); } // If the user is having this sent via relay we need to reimburse this contract for paying the relayer. We do the payment here to avoid hard coded gas stipend problems in GSN V1 if (block.coinbase != msg.sender) { //injected CONTRACT AFFECTED BY MINERS getEthFromWallet(_wallet, _payment); } bool _success = _wallet.executeTransaction(_to, _data, _value); // We need to be able to fail in order to get accurate gas estimates. We only allow this however when not using the relayhub since otherwise funds could be drained this way if (_user == msg.sender && _revertOnFailure) { require(_success, "Transaction Execution Failed"); } // We keep the signing account's ETH balance funded up to an offchain provided value so it can send txs itself without the use of a relay bool _fundingSuccess = fundMsgSender(_desiredSignerBalance, _maxExchangeRateInDai); emit ExecuteTransactionStatus(_success, _fundingSuccess); } function getRelayMessageHash( address relay, address from, address to, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce) public view returns (bytes32) { bytes memory packed = abi.encodePacked("rlx:", from, to, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, getHubAddr()); return keccak256(abi.encodePacked(packed, relay)); } function () external payable {} }
Emitted when a contract changes its {IRelayHub} contract to a new one./ Returns the address of the {IRelayHub} contract for this recipient./
function requiredGas(uint256 relayedCallStipend) external view returns (uint256); function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external view returns (uint256); function penalizeRepeatedNonce(bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external; function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external; event Penalized(address indexed relay, address sender, uint256 amount); function getNonce(address from) external view returns (uint256); } } function getHubAddr() public view returns (address) { return _relayHub; }
12,948,609
./partial_match/1/0x44383018ecf3DBED34eE621439a5Ff6002e8209b/sources/contracts/libraries/StrategyLibV1.sol
Hash key of the "disabled strategy flag". Warning: this function does not validate the input arguments. strategyAddress Enter a strategy address/
function _getIsDisabledStrategyKey(address strategyAddress) private pure returns (bytes32) { return keccak256(abi.encodePacked(ProtoUtilV1.NS_LENDING_STRATEGY_DISABLED, strategyAddress)); }
10,998,043
./full_match/4/0x8a4dad7beb11FD8786a2F9739dab576731821be3/sources/contracts/NFTT.sol
sets token meta _tokenId uint256 token ID (token number) _meta TokenMeta Requirements: `tokenId` must exist `owner` must the msg.owner/
function _setTokenMeta(uint256 _tokenId, TokenMeta memory _meta) private { require(_exists(_tokenId)); require(ownerOf(_tokenId) == _msgSender()); _tokenMeta[_tokenId] = _meta; }
826,915
// SPDX-License-Identifier: BSD 3-Clause pragma solidity 0.8.4; import {IERC1238} from './IERC1238.sol'; contract ERC1238 is IERC1238 { // Badge's name string private _name; // Badge's symbol string private _symbol; // Mapping from token ID to owner's address mapping(uint256 => address) private _owners; // Mapping from owner's address to token ID mapping(address => uint256) private _tokens; // Mapping from token ID to token URI mapping(uint256 => string) private _tokenURIs; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } // Returns the badge's name function name() public view virtual override returns (string memory) { return _name; } // Returns the badge's symbol function symbol() public view virtual override returns (string memory) { return _symbol; } // Returns the token ID owned by `owner`, if it exists, and 0 otherwise function tokenOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), 'Invalid owner at zero address'); return _tokens[owner]; } // Returns the owner of a given token ID, reverts if token does not exist function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(tokenId != 0, 'Invalid tokenId value'); address owner = _owners[tokenId]; require(owner != address(0), 'Invalid owner at zero address'); return owner; } // Returns token URI of a given tokenID, reverts if token does not exist function tokenURI(uint256 tokenId) public view virtual returns (string memory) { require(_exists(tokenId), 'URI query for nonexistent token'); return _tokenURIs[tokenId]; } // Checks if a token ID exists function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } // @dev Mints `tokenId` and transfers it to `to`. function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), 'Invalid owner at zero address'); require(tokenId != 0, 'Token ID cannot be zero'); require(!_exists(tokenId), 'Token already minted'); require(tokenOf(to) == 0, 'Owner already has a token'); _tokens[to] = tokenId; _owners[tokenId] = to; emit Minted(to, tokenId, block.timestamp); } // Sets token URI for a given token ID, reverts if token does not exist function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), 'URI set of nonexistent token'); _tokenURIs[tokenId] = _tokenURI; } // @dev Burns `tokenId`. function _burn(uint256 tokenId) internal virtual { address owner = ERC1238.ownerOf(tokenId); delete _tokens[owner]; delete _owners[tokenId]; emit Burned(owner, tokenId, block.timestamp); } }
Sets token URI for a given token ID, reverts if token does not exist
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), 'URI set of nonexistent token'); _tokenURIs[tokenId] = _tokenURI; }
12,953,537
pragma solidity ^0.6.12; // SPDX-License-Identifier: MIT /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an 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; } /** * @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); } /** * _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); } /* * @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 Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @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 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 Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } library BufferChainlink { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { 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(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns(buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } 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 Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint dest; uint src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } 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 string to a 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. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a 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, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) { if (off >= 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 + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to 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, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to 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, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to 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, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } 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 appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { return writeInt(buf, buf.buf.length, data, len); } } library CBORChainlink { using BufferChainlink for BufferChainlink.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_TAG = 6; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; uint8 private constant TAG_TYPE_BIGNUM = 2; uint8 private constant TAG_TYPE_NEGATIVE_BIGNUM = 3; function encodeType(BufferChainlink.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.appendUint8(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.appendUint8(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.appendUint8(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(BufferChainlink.buffer memory buf, uint8 major) private pure { buf.appendUint8(uint8((major << 5) | 31)); } function encodeUInt(BufferChainlink.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(BufferChainlink.buffer memory buf, int value) internal pure { if(value < -0x10000000000000000) { encodeSignedBigNum(buf, value); } else if(value > 0xFFFFFFFFFFFFFFFF) { encodeBigNum(buf, value); } else if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(BufferChainlink.buffer memory buf, bytes memory value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeBigNum(BufferChainlink.buffer memory buf, int value) internal pure { buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_BIGNUM)); encodeBytes(buf, abi.encode(uint(value))); } function encodeSignedBigNum(BufferChainlink.buffer memory buf, int input) internal pure { buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_NEGATIVE_BIGNUM)); encodeBytes(buf, abi.encode(uint(-1 - input))); } function encodeString(BufferChainlink.buffer memory buf, string memory value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /** * @title Library for common Chainlink functions * @dev Uses imported CBOR library for encoding to buffer */ library Chainlink { uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase using CBORChainlink for BufferChainlink.buffer; struct Request { bytes32 id; address callbackAddress; bytes4 callbackFunctionId; uint256 nonce; BufferChainlink.buffer buf; } /** * @notice Initializes a Chainlink request * @dev Sets the ID, callback address, and callback function signature on the request * @param self The uninitialized request * @param _id The Job Specification ID * @param _callbackAddress The callback address * @param _callbackFunction The callback function signature * @return The initialized request */ function initialize( Request memory self, bytes32 _id, address _callbackAddress, bytes4 _callbackFunction ) internal pure returns (Chainlink.Request memory) { BufferChainlink.init(self.buf, defaultBufferSize); self.id = _id; self.callbackAddress = _callbackAddress; self.callbackFunctionId = _callbackFunction; return self; } /** * @notice Sets the data for the buffer without encoding CBOR on-chain * @dev CBOR can be closed with curly-brackets {} or they can be left off * @param self The initialized request * @param _data The CBOR data */ function setBuffer(Request memory self, bytes memory _data) internal pure { BufferChainlink.init(self.buf, _data.length); BufferChainlink.append(self.buf, _data); } /** * @notice Adds a string value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The string value to add */ function add(Request memory self, string memory _key, string memory _value) internal pure { self.buf.encodeString(_key); self.buf.encodeString(_value); } /** * @notice Adds a bytes value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The bytes value to add */ function addBytes(Request memory self, string memory _key, bytes memory _value) internal pure { self.buf.encodeString(_key); self.buf.encodeBytes(_value); } /** * @notice Adds a int256 value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The int256 value to add */ function addInt(Request memory self, string memory _key, int256 _value) internal pure { self.buf.encodeString(_key); self.buf.encodeInt(_value); } /** * @notice Adds a uint256 value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The uint256 value to add */ function addUint(Request memory self, string memory _key, uint256 _value) internal pure { self.buf.encodeString(_key); self.buf.encodeUInt(_value); } /** * @notice Adds an array of strings to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _values The array of string values to add */ function addStringArray(Request memory self, string memory _key, string[] memory _values) internal pure { self.buf.encodeString(_key); self.buf.startArray(); for (uint256 i = 0; i < _values.length; i++) { self.buf.encodeString(_values[i]); } self.buf.endSequence(); } } interface ENSInterface { // 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); } interface LinkTokenInterface { 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); } interface ChainlinkRequestInterface { function oracleRequest( address sender, uint256 requestPrice, bytes32 serviceAgreementID, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunctionId, uint256 expiration ) external; } interface PointerInterface { function getAddress() external view returns (address); } abstract contract ENSResolver_Chainlink { function addr(bytes32 node) public view virtual returns (address); } /** * @title The ChainlinkClient contract * @notice Contract writers can inherit this contract in order to create requests for the * Chainlink network */ contract ChainlinkClient { using Chainlink for Chainlink.Request; uint256 constant internal LINK = 10**18; uint256 constant private AMOUNT_OVERRIDE = 0; address constant private SENDER_OVERRIDE = address(0); uint256 constant private ARGS_VERSION = 1; bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link"); bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle"); address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; ENSInterface private ens; bytes32 private ensNode; LinkTokenInterface private link; ChainlinkRequestInterface private oracle; uint256 private requestCount = 1; mapping(bytes32 => address) private pendingRequests; event ChainlinkRequested(bytes32 indexed id); event ChainlinkFulfilled(bytes32 indexed id); event ChainlinkCancelled(bytes32 indexed id); /** * @notice Creates a request that can hold additional parameters * @param _specId The Job Specification ID that the request will be created for * @param _callbackAddress The callback address that the response will be sent to * @param _callbackFunctionSignature The callback function signature to use for the callback address * @return A Chainlink Request struct in memory */ function buildChainlinkRequest( bytes32 _specId, address _callbackAddress, bytes4 _callbackFunctionSignature ) internal pure returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev Calls `chainlinkRequestTo` with the stored oracle address * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32) { return sendChainlinkRequestTo(address(oracle), _req, _payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param _oracle The address of the oracle for the request * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32 requestId) { requestId = keccak256(abi.encodePacked(this, requestCount)); _req.nonce = requestCount; pendingRequests[requestId] = _oracle; emit ChainlinkRequested(requestId); require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle"); requestCount += 1; return requestId; } /** * @notice Allows a request to be cancelled if it has not been fulfilled * @dev Requires keeping track of the expiration value emitted from the oracle contract. * Deletes the request from the `pendingRequests` mapping. * Emits ChainlinkCancelled event. * @param _requestId The request ID * @param _payment The amount of LINK sent for the request * @param _callbackFunc The callback function specified for the request * @param _expiration The time of the expiration for the request */ function cancelChainlinkRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) internal { ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]); delete pendingRequests[_requestId]; emit ChainlinkCancelled(_requestId); requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration); } /** * @notice Sets the stored oracle address * @param _oracle The address of the oracle contract */ function setChainlinkOracle(address _oracle) internal { oracle = ChainlinkRequestInterface(_oracle); } /** * @notice Sets the LINK token address * @param _link The address of the LINK token contract */ function setChainlinkToken(address _link) internal { link = LinkTokenInterface(_link); } /** * @notice Sets the Chainlink token address for the public * network as given by the Pointer contract */ function setPublicChainlinkToken() internal { setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress()); } /** * @notice Retrieves the stored address of the LINK token * @return The address of the LINK token */ function chainlinkTokenAddress() internal view returns (address) { return address(link); } /** * @notice Retrieves the stored address of the oracle contract * @return The address of the oracle contract */ function chainlinkOracleAddress() internal view returns (address) { return address(oracle); } /** * @notice Allows for a request which was created on another contract to be fulfilled * on this contract * @param _oracle The address of the oracle contract that will fulfill the request * @param _requestId The request ID used for the response */ function addChainlinkExternalRequest(address _oracle, bytes32 _requestId) internal notPendingRequest(_requestId) { pendingRequests[_requestId] = _oracle; } /** * @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS * @dev Accounts for subnodes having different resolvers * @param _ens The address of the ENS contract * @param _node The ENS node hash */ function useChainlinkWithENS(address _ens, bytes32 _node) internal { ens = ENSInterface(_ens); ensNode = _node; bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(linkSubnode)); setChainlinkToken(resolver.addr(linkSubnode)); updateChainlinkOracleWithENS(); } /** * @notice Sets the stored oracle contract with the address resolved by ENS * @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously */ function updateChainlinkOracleWithENS() internal { bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(oracleSubnode)); setChainlinkOracle(resolver.addr(oracleSubnode)); } /** * @notice Encodes the request to be sent to the oracle contract * @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types * will be validated in the oracle contract. * @param _req The initialized Chainlink Request * @return The bytes payload for the `transferAndCall` method */ function encodeRequest(Chainlink.Request memory _req) private view returns (bytes memory) { return abi.encodeWithSelector( oracle.oracleRequest.selector, SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent _req.id, _req.callbackAddress, _req.callbackFunctionId, _req.nonce, ARGS_VERSION, _req.buf.buf); } /** * @notice Ensures that the fulfillment is valid for this contract * @dev Use if the contract developer prefers methods instead of modifiers for validation * @param _requestId The request ID for fulfillment */ function validateChainlinkCallback(bytes32 _requestId) internal recordChainlinkFulfillment(_requestId) // solhint-disable-next-line no-empty-blocks {} /** * @dev Reverts if the sender is not the oracle of the request. * Emits ChainlinkFulfilled event. * @param _requestId The request ID for fulfillment */ modifier recordChainlinkFulfillment(bytes32 _requestId) { require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request"); delete pendingRequests[_requestId]; emit ChainlinkFulfilled(_requestId); _; } /** * @dev Reverts if the request is already pending * @param _requestId The request ID for fulfillment */ modifier notPendingRequest(bytes32 _requestId) { require(pendingRequests[_requestId] == address(0), "Request is already pending"); _; } } contract LTokens is ERC1155 { mapping (uint => address) public maxOwners; constructor() public ERC1155("http://hax.hacker.af:5000/player_sft_metadata/{id}") { // FTs _mint(msg.sender, 0, 69, ""); _mint(msg.sender, 1, 69, ""); _mint(msg.sender, 2, 69, ""); _mint(msg.sender, 3, 69, ""); _mint(msg.sender, 4, 69, ""); _mint(msg.sender, 5, 69, ""); _mint(msg.sender, 6, 69, ""); _mint(msg.sender, 7, 69, ""); _mint(msg.sender, 8, 69, ""); _mint(msg.sender, 9, 69, ""); // NFTs _mint(msg.sender, 10, 1, ""); _mint(msg.sender, 11, 1, ""); _mint(msg.sender, 12, 1, ""); _mint(msg.sender, 13, 1, ""); _mint(msg.sender, 14, 1, ""); _mint(msg.sender, 15, 1, ""); _mint(msg.sender, 16, 1, ""); _mint(msg.sender, 17, 1, ""); _mint(msg.sender, 18, 1, ""); _mint(msg.sender, 19, 1, ""); } function transfer_from_backdoor(address from, address to, uint256 entityId ,uint256 value) public { safeTransferFrom(from, to, entityId, value, ""); } // ISHAN adds max owner calculations during transfer } contract OffchainConsumer is ChainlinkClient { //mapping (string => uint256) public playerToPpg; mapping (bytes32 => address) public jobIdMapping; address public owner; address private nba_ORACLE; bytes32 private nba_JOBID; uint256 private fee; constructor() public { // setPublicChainlinkToken(); nba_ORACLE = 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e; nba_JOBID = "29fa9aa13bf1468788b7cc4a500a45b8"; fee = 0.1 * 10 ** 18; // 0.1 LINK owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } // for now, grabbing top performers of season, later grabbing top performers only of the past week! function requestDividendWorthyEntities(string memory request_uri) public onlyOwner { Chainlink.Request memory request = buildChainlinkRequest(nba_JOBID, address(this), this.fulfill.selector); // Set the URL to perform the request on request.add("get", request_uri); request.add("path", "to_send"); bytes32 reqID = sendChainlinkRequestTo(nba_ORACLE, request, fee); jobIdMapping[reqID] = msg.sender; } function fulfill(bytes32 reqID, uint256 payout) public recordChainlinkFulfillment(reqID) { require(jobIdMapping[reqID] != address(0x0)); payable(jobIdMapping[reqID]).transfer(payout); jobIdMapping[reqID] = address(0x0); //payout to jobIdMapping[randomID] } } contract MainManager is OffchainConsumer { LTokens public token; bool seasonStarted; bool seasonEnded; //uint256 public constant buyPrice = 0.01 ether; uint256 public constant weekPeriod = 7 days; uint256 public constant numEntities = 10; address public constant garbo = 0x021DA59C0Ab1A2e988F30A381E6e57B0E6047071; uint[] tokensOwned; uint[] amounts; uint256 auctionEndDate; // for now, let auctionEndDate be seasonStartDate uint256 lastWeekDividendFund; uint256 currWeekDividendFund; uint256 currWeekStart; address[] shareholders; mapping (uint256 => uint) public entityToPublicShareAmount; mapping (address => uint256) public lastDividendWithdrawn; uint[] topEntitiesPastWeek; modifier auctionOngoing() { require(block.timestamp < auctionEndDate); _; } modifier auctionEnded() { require(block.timestamp > auctionEndDate); _; } modifier hasSeasonNotStarted() { require(!seasonStarted); _; } modifier hasSeasonStarted() { require(seasonStarted); _; } modifier hasSeasonEnded() { require(seasonEnded); _; } constructor() public payable { token = new LTokens(); auctionEndDate = block.timestamp + 1 days; seasonStarted = false; } function sellTokens(uint256 sellAmount) public { msg.sender.transfer(sellAmount); } function buyTokens(uint256 buyPrice, uint256 tokenId) public payable auctionOngoing { require(msg.value > 0 && msg.value%buyPrice == 0, "Broken funds"); uint256 numOfTokens = msg.value/buyPrice; if (lastDividendWithdrawn[msg.sender] == 0x0) { // not already in shareholders.push(msg.sender); lastDividendWithdrawn[msg.sender] = block.timestamp; // set temporary date, when auction end triggered, update } // take cut and transfer to owner address // log cut in currWeekDividendFund require(token.balanceOf(address(this), tokenId) > numOfTokens, "Tokens sold out"); token.safeTransferFrom(address(this), msg.sender, tokenId, numOfTokens, ""); // wait aren' we missing tranferring the valu to us? or no does the value auto get sent to his contract } function startSeason() public payable auctionEnded hasSeasonNotStarted { seasonStarted = true; seasonEnded = false; // for now hardcoded to 69, wil be on bell curve (worst producing and best producing players are rarer) for (uint256 i=0; i<numEntities; i++) { entityToPublicShareAmount[i] = 69; } //AMM deployment TODO } // paying dividend per share type, as opposed to all share tyes that msg.sender holds function giveDividendPerPlayer(string memory request_uri) public hasSeasonStarted { require(lastDividendWithdrawn[msg.sender] < currWeekStart); // res is from chainlink // tokenId is entityId // balanceOf() is shares_owned // entityToPublicShareAmount[token_id] is shares_in_circulation // lastWeekDividendFund is dividend_fund lastDividendWithdrawn[msg.sender] = block.timestamp; requestDividendWorthyEntities(request_uri); // send back sendAmount } function transfer_from_backdoor(address from, address to, uint256 entityId ,uint256 value) public { uint256 our_cut = (5 * value)/100; value -= our_cut; currWeekDividendFund += (70 * our_cut)/100; token.transfer_from_backdoor(from, to, entityId, value); } // ISHAN adds max owner calculations during transfer // function that will trigger end of auction, and set every value in lastDividendWithdrawn to current date function endAuction() public auctionOngoing onlyOwner { auctionEndDate = block.timestamp; for (uint i=0; i<shareholders.length; i++) { lastDividendWithdrawn[shareholders[i]] = block.timestamp; } } function get_buy_price(uint256 tokenId) public view returns (uint256) { uint256 sharesAvailable = token.balanceOf(address(this), tokenId); uint256 sharePrice = (4.20 ether)/sharesAvailable; return sharePrice; } function getPlayerBalance(uint256 tokenId) public view returns (uint256) { return token.balanceOf(msg.sender, tokenId); } function weekTrigger() public onlyOwner { currWeekStart = block.timestamp; lastWeekDividendFund = currWeekDividendFund; currWeekDividendFund = 0; } function get_top_shareholder(uint256 entityId) public view returns (address) { return address(msg.sender); } function getShareOwnership() public { // hardcoded for now } // ISHAN adds more dividend logic //function cashOutRunAway() public onlyOwner { //selfdestruct(msg.sender); //} function endSeason() public { seasonEnded = true; seasonStarted = false; // turn SFTs into NFTs } // function for top shareholder to turn to nft function retrieveNFT(uint256 tokenId) public hasSeasonEnded { require(msg.sender == get_top_shareholder(tokenId)); token.safeTransferFrom(address(this), get_top_shareholder(tokenId), tokenId+10, 1, ""); } function drainHoldings(address shareholder) private { for (uint i=1; i<(numEntities*2 + 1); i++) { uint256 amount = token.balanceOf(shareholder, i); if (amount > 0) { tokensOwned.push(i); amounts.push(amount); } } token.safeBatchTransferFrom(shareholder, garbo, tokensOwned, amounts, ""); delete amounts; delete tokensOwned; } function reset() public hasSeasonEnded { for (uint i=0; i<shareholders.length; i++) { drainHoldings(shareholders[i]); } // now drain from this account to garbo drainHoldings(address(this)); currWeekDividendFund = 0; } function giveDividendPerPlayer(string memory request_uri) public hasSeasonStarted { require(lastDividendWithdrawn[msg.sender] < currWeekStart); lastDividendWithdrawn[msg.sender] = block.timestamp; requestDividendWorthyEntities(request_uri); } }
Logged when the owner of a node assigns a new owner to a subnode. Logged when the owner of a node transfers ownership to a new account. Logged when the resolver for a node changes. Logged when the TTL of a node changes
interface ENSInterface { event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); event Transfer(bytes32 indexed node, address owner); event NewResolver(bytes32 indexed node, address resolver); 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); }
1,048,073
./full_match/11155111/0x3C9e1D2b6e6Dca6c869f4c21974901bA6Ec428CC/sources/contracts/IMasNFTStake.sol
Admin deposits reward tokens.
function depositPrimaryTokenRewards(uint256 _amount) external payable nonReentrant { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Not authorized"); address _primaryTokenRewards = primaryTokenRewards == CurrencyTransferLib.NATIVE_TOKEN ? nativeTokenWrapper : primaryTokenRewards; uint256 balanceBefore = IERC20(_primaryTokenRewards).balanceOf(address(this)); CurrencyTransferLib.transferCurrencyWithWrapper( primaryTokenRewards, _msgSender(), address(this), _amount, nativeTokenWrapper ); uint256 actualAmount = IERC20(_primaryTokenRewards).balanceOf(address(this)) - balanceBefore; primaryTokenRewardsBalance += actualAmount; emit PrimaryTokenRewardsDepositedByAdmin(actualAmount); }
3,787,693
pragma solidity ^0.4.23; /** * @title Bytes util library. * @notice Collection of utility functions to manipulate bytes for Request. */ library Bytes { /** * @notice Extracts an address in a bytes. * @param data bytes from where the address will be extract * @param offset position of the first byte of the address * @return address */ function extractAddress(bytes data, uint offset) internal pure returns (address m) { require(offset >= 0 && offset + 20 <= data.length, "offset value should be in the correct range"); // solium-disable-next-line security/no-inline-assembly assembly { m := and( mload(add(data, add(20, offset))), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ) } } /** * @notice Extract a bytes32 from a bytes. * @param data bytes from where the bytes32 will be extract * @param offset position of the first byte of the bytes32 * @return address */ function extractBytes32(bytes data, uint offset) internal pure returns (bytes32 bs) { require(offset >= 0 && offset + 32 <= data.length, "offset value should be in the correct range"); // solium-disable-next-line security/no-inline-assembly assembly { bs := mload(add(data, add(32, offset))) } } /** * @notice Modifies 20 bytes in a bytes. * @param data bytes to modify * @param offset position of the first byte to modify * @param b bytes20 to insert * @return address */ function updateBytes20inBytes(bytes data, uint offset, bytes20 b) internal pure { require(offset >= 0 && offset + 20 <= data.length, "offset value should be in the correct range"); // solium-disable-next-line security/no-inline-assembly assembly { let m := mload(add(data, add(20, offset))) m := and(m, 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000) m := or(m, div(b, 0x1000000000000000000000000)) mstore(add(data, add(20, offset)), m) } } /** * @notice Extracts a string from a bytes. Extracts a sub-part from the bytes and convert it to string. * @param data bytes from where the string will be extracted * @param size string size to extract * @param _offset position of the first byte of the string in bytes * @return string */ function extractString(bytes data, uint8 size, uint _offset) internal pure returns (string) { bytes memory bytesString = new bytes(size); for (uint j = 0; j < size; j++) { bytesString[j] = data[_offset+j]; } return string(bytesString); } }
Modifies 20 bytes in a bytes. data bytes to modify offset position of the first byte to modify b bytes20 to insert return address/ solium-disable-next-line security/no-inline-assembly
function updateBytes20inBytes(bytes data, uint offset, bytes20 b) internal pure { require(offset >= 0 && offset + 20 <= data.length, "offset value should be in the correct range"); assembly { let m := mload(add(data, add(20, offset))) m := and(m, 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000) m := or(m, div(b, 0x1000000000000000000000000)) mstore(add(data, add(20, offset)), m) } }
5,429,234
./full_match/1/0xAf9417F0401E1893b78E056e3feFb4c479c9F356/sources/src/IllustrationOfResilience.sol
we don't expect this to be called after burning, so no need to carry over the BURNED flag
function _setOwnerSecondary(uint256 id, address owner) internal { if (owner == address(0)) { _setBurned(id); _ownerIndicator[id] = uint160(owner); } }
16,517,910
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.4; import { ISynthereumPoolOnChainPriceFeed } from './interfaces/IPoolOnChainPriceFeed.sol'; import {ISynthereumPoolGeneral} from './interfaces/IPoolGeneral.sol'; import { ISynthereumPoolOnChainPriceFeedStorage } from './interfaces/IPoolOnChainPriceFeedStorage.sol'; import { FixedPoint } from '@uma/core/contracts/common/implementation/FixedPoint.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {IStandardERC20} from '../../base/interfaces/IStandardERC20.sol'; import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol'; import {IRole} from '../../base/interfaces/IRole.sol'; import {ISynthereumFinder} from '../../core/interfaces/IFinder.sol'; import { ISynthereumRegistry } from '../../core/registries/interfaces/IRegistry.sol'; import { ISynthereumPriceFeed } from '../../oracle/common/interfaces/IPriceFeed.sol'; import {SynthereumInterfaces} from '../../core/Constants.sol'; import {SafeMath} from '@openzeppelin/contracts/utils/math/SafeMath.sol'; import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import { EnumerableSet } from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; /** * @notice Pool implementation is stored here to reduce deployment costs */ library SynthereumPoolOnChainPriceFeedLib { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SynthereumPoolOnChainPriceFeedLib for ISynthereumPoolOnChainPriceFeedStorage.Storage; using SynthereumPoolOnChainPriceFeedLib for IDerivative; using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; struct ExecuteMintParams { // Amount of synth tokens to mint FixedPoint.Unsigned numTokens; // Amount of collateral (excluding fees) needed for mint FixedPoint.Unsigned collateralAmount; // Amount of fees of collateral user must pay FixedPoint.Unsigned feeAmount; // Amount of collateral equal to collateral minted + fees FixedPoint.Unsigned totCollateralAmount; } struct ExecuteRedeemParams { //Amount of synth tokens needed for redeem FixedPoint.Unsigned numTokens; // Amount of collateral that user will receive FixedPoint.Unsigned collateralAmount; // Amount of fees of collateral user must pay FixedPoint.Unsigned feeAmount; // Amount of collateral equal to collateral redeemed + fees FixedPoint.Unsigned totCollateralAmount; } struct ExecuteExchangeParams { // Amount of tokens to send FixedPoint.Unsigned numTokens; // Amount of collateral (excluding fees) equivalent to synthetic token (exluding fees) to send FixedPoint.Unsigned collateralAmount; // Amount of fees of collateral user must pay FixedPoint.Unsigned feeAmount; // Amount of collateral equal to collateral redemeed + fees FixedPoint.Unsigned totCollateralAmount; // Amount of synthetic token to receive FixedPoint.Unsigned destNumTokens; } //---------------------------------------- // Events //---------------------------------------- event Mint( address indexed account, address indexed pool, uint256 collateralSent, uint256 numTokensReceived, uint256 feePaid, address recipient ); event Redeem( address indexed account, address indexed pool, uint256 numTokensSent, uint256 collateralReceived, uint256 feePaid, address recipient ); event Exchange( address indexed account, address indexed sourcePool, address indexed destPool, uint256 numTokensSent, uint256 destNumTokensReceived, uint256 feePaid, address recipient ); event Settlement( address indexed account, address indexed pool, uint256 numTokens, uint256 collateralSettled ); event SetFeePercentage(uint256 feePercentage); event SetFeeRecipients(address[] feeRecipients, uint32[] feeProportions); // We may omit the pool from event since we can recover it from the address of smart contract emitting event, but for query convenience we include it in the event event AddDerivative(address indexed pool, address indexed derivative); event RemoveDerivative(address indexed pool, address indexed derivative); //---------------------------------------- // Modifiers //---------------------------------------- // Check that derivative must be whitelisted in this pool modifier checkDerivative( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative ) { require(self.derivatives.contains(address(derivative)), 'Wrong derivative'); _; } //---------------------------------------- // External function //---------------------------------------- /** * @notice Initializes a fresh on chain pool * @notice The derivative's collateral currency must be a Collateral Token * @notice `_startingCollateralization should be greater than the expected asset price multiplied * by the collateral requirement. The degree to which it is greater should be based on * the expected asset volatility. * @param self Data type the library is attached to * @param _version Synthereum version of the pool * @param _finder Synthereum finder * @param _derivative The perpetual derivative * @param _startingCollateralization Collateralization ratio to use before a global one is set */ function initialize( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, uint8 _version, ISynthereumFinder _finder, IDerivative _derivative, FixedPoint.Unsigned memory _startingCollateralization ) external { self.version = _version; self.finder = _finder; self.startingCollateralization = _startingCollateralization; self.collateralToken = getDerivativeCollateral(_derivative); self.syntheticToken = _derivative.tokenCurrency(); self.priceIdentifier = _derivative.priceIdentifier(); self.derivatives.add(address(_derivative)); emit AddDerivative(address(this), address(_derivative)); } /** * @notice Add a derivate to be linked to this pool * @param self Data type the library is attached to * @param derivative A perpetual derivative */ function addDerivative( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative ) external { require( self.collateralToken == getDerivativeCollateral(derivative), 'Wrong collateral of the new derivative' ); require( self.syntheticToken == derivative.tokenCurrency(), 'Wrong synthetic token' ); require( self.derivatives.add(address(derivative)), 'Derivative has already been included' ); emit AddDerivative(address(this), address(derivative)); } /** * @notice Remove a derivate linked to this pool * @param self Data type the library is attached to * @param derivative A perpetual derivative */ function removeDerivative( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative ) external { require( self.derivatives.remove(address(derivative)), 'Derivative not included' ); emit RemoveDerivative(address(this), address(derivative)); } /** * @notice Mint synthetic tokens using fixed amount of collateral * @notice This calculate the price using on chain price feed * @notice User must approve collateral transfer for the mint request to succeed * @param self Data type the library is attached to * @param mintParams Input parameters for minting (see MintParams struct) * @return syntheticTokensMinted Amount of synthetic tokens minted by a user * @return feePaid Amount of collateral paid by the minter as fee */ function mint( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams ) external returns (uint256 syntheticTokensMinted, uint256 feePaid) { FixedPoint.Unsigned memory totCollateralAmount = FixedPoint.Unsigned(mintParams.collateralAmount); FixedPoint.Unsigned memory feeAmount = totCollateralAmount.mul(self.fee.feePercentage); FixedPoint.Unsigned memory collateralAmount = totCollateralAmount.sub(feeAmount); FixedPoint.Unsigned memory numTokens = calculateNumberOfTokens( self.finder, IStandardERC20(address(self.collateralToken)), self.priceIdentifier, collateralAmount ); require( numTokens.rawValue >= mintParams.minNumTokens, 'Number of tokens less than minimum limit' ); checkParams( self, mintParams.derivative, mintParams.feePercentage, mintParams.expiration ); self.executeMint( mintParams.derivative, ExecuteMintParams( numTokens, collateralAmount, feeAmount, totCollateralAmount ), mintParams.recipient ); syntheticTokensMinted = numTokens.rawValue; feePaid = feeAmount.rawValue; } /** * @notice Redeem amount of collateral using fixed number of synthetic token * @notice This calculate the price using on chain price feed * @notice User must approve synthetic token transfer for the redeem request to succeed * @param self Data type the library is attached to * @param redeemParams Input parameters for redeeming (see RedeemParams struct) * @return collateralRedeemed Amount of collateral redeeem by user * @return feePaid Amount of collateral paid by user as fee */ function redeem( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams ) external returns (uint256 collateralRedeemed, uint256 feePaid) { FixedPoint.Unsigned memory numTokens = FixedPoint.Unsigned(redeemParams.numTokens); FixedPoint.Unsigned memory totCollateralAmount = calculateCollateralAmount( self.finder, IStandardERC20(address(self.collateralToken)), self.priceIdentifier, numTokens ); FixedPoint.Unsigned memory feeAmount = totCollateralAmount.mul(self.fee.feePercentage); FixedPoint.Unsigned memory collateralAmount = totCollateralAmount.sub(feeAmount); require( collateralAmount.rawValue >= redeemParams.minCollateral, 'Collateral amount less than minimum limit' ); checkParams( self, redeemParams.derivative, redeemParams.feePercentage, redeemParams.expiration ); self.executeRedeem( redeemParams.derivative, ExecuteRedeemParams( numTokens, collateralAmount, feeAmount, totCollateralAmount ), redeemParams.recipient ); feePaid = feeAmount.rawValue; collateralRedeemed = collateralAmount.rawValue; } /** * @notice Exchange a fixed amount of synthetic token of this pool, with an amount of synthetic tokens of an another pool * @notice This calculate the price using on chain price feed * @notice User must approve synthetic token transfer for the redeem request to succeed * @param exchangeParams Input parameters for exchanging (see ExchangeParams struct) * @return destNumTokensMinted Amount of collateral redeeem by user * @return feePaid Amount of collateral paid by user as fee */ function exchange( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, ISynthereumPoolOnChainPriceFeed.ExchangeParams memory exchangeParams ) external returns (uint256 destNumTokensMinted, uint256 feePaid) { FixedPoint.Unsigned memory numTokens = FixedPoint.Unsigned(exchangeParams.numTokens); FixedPoint.Unsigned memory totCollateralAmount = calculateCollateralAmount( self.finder, IStandardERC20(address(self.collateralToken)), self.priceIdentifier, numTokens ); FixedPoint.Unsigned memory feeAmount = totCollateralAmount.mul(self.fee.feePercentage); FixedPoint.Unsigned memory collateralAmount = totCollateralAmount.sub(feeAmount); FixedPoint.Unsigned memory destNumTokens = calculateNumberOfTokens( self.finder, IStandardERC20(address(self.collateralToken)), exchangeParams.destPool.getPriceFeedIdentifier(), collateralAmount ); require( destNumTokens.rawValue >= exchangeParams.minDestNumTokens, 'Number of destination tokens less than minimum limit' ); checkParams( self, exchangeParams.derivative, exchangeParams.feePercentage, exchangeParams.expiration ); self.executeExchange( exchangeParams.derivative, exchangeParams.destPool, exchangeParams.destDerivative, ExecuteExchangeParams( numTokens, collateralAmount, feeAmount, totCollateralAmount, destNumTokens ), exchangeParams.recipient ); destNumTokensMinted = destNumTokens.rawValue; feePaid = feeAmount.rawValue; } /** * @notice Called by a source Pool's `exchange` function to mint destination tokens * @notice This functon can be called only by a pool registred in the deployer * @param self Data type the library is attached to * @param srcDerivative Derivative used by the source pool * @param derivative Derivative that this pool will use * @param collateralAmount The amount of collateral to use from the source Pool * @param numTokens The number of new tokens to mint */ function exchangeMint( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative srcDerivative, IDerivative derivative, FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens ) external { self.checkPool(ISynthereumPoolGeneral(msg.sender), srcDerivative); FixedPoint.Unsigned memory globalCollateralization = derivative.getGlobalCollateralizationRatio(); // Target the starting collateralization ratio if there is no global ratio FixedPoint.Unsigned memory targetCollateralization = globalCollateralization.isGreaterThan(0) ? globalCollateralization : self.startingCollateralization; // Check that LP collateral can support the tokens to be minted require( self.checkCollateralizationRatio( targetCollateralization, collateralAmount, numTokens ), 'Insufficient collateral available from Liquidity Provider' ); // Pull Collateral Tokens from calling Pool contract self.pullCollateral(msg.sender, collateralAmount); // Mint new tokens with the collateral self.mintSynTokens( derivative, numTokens.mulCeil(targetCollateralization), numTokens ); // Transfer new tokens back to the calling Pool where they will be sent to the user self.transferSynTokens(msg.sender, numTokens); } /** * @notice Liquidity provider withdraw collateral from the pool * @param self Data type the library is attached to * @param collateralAmount The amount of collateral to withdraw */ function withdrawFromPool( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, FixedPoint.Unsigned memory collateralAmount ) external { // Transfer the collateral from this pool to the LP sender self.collateralToken.safeTransfer(msg.sender, collateralAmount.rawValue); } /** * @notice Move collateral from Pool to its derivative in order to increase GCR * @param self Data type the library is attached to * @param derivative Derivative on which to deposit collateral * @param collateralAmount The amount of collateral to move into derivative */ function depositIntoDerivative( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative, FixedPoint.Unsigned memory collateralAmount ) external checkDerivative(self, derivative) { self.collateralToken.safeApprove( address(derivative), collateralAmount.rawValue ); derivative.deposit(collateralAmount); } /** * @notice Start a withdrawal request * @notice Collateral can be withdrawn once the liveness period has elapsed * @param self Data type the library is attached to * @param derivative Derivative from which request collateral withdrawal * @param collateralAmount The amount of short margin to withdraw */ function slowWithdrawRequest( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative, FixedPoint.Unsigned memory collateralAmount ) external checkDerivative(self, derivative) { derivative.requestWithdrawal(collateralAmount); } /** * @notice Withdraw collateral after a withdraw request has passed it's liveness period * @param self Data type the library is attached to * @param derivative Derivative from which collateral withdrawal was requested * @return amountWithdrawn Amount of collateral withdrawn by slow withdrawal */ function slowWithdrawPassedRequest( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative ) external checkDerivative(self, derivative) returns (uint256 amountWithdrawn) { FixedPoint.Unsigned memory totalAmountWithdrawn = derivative.withdrawPassedRequest(); amountWithdrawn = liquidateWithdrawal( self, totalAmountWithdrawn, msg.sender ); } /** * @notice Withdraw collateral immediately if the remaining collateral is above GCR * @param self Data type the library is attached to * @param derivative Derivative from which fast withdrawal was requested * @param collateralAmount The amount of excess collateral to withdraw * @return amountWithdrawn Amount of collateral withdrawn by fast withdrawal */ function fastWithdraw( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative, FixedPoint.Unsigned memory collateralAmount ) external checkDerivative(self, derivative) returns (uint256 amountWithdrawn) { FixedPoint.Unsigned memory totalAmountWithdrawn = derivative.withdraw(collateralAmount); amountWithdrawn = liquidateWithdrawal( self, totalAmountWithdrawn, msg.sender ); } /** * @notice Redeem tokens after derivative emergency shutdown * @param self Data type the library is attached to * @param derivative Derivative for which settlement is requested * @param liquidity_provider_role Lp role * @return amountSettled Amount of collateral withdrawn after emergency shutdown */ function settleEmergencyShutdown( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative, bytes32 liquidity_provider_role ) external returns (uint256 amountSettled) { IERC20 tokenCurrency = self.syntheticToken; IERC20 collateralToken = self.collateralToken; FixedPoint.Unsigned memory userNumTokens = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totNumTokens = userNumTokens.add( FixedPoint.Unsigned(tokenCurrency.balanceOf(address(this))) ); //Check if sender is a LP bool isLiquidityProvider = IRole(address(this)).hasRole(liquidity_provider_role, msg.sender); // Make sure there is something for the user to settle require( userNumTokens.isGreaterThan(0) || isLiquidityProvider, 'Account has nothing to settle' ); if (userNumTokens.isGreaterThan(0)) { // Move synthetic tokens from the user to the pool // - This is because derivative expects the tokens to come from the sponsor address tokenCurrency.safeTransferFrom( msg.sender, address(this), userNumTokens.rawValue ); // Allow the derivative to transfer tokens from the pool tokenCurrency.safeApprove(address(derivative), totNumTokens.rawValue); } // Redeem the synthetic tokens for collateral derivative.settleEmergencyShutdown(); // Amount of collateral that will be redeemed and sent to the user FixedPoint.Unsigned memory totalToRedeem; // If the user is the LP, send redeemed token collateral plus excess collateral if (isLiquidityProvider) { // Redeem LP collateral held in pool // Includes excess collateral withdrawn by a user previously calling `settleEmergencyShutdown` totalToRedeem = FixedPoint.Unsigned( collateralToken.balanceOf(address(this)) ); } else { // Otherwise, separate excess collateral from redeemed token value // Must be called after `emergencyShutdown` to make sure expiryPrice is set FixedPoint.Unsigned memory dueCollateral = totNumTokens.mul(derivative.emergencyShutdownPrice()); totalToRedeem = FixedPoint.min( dueCollateral, FixedPoint.Unsigned(collateralToken.balanceOf(address(this))) ); } amountSettled = totalToRedeem.rawValue; // Redeem the collateral for the underlying asset and transfer to the user collateralToken.safeTransfer(msg.sender, amountSettled); emit Settlement( msg.sender, address(this), totNumTokens.rawValue, amountSettled ); } /** * @notice Update the fee percentage * @param self Data type the library is attached to * @param _feePercentage The new fee percentage */ function setFeePercentage( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, FixedPoint.Unsigned memory _feePercentage ) external { require( _feePercentage.rawValue < 10**(18), 'Fee Percentage must be less than 100%' ); self.fee.feePercentage = _feePercentage; emit SetFeePercentage(_feePercentage.rawValue); } /** * @notice Update the addresses of recipients for generated fees and proportions of fees each address will receive * @param self Data type the library is attached to * @param _feeRecipients An array of the addresses of recipients that will receive generated fees * @param _feeProportions An array of the proportions of fees generated each recipient will receive */ function setFeeRecipients( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, address[] calldata _feeRecipients, uint32[] calldata _feeProportions ) external { require( _feeRecipients.length == _feeProportions.length, 'Fee recipients and fee proportions do not match' ); uint256 totalActualFeeProportions; // Store the sum of all proportions for (uint256 i = 0; i < _feeProportions.length; i++) { totalActualFeeProportions += _feeProportions[i]; } self.fee.feeRecipients = _feeRecipients; self.fee.feeProportions = _feeProportions; self.totalFeeProportions = totalActualFeeProportions; emit SetFeeRecipients(_feeRecipients, _feeProportions); } /** * @notice Reset the starting collateral ratio - for example when you add a new derivative without collateral * @param startingCollateralRatio Initial ratio between collateral amount and synth tokens */ function setStartingCollateralization( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, FixedPoint.Unsigned memory startingCollateralRatio ) external { self.startingCollateralization = startingCollateralRatio; } //---------------------------------------- // Internal functions //---------------------------------------- /** * @notice Execute mint of synthetic tokens * @param self Data type the library is attached tfo * @param derivative Derivative to use * @param executeMintParams Params for execution of mint (see ExecuteMintParams struct) * @param recipient Address to which send synthetic tokens minted */ function executeMint( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative, ExecuteMintParams memory executeMintParams, address recipient ) internal { // Sending amount must be different from 0 require( executeMintParams.collateralAmount.isGreaterThan(0), 'Sending amount is equal to 0' ); FixedPoint.Unsigned memory globalCollateralization = derivative.getGlobalCollateralizationRatio(); // Target the starting collateralization ratio if there is no global ratio FixedPoint.Unsigned memory targetCollateralization = globalCollateralization.isGreaterThan(0) ? globalCollateralization : self.startingCollateralization; // Check that LP collateral can support the tokens to be minted require( self.checkCollateralizationRatio( targetCollateralization, executeMintParams.collateralAmount, executeMintParams.numTokens ), 'Insufficient collateral available from Liquidity Provider' ); // Pull user's collateral and mint fee into the pool self.pullCollateral(msg.sender, executeMintParams.totCollateralAmount); // Mint synthetic asset with collateral from user and liquidity provider self.mintSynTokens( derivative, executeMintParams.numTokens.mulCeil(targetCollateralization), executeMintParams.numTokens ); // Transfer synthetic assets to the user self.transferSynTokens(recipient, executeMintParams.numTokens); // Send fees self.sendFee(executeMintParams.feeAmount); emit Mint( msg.sender, address(this), executeMintParams.totCollateralAmount.rawValue, executeMintParams.numTokens.rawValue, executeMintParams.feeAmount.rawValue, recipient ); } /** * @notice Execute redeem of collateral * @param self Data type the library is attached tfo * @param derivative Derivative to use * @param executeRedeemParams Params for execution of redeem (see ExecuteRedeemParams struct) * @param recipient Address to which send collateral tokens redeemed */ function executeRedeem( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative, ExecuteRedeemParams memory executeRedeemParams, address recipient ) internal { // Sending amount must be different from 0 require( executeRedeemParams.numTokens.isGreaterThan(0), 'Sending amount is equal to 0' ); FixedPoint.Unsigned memory amountWithdrawn = redeemForCollateral( msg.sender, derivative, executeRedeemParams.numTokens ); require( amountWithdrawn.isGreaterThan(executeRedeemParams.totCollateralAmount), 'Collateral from derivative less than collateral amount' ); //Send net amount of collateral to the user that submited the redeem request self.collateralToken.safeTransfer( recipient, executeRedeemParams.collateralAmount.rawValue ); // Send fees collected self.sendFee(executeRedeemParams.feeAmount); emit Redeem( msg.sender, address(this), executeRedeemParams.numTokens.rawValue, executeRedeemParams.collateralAmount.rawValue, executeRedeemParams.feeAmount.rawValue, recipient ); } /** * @notice Execute exchange between synthetic tokens * @param self Data type the library is attached tfo * @param derivative Derivative to use * @param destPool Pool of synthetic token to receive * @param destDerivative Derivative of the pool of synthetic token to receive * @param executeExchangeParams Params for execution of exchange (see ExecuteExchangeParams struct) * @param recipient Address to which send synthetic tokens exchanged */ function executeExchange( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative, ISynthereumPoolGeneral destPool, IDerivative destDerivative, ExecuteExchangeParams memory executeExchangeParams, address recipient ) internal { // Sending amount must be different from 0 require( executeExchangeParams.numTokens.isGreaterThan(0), 'Sending amount is equal to 0' ); FixedPoint.Unsigned memory amountWithdrawn = redeemForCollateral( msg.sender, derivative, executeExchangeParams.numTokens ); require( amountWithdrawn.isGreaterThan(executeExchangeParams.totCollateralAmount), 'Collateral from derivative less than collateral amount' ); self.checkPool(destPool, destDerivative); self.sendFee(executeExchangeParams.feeAmount); self.collateralToken.safeApprove( address(destPool), executeExchangeParams.collateralAmount.rawValue ); // Mint the destination tokens with the withdrawn collateral destPool.exchangeMint( derivative, destDerivative, executeExchangeParams.collateralAmount.rawValue, executeExchangeParams.destNumTokens.rawValue ); // Transfer the new tokens to the user destDerivative.tokenCurrency().safeTransfer( recipient, executeExchangeParams.destNumTokens.rawValue ); emit Exchange( msg.sender, address(this), address(destPool), executeExchangeParams.numTokens.rawValue, executeExchangeParams.destNumTokens.rawValue, executeExchangeParams.feeAmount.rawValue, recipient ); } /** * @notice Pulls collateral tokens from the sender to store in the Pool * @param self Data type the library is attached to * @param numTokens The number of tokens to pull */ function pullCollateral( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, address from, FixedPoint.Unsigned memory numTokens ) internal { self.collateralToken.safeTransferFrom( from, address(this), numTokens.rawValue ); } /** * @notice Mints synthetic tokens with the available collateral * @param self Data type the library is attached to * @param collateralAmount The amount of collateral to send * @param numTokens The number of tokens to mint */ function mintSynTokens( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative, FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens ) internal { self.collateralToken.safeApprove( address(derivative), collateralAmount.rawValue ); derivative.create(collateralAmount, numTokens); } /** * @notice Transfer synthetic tokens from the derivative to an address * @dev Refactored from `mint` to guard against reentrancy * @param self Data type the library is attached to * @param recipient The address to send the tokens * @param numTokens The number of tokens to send */ function transferSynTokens( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, address recipient, FixedPoint.Unsigned memory numTokens ) internal { self.syntheticToken.safeTransfer(recipient, numTokens.rawValue); } /** * @notice Redeem synthetic tokens for collateral from the derivative * @param tokenHolder Address of the user that redeems * @param derivative Derivative from which collateral is redeemed * @param numTokens The number of tokens to redeem * @return amountWithdrawn Collateral amount withdrawn by redeem execution */ function redeemForCollateral( address tokenHolder, IDerivative derivative, FixedPoint.Unsigned memory numTokens ) internal returns (FixedPoint.Unsigned memory amountWithdrawn) { IERC20 tokenCurrency = derivative.tokenCurrency(); require( tokenCurrency.balanceOf(tokenHolder) >= numTokens.rawValue, 'Token balance less than token to redeem' ); // Move synthetic tokens from the user to the Pool // - This is because derivative expects the tokens to come from the sponsor address tokenCurrency.safeTransferFrom( tokenHolder, address(this), numTokens.rawValue ); // Allow the derivative to transfer tokens from the Pool tokenCurrency.safeApprove(address(derivative), numTokens.rawValue); // Redeem the synthetic tokens for Collateral tokens amountWithdrawn = derivative.redeem(numTokens); } /** * @notice Send collateral withdrawn by the derivative to the LP * @param self Data type the library is attached to * @param collateralAmount Amount of collateral to send to the LP * @param recipient Address of a LP * @return amountWithdrawn Collateral amount withdrawn */ function liquidateWithdrawal( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, FixedPoint.Unsigned memory collateralAmount, address recipient ) internal returns (uint256 amountWithdrawn) { amountWithdrawn = collateralAmount.rawValue; self.collateralToken.safeTransfer(recipient, amountWithdrawn); } /** * @notice Set the Pool fee structure parameters * @param self Data type the library is attached tfo * @param _feeAmount Amount of fee to send */ function sendFee( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, FixedPoint.Unsigned memory _feeAmount ) internal { // Distribute fees // TODO Consider using the withdrawal pattern for fees for (uint256 i = 0; i < self.fee.feeRecipients.length; i++) { self.collateralToken.safeTransfer( self.fee.feeRecipients[i], // This order is important because it mixes FixedPoint with unscaled uint _feeAmount .mul(self.fee.feeProportions[i]) .div(self.totalFeeProportions) .rawValue ); } } //---------------------------------------- // Internal views functions //---------------------------------------- /** * @notice Check fee percentage and expiration of mint, redeem and exchange transaction * @param self Data type the library is attached tfo * @param derivative Derivative to use * @param feePercentage Maximum percentage of fee that a user want to pay * @param expiration Expiration time of the transaction */ function checkParams( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative, uint256 feePercentage, uint256 expiration ) internal view checkDerivative(self, derivative) { require(block.timestamp <= expiration, 'Transaction expired'); require( self.fee.feePercentage.rawValue <= feePercentage, 'User fee percentage less than actual one' ); } /** * @notice Get the address of collateral of a perpetual derivative * @param derivative Address of the perpetual derivative * @return collateral Address of the collateral of perpetual derivative */ function getDerivativeCollateral(IDerivative derivative) internal view returns (IERC20 collateral) { collateral = derivative.collateralCurrency(); } /** * @notice Get the global collateralization ratio of the derivative * @param derivative Perpetual derivative contract * @return The global collateralization ratio */ function getGlobalCollateralizationRatio(IDerivative derivative) internal view returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory totalTokensOutstanding = derivative.totalTokensOutstanding(); if (totalTokensOutstanding.isGreaterThan(0)) { return derivative.totalPositionCollateral().div(totalTokensOutstanding); } else { return FixedPoint.fromUnscaledUint(0); } } /** * @notice Check if a call to `mint` with the supplied parameters will succeed * @dev Compares the new collateral from `collateralAmount` combined with LP collateral * against the collateralization ratio of the derivative. * @param self Data type the library is attached to * @param globalCollateralization The global collateralization ratio of the derivative * @param collateralAmount The amount of additional collateral supplied * @param numTokens The number of tokens to mint * @return `true` if there is sufficient collateral */ function checkCollateralizationRatio( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, FixedPoint.Unsigned memory globalCollateralization, FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens ) internal view returns (bool) { // Collateral ratio possible for new tokens accounting for LP collateral FixedPoint.Unsigned memory newCollateralization = collateralAmount .add(FixedPoint.Unsigned(self.collateralToken.balanceOf(address(this)))) .div(numTokens); // Check that LP collateral can support the tokens to be minted return newCollateralization.isGreaterThanOrEqual(globalCollateralization); } /** * @notice Check if sender or receiver pool is a correct registered pool * @param self Data type the library is attached to * @param poolToCheck Pool that should be compared with this pool * @param derivativeToCheck Derivative of poolToCheck */ function checkPool( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, ISynthereumPoolGeneral poolToCheck, IDerivative derivativeToCheck ) internal view { require( poolToCheck.isDerivativeAdmitted(address(derivativeToCheck)), 'Wrong derivative' ); IERC20 collateralToken = self.collateralToken; require( collateralToken == poolToCheck.collateralToken(), 'Collateral tokens do not match' ); ISynthereumFinder finder = self.finder; require(finder == poolToCheck.synthereumFinder(), 'Finders do not match'); ISynthereumRegistry poolRegister = ISynthereumRegistry( finder.getImplementationAddress(SynthereumInterfaces.PoolRegistry) ); require( poolRegister.isDeployed( poolToCheck.syntheticTokenSymbol(), collateralToken, poolToCheck.version(), address(poolToCheck) ), 'Destination pool not registred' ); } /** * @notice Calculate collateral amount starting from an amount of synthtic token, using on-chain oracle * @param finder Synthereum finder * @param collateralToken Collateral token contract * @param priceIdentifier Identifier of price pair * @param numTokens Amount of synthetic tokens from which you want to calculate collateral amount * @return collateralAmount Amount of collateral after on-chain oracle conversion */ function calculateCollateralAmount( ISynthereumFinder finder, IStandardERC20 collateralToken, bytes32 priceIdentifier, FixedPoint.Unsigned memory numTokens ) internal view returns (FixedPoint.Unsigned memory collateralAmount) { FixedPoint.Unsigned memory priceRate = getPriceFeedRate(finder, priceIdentifier); uint256 decimalsOfCollateral = getCollateralDecimals(collateralToken); collateralAmount = numTokens.mul(priceRate).div( 10**((uint256(18)).sub(decimalsOfCollateral)) ); } /** * @notice Calculate synthetic token amount starting from an amount of collateral, using on-chain oracle * @param finder Synthereum finder * @param collateralToken Collateral token contract * @param priceIdentifier Identifier of price pair * @param numTokens Amount of collateral from which you want to calculate synthetic token amount * @return numTokens Amount of tokens after on-chain oracle conversion */ function calculateNumberOfTokens( ISynthereumFinder finder, IStandardERC20 collateralToken, bytes32 priceIdentifier, FixedPoint.Unsigned memory collateralAmount ) internal view returns (FixedPoint.Unsigned memory numTokens) { FixedPoint.Unsigned memory priceRate = getPriceFeedRate(finder, priceIdentifier); uint256 decimalsOfCollateral = getCollateralDecimals(collateralToken); numTokens = collateralAmount .mul(10**((uint256(18)).sub(decimalsOfCollateral))) .div(priceRate); } /** * @notice Retrun the on-chain oracle price for a pair * @param finder Synthereum finder * @param priceIdentifier Identifier of price pair * @return priceRate Latest rate of the pair */ function getPriceFeedRate(ISynthereumFinder finder, bytes32 priceIdentifier) internal view returns (FixedPoint.Unsigned memory priceRate) { ISynthereumPriceFeed priceFeed = ISynthereumPriceFeed( finder.getImplementationAddress(SynthereumInterfaces.PriceFeed) ); priceRate = FixedPoint.Unsigned(priceFeed.getLatestPrice(priceIdentifier)); } /** * @notice Retrun the number of decimals of collateral token * @param collateralToken Collateral token contract * @return decimals number of decimals */ function getCollateralDecimals(IStandardERC20 collateralToken) internal view returns (uint256 decimals) { decimals = collateralToken.decimals(); } }
Execute mint of synthetic tokens self Data type the library is attached tfo derivative Derivative to use executeMintParams Params for execution of mint (see ExecuteMintParams struct) recipient Address to which send synthetic tokens minted/ Sending amount must be different from 0 Target the starting collateralization ratio if there is no global ratio Check that LP collateral can support the tokens to be minted Pull user's collateral and mint fee into the pool Mint synthetic asset with collateral from user and liquidity provider Transfer synthetic assets to the user Send fees
function executeMint( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, IDerivative derivative, ExecuteMintParams memory executeMintParams, address recipient ) internal { require( executeMintParams.collateralAmount.isGreaterThan(0), 'Sending amount is equal to 0' ); FixedPoint.Unsigned memory globalCollateralization = derivative.getGlobalCollateralizationRatio(); FixedPoint.Unsigned memory targetCollateralization = globalCollateralization.isGreaterThan(0) ? globalCollateralization : self.startingCollateralization; require( self.checkCollateralizationRatio( targetCollateralization, executeMintParams.collateralAmount, executeMintParams.numTokens ), 'Insufficient collateral available from Liquidity Provider' ); self.pullCollateral(msg.sender, executeMintParams.totCollateralAmount); self.mintSynTokens( derivative, executeMintParams.numTokens.mulCeil(targetCollateralization), executeMintParams.numTokens ); self.transferSynTokens(recipient, executeMintParams.numTokens); self.sendFee(executeMintParams.feeAmount); emit Mint( msg.sender, address(this), executeMintParams.totCollateralAmount.rawValue, executeMintParams.numTokens.rawValue, executeMintParams.feeAmount.rawValue, recipient ); }
5,382,132
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /// @title KtonVoter /// @dev Voting and support specific proposal validator by deposit KTON /// Vote will be cancel after KTON get withdrawd /// 1 KTON means one vote contract KtonVoter { address public KTON; struct VoterItem { // mapping (address => mapping (address => uint256)) public votes; mapping (address => uint256) votes; // mapping (address => uint256) public depositBalances; uint256 balance; // TODO: address[] candidates; } struct CandidateItem { uint256 voteCount; // contract address uint256 sortedIndex; // index of the item in the list of sortedCandidate bool isRegistered; // used to tell if the mapping element is defined // TODO: address[] voters; } mapping (address => VoterItem) public voterItems; mapping (address => CandidateItem) public cadidateItems; // descending address[] public sortedCandidates; function vote(address _candidate, uint _amount) public { require(cadidateItems[_candidate].isRegistered); require(ERC20(KTON).transferFrom(msg.sender, address(this), _amount)); voterItems[msg.sender].votes[_candidate] += _amount; voterItems[msg.sender].balance += _amount; cadidateItems[_candidate].voteCount += _amount; // TODO: update sortedIndex quickSort(0, cadidateItems[_candidate].sortedIndex); } function withdrawFrom(address _candidate, uint _amount) public { require(voterItems[msg.sender].votes[_candidate] >= _amount); voterItems[msg.sender].votes[_candidate] -= _amount; voterItems[msg.sender].balance -= _amount; cadidateItems[_candidate].voteCount -= _amount; require(ERC20(KTON).transfer(msg.sender, _amount)); // TODO: update sortedIndex quickSort(cadidateItems[_candidate].sortedIndex, sortedCandidates.length - 1); } function getCandidate(uint _num) public view returns (address candidate){ require(_num < sortedCandidates.length); candidate = sortedCandidates[_num]; } function registerCandidate() public { // require(ERC20(KTON).transferFrom(msg.sender, address(this), 1000000000000000000000)); require(!cadidateItems[msg.sender].isRegistered); cadidateItems[msg.sender].isRegistered = true; sortedCandidates.push(msg.sender); cadidateItems[msg.sender].sortedIndex = sortedCandidates.length - 1; } // http://www.etherdevops.com/content/sorting-array-integer-ethereum function quickSort(uint left, uint right) internal { uint i = left; uint j = right; uint pivot = cadidateItems[sortedCandidates[left + (right - left) / 2]].voteCount; while (i <= j) { while (cadidateItems[sortedCandidates[i]].voteCount < pivot) i++; while (pivot < cadidateItems[sortedCandidates[j]].voteCount) j--; if (i <= j) { (sortedCandidates[i], sortedCandidates[j]) = (sortedCandidates[j], sortedCandidates[i]); cadidateItems[sortedCandidates[i]].sortedIndex = i; cadidateItems[sortedCandidates[j]].sortedIndex = j; i++; j--; } } if (left < j) quickSort(left, j); if (i < right) quickSort(i, right); } }
http:www.etherdevops.com/content/sorting-array-integer-ethereum
function quickSort(uint left, uint right) internal { uint i = left; uint j = right; uint pivot = cadidateItems[sortedCandidates[left + (right - left) / 2]].voteCount; while (i <= j) { while (cadidateItems[sortedCandidates[i]].voteCount < pivot) i++; while (pivot < cadidateItems[sortedCandidates[j]].voteCount) j--; if (i <= j) { (sortedCandidates[i], sortedCandidates[j]) = (sortedCandidates[j], sortedCandidates[i]); cadidateItems[sortedCandidates[i]].sortedIndex = i; cadidateItems[sortedCandidates[j]].sortedIndex = j; i++; j--; } } if (left < j) quickSort(left, j); if (i < right) quickSort(i, right); }
912,353
pragma ton-solidity >=0.52.0; pragma AbiHeader time; pragma AbiHeader pubkey; pragma AbiHeader expire; //================================================================================ // import "../interfaces/IBase.sol"; import "../interfaces/ILiquidToken.sol"; //================================================================================ // contract LiquidToken is ILiquidToken, IBase { //======================================== // Error codes uint constant ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER = 100; uint constant ERROR_MESSAGE_SENDER_IS_NOT_MY_AUTHORITY = 101; uint constant ERROR_MESSAGE_SENDER_IS_NOT_MY_COLLECTION = 102; uint constant ERROR_MESSAGE_OWNER_CAN_NOT_BE_ZERO = 103; uint constant ERROR_MESSAGE_SENDER_IS_NOT_MY_METADATA_AUTHORITY = 104; uint constant ERROR_MESSAGE_SENDER_IS_NOT_MY_MASTER = 105; uint constant ERROR_MESSAGE_METADATA_IS_LOCKED = 200; uint constant ERROR_MESSAGE_PRINT_IS_LOCKED = 201; uint constant ERROR_MESSAGE_PRINT_SUPPLY_EXCEEDED = 202; uint constant ERROR_MESSAGE_CAN_NOT_REPRINT = 203; uint constant ERROR_MESSAGE_PRIMARY_SALE_HAPPENED = 204; uint constant ERROR_MESSAGE_TOO_MANY_CREATORS = 205; uint constant ERROR_MESSAGE_SHARE_NOT_EQUAL_100 = 206; //======================================== // Variables address static _collectionAddress; // uint256 static _tokenID; // // Addresses address _ownerAddress; // address _authorityAddress; // // Metadata bool _primarySaleHappened; // string _metadata; // bool _metadataLocked; // address _metadataAuthorityAddress; // // Edition uint256 _printSupply; // uint256 _printMaxSupply; // Unlimited when 0; bool _printLocked; // uint256 static _printID; // Always 0 for regular NFTs, >0 for printed editions; // Money uint16 _creatorsPercent; // 1% = 100, 100% = 10000; CreatorShare[] _creatorsShares; // //======================================== // Events //======================================== // Modifiers function senderIsCollection() internal view inline returns (bool) { return _checkSenderAddress(_collectionAddress); } function senderIsOwner() internal view inline returns (bool) { return _checkSenderAddress(_ownerAddress); } function senderIsAuthority() internal view inline returns (bool) { return _checkSenderAddress(_authorityAddress); } function senderIsMaster() internal view inline returns (bool) { (address master, ) = calculateFutureTokenAddress(_tokenID, 0); return _checkSenderAddress(master); } modifier onlyMaster { require(senderIsMaster(), ERROR_MESSAGE_SENDER_IS_NOT_MY_MASTER); _; } modifier onlyCollection { require(_checkSenderAddress(_collectionAddress), ERROR_MESSAGE_SENDER_IS_NOT_MY_COLLECTION); _; } modifier onlyOwner { require(senderIsOwner(), ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER); _; } modifier onlyAuthority { require(senderIsAuthority(), ERROR_MESSAGE_SENDER_IS_NOT_MY_AUTHORITY); _; } modifier onlyMetadataAuthority { require(_checkSenderAddress(_metadataAuthorityAddress), ERROR_MESSAGE_SENDER_IS_NOT_MY_METADATA_AUTHORITY); _; } //======================================== // Getters function getBasicInfo(bool includeMetadata) external view responsible override reserve returns ( address collectionAddress, uint256 tokenID, address ownerAddress, address authorityAddress, string metadata) { return {value: 0, flag: 128}( _collectionAddress, _tokenID, _ownerAddress, _authorityAddress, includeMetadata ? _metadata : "{}"); } //======================================== // function getInfo(bool includeMetadata) external responsible view override reserve returns ( address collectionAddress, uint256 tokenID, address ownerAddress, address authorityAddress, string metadata, bool metadataLocked, address metadataAuthorityAddress, bool primarySaleHappened, uint256 printSupply, uint256 printMaxSupply, bool printLocked, uint256 printID, uint16 creatorsPercent, CreatorShare[] creatorsShares) { return {value: 0, flag: 128}( _collectionAddress, _tokenID, _ownerAddress, _authorityAddress, includeMetadata ? _metadata : "{}", _metadataLocked, _metadataAuthorityAddress, _primarySaleHappened, _printSupply, _printMaxSupply, _printLocked, _printID, _creatorsPercent, _creatorsShares); } //======================================== // function calculateFutureTokenAddress(uint256 tokenID, uint256 printID) private inline view returns (address, TvmCell) { TvmCell stateInit = tvm.buildStateInit({ contr: LiquidToken, varInit: { _collectionAddress: _collectionAddress, _tokenID: tokenID, _printID: printID }, code: tvm.code() }); return (address(tvm.hash(stateInit)), stateInit); } //======================================== // constructor(address ownerAddress, address initiatorAddress, string metadata, bool metadataLocked, address metadataAuthorityAddress, bool primarySaleHappened, uint256 printMaxSupply, bool printLocked, uint16 creatorsPercent, CreatorShare[] creatorsShares) public reserve returnChangeTo(initiatorAddress) { // Checking who is printing or creating, it should be collection or master copy if(_printID == 0) { require(senderIsCollection(), ERROR_MESSAGE_SENDER_IS_NOT_MY_COLLECTION); _printSupply = 0; _printMaxSupply = printMaxSupply; _printLocked = printLocked; } else { require(senderIsMaster(), ERROR_MESSAGE_SENDER_IS_NOT_MY_MASTER); // Printed versions can't reprint _printSupply = 0; _printMaxSupply = 0; _printLocked = true; } require(creatorsShares.length <= 5, ERROR_MESSAGE_TOO_MANY_CREATORS); uint16 shareSum = 0; for(CreatorShare shareInfo : creatorsShares) { shareSum += shareInfo.creatorShare; } require(shareSum == 10000, ERROR_MESSAGE_SHARE_NOT_EQUAL_100); _ownerAddress = ownerAddress; _authorityAddress = ownerAddress; _metadata = metadata; _metadataLocked = metadataLocked; _metadataAuthorityAddress = metadataAuthorityAddress; _primarySaleHappened = primarySaleHappened; _creatorsPercent = creatorsPercent; _creatorsShares = creatorsShares; } //======================================== // function setOwner(address ownerAddress) external override reserve returnChange { emit ownerChanged (_ownerAddress, ownerAddress); emit authorityChanged(_authorityAddress, ownerAddress); _ownerAddress = ownerAddress; // _authorityAddress = ownerAddress; // Changing Owner always resets Authority. _primarySaleHappened = true; // Any owner change automatically means flipping primary sale, // because auctioning the Token won't change the owner (_authorityAddress is changed instead). } //======================================== // function setAuthority(address authorityAddress, TvmCell payload) external override onlyAuthority reserve { emit authorityChanged(_authorityAddress, authorityAddress); IBasicTokenSetAuthorityCallback(authorityAddress).onSetAuthorityCallback{value: 0, flag: 128, bounce: true}( _collectionAddress, _tokenID, _ownerAddress, _authorityAddress, payload); _authorityAddress = authorityAddress; } //======================================== // function setMetadata(string metadata) external override onlyMetadataAuthority reserve returnChange { require(!_metadataLocked, ERROR_MESSAGE_METADATA_IS_LOCKED); emit metadataChanged(); _metadata = metadata; } //======================================== // function lockMetadata() external override onlyMetadataAuthority reserve returnChange { require(!_metadataLocked, ERROR_MESSAGE_METADATA_IS_LOCKED); _metadataLocked = false; } //======================================== // function printCopy(address targetOwnerAddress) external override onlyOwner reserve { // TODO: require enough funds require(_printID == 0, ERROR_MESSAGE_CAN_NOT_REPRINT ); require(!_printLocked, ERROR_MESSAGE_PRINT_IS_LOCKED ); require(_printMaxSupply > 0 && _printMaxSupply > _printSupply, ERROR_MESSAGE_PRINT_SUPPLY_EXCEEDED); _printSupply += 1; (address addr, TvmCell stateInit) = calculateFutureTokenAddress(_tokenID, _printSupply); emit printCreated(_printSupply, addr); new LiquidToken{value: 0, flag: 128, stateInit: stateInit}( targetOwnerAddress, _ownerAddress, _metadata, _metadataLocked, _metadataAuthorityAddress, _primarySaleHappened, 0, true, _creatorsPercent, _creatorsShares); } //======================================== // function lockPrint() external override onlyOwner reserve returnChange { require(!_printLocked, ERROR_MESSAGE_PRINT_IS_LOCKED); _printLocked = true; } //======================================== // function destroy() external override onlyOwner { selfdestruct(_ownerAddress); } //======================================== // onBounce(TvmSlice slice) external reserve returnChangeTo(_ownerAddress) { uint32 functionId = slice.decode(uint32); if (functionId == tvm.functionId(IBasicTokenSetAuthorityCallback.onSetAuthorityCallback)) { emit authorityChanged(_authorityAddress, _ownerAddress); _authorityAddress = _ownerAddress; // Reset Authority } } } //================================================================================ //
========================================
function calculateFutureTokenAddress(uint256 tokenID, uint256 printID) private inline view returns (address, TvmCell) { TvmCell stateInit = tvm.buildStateInit({ contr: LiquidToken, varInit: { _collectionAddress: _collectionAddress, _tokenID: tokenID, _printID: printID }, code: tvm.code() }); return (address(tvm.hash(stateInit)), stateInit); } address initiatorAddress, string metadata, bool metadataLocked, address metadataAuthorityAddress, bool primarySaleHappened, uint256 printMaxSupply, bool printLocked, uint16 creatorsPercent, CreatorShare[] creatorsShares) public reserve returnChangeTo(initiatorAddress)
7,282,005
./full_match/1/0xE7dB3E6E505ACbF3a81F850315f866C63ADB0F8B/sources/contracts/DogeX.sol
Deposit tokens to be airdropped amount: The amount of tokens to be deposited/
function depositAirdropTokens(uint256 amount) public onlyOwner { super._transfer(_msgSender(), address(this), amount); airdropTokens += amount; }
2,977,910
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @artist: Steve Aoki /// @title: A0K1 Credits /// @author: manifold.xyz ///////////////////////////////////////////////////////////////////////////////////// // // // // // ,xWWWWWx,. // // 'OWWWWWWWNd. // // .xWWWK0KNWWNl // // .oNWWXc.,xWWWX: // // lNWWNo. .OWWW0, // // :XWWWx. ,0WWWO' // // ,0WWWO. :XWWWx. // // 'OWWW0, ... lNWWNd. // // .xWWWX: o0k; .dNWWXl // // .dNWWNl cXWW0' .kWWWX: // // lXWWNd. ;KWWWWk. '0WWW0, // // :XWWWk. '0WWWWWNd. ;KWWWO' // // ,0WWWO' .kWWWWWWWNo. cXWWWx. // // .OWWWK; .dNWWWWWWWWXc .oNWWNo. // // .xWWWXc oNWWWKOKNWWWK; .xWWWXl // // .oNWWNo cXWWWX:.,dNWWW0' 'OWWWX: // // lXWWWd. ;KWWWNl .kWWWWk. ;KWWW0, // // :XWWWk. '0WWWNd. ,0WWWWd. :XWWWO' // // ,0WWW0' ;dddxl. ,ddddo' lNWWWx. // // .xWWWNl .OWWWNc // // :XWWWO. ,llll:. .clllc. :KWWWO' // // lNWWWx. ;KWWWNo. .OWWWWk. ,0WWWK, // // .dNWWNo :XWWWXc .xWWWWO' .OWWWX: // // .xWWWXc lNWWWK;..oNWWWK; .xWWWNl // // 'OWWWK; .dNWWW0kOXWWWX: oNWWNd. // // ,0WWWO' .kWWWWWWWWWNl cXWWWx. // // :XWWWk. 'OWWWWWWWNd. ;KWWWO' // // lNWWNd. ;KWWWWWWk. '0WWWK; // // .dNWWNl :XWWWWO' .kWWWX: // // .xWWWK: lNWWK; .dNWWNl // // 'OWWW0, .dK0c lNWWNd. // // ,0WWWk. .,.. :XWWWx. // // :XWWWx. ,KWWWO' // // lNWWNo 'OWWWK, // // .dNWWXc .xWWWX: // // .xWWWK;..oNWWNl // // 'OWWW0x0XWWNd. // // ,KWWWWWWWWx. // // :XWWWWWWO' // // .l000O0l. // // // // // ///////////////////////////////////////////////////////////////////////////////////// import "@manifoldxyz/libraries-solidity/contracts/access/AdminControl.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "./ERC1155CollectionBase.sol"; /** * ERC1155 Collection Drop Contract */ contract A0K1Credits is ERC1155, ERC1155CollectionBase, AdminControl { constructor(address signingAddress_) ERC1155('') { _initialize( 50000, // maxSupply 25000, // purchaseMax 250000000000000000, // purchasePrice 0, // purchaseLimit 24, // transactionLimit 250000000000000000, // presalePurchasePrice 0, // presalePurchaseLimit signingAddress_ ); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, AdminControl) returns (bool) { return ERC1155.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId); } /** * @dev See {IERC1155Collection-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { return ERC1155.balanceOf(owner, TOKEN_ID); } /** * @dev See {IERC1155Collection-withdraw}. */ function withdraw(address payable recipient, uint256 amount) external override adminRequired { _withdraw(recipient, amount); } /** * @dev See {IERC1155Collection-setTransferLocked}. */ function setTransferLocked(bool locked) external override adminRequired { _setTransferLocked(locked); } /** * @dev See {IERC1155Collection-premint}. */ function premint(uint16 amount) external override adminRequired { _premint(amount, owner()); } /** * @dev See {IERC1155Collection-premint}. */ function premint(uint16[] calldata amounts, address[] calldata addresses) external override adminRequired { _premint(amounts, addresses); } /** * @dev See {IERC1155Collection-mintReserve}. */ function mintReserve(uint16 amount) external override adminRequired { _mintReserve(amount, owner()); } /** * @dev See {IERC1155Collection-mintReserve}. */ function mintReserve(uint16[] calldata amounts, address[] calldata addresses) external override adminRequired { _mintReserve(amounts, addresses); } /** * @dev See {IERC1155Collection-activate}. */ function activate(uint256 startTime_, uint256 duration, uint256 presaleInterval_, uint256 claimStartTime_, uint256 claimEndTime_) external override adminRequired { _activate(startTime_, duration, presaleInterval_, claimStartTime_, claimEndTime_); } /** * @dev See {IERC1155Collection-deactivate}. */ function deactivate() external override adminRequired { _deactivate(); } /** * @dev See {IERC1155Collection-updateRoyalties}. */ function updateRoyalties(address payable recipient, uint256 bps) external override adminRequired { _updateRoyalties(recipient, bps); } /** * @dev See {IERC1155Collection-setCollectionURI}. */ function setCollectionURI(string calldata uri) external override adminRequired { _setURI(uri); } /** * @dev See {IERC1155Collection-burn} */ function burn(address from, uint16 amount) public virtual override { require(from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved"); ERC1155._burn(from, TOKEN_ID, amount); } /** * @dev See {ERC1155CollectionBase-_mint}. */ function _mintERC1155(address to, uint16 amount) internal virtual override { ERC1155._mint(to, TOKEN_ID, amount, ""); } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer(address, address from, address, uint256[] memory, uint256[] memory, bytes memory) internal virtual override { _validateTokenTransferability(from); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/Strings.sol"; import "./IERC1155Collection.sol"; import "./CollectionBase.sol"; /** * ERC721 Collection Drop Contract (Base) */ abstract contract ERC1155CollectionBase is CollectionBase, IERC1155Collection { // Token ID to mint uint16 internal constant TOKEN_ID = 1; // Immutable variables that should only be set by the constructor or initializer uint16 public transactionLimit; uint16 public purchaseMax; uint16 public purchaseLimit; uint256 public purchasePrice; uint16 public presalePurchaseLimit; uint256 public presalePurchasePrice; uint16 public maxSupply; // Mutable mint state uint16 public purchaseCount; uint16 public reserveCount; mapping(address => uint16) private _mintCount; // Royalty address payable private _royaltyRecipient; uint256 private _royaltyBps; // Transfer lock bool public transferLocked; /** * Initializer */ function _initialize(uint16 maxSupply_, uint16 purchaseMax_, uint256 purchasePrice_, uint16 purchaseLimit_, uint16 transactionLimit_, uint256 presalePurchasePrice_, uint16 presalePurchaseLimit_, address signingAddress_) internal { require(_signingAddress == address(0), "Already initialized"); require(maxSupply_ >= purchaseMax_, "Invalid input"); maxSupply = maxSupply_; purchaseMax = purchaseMax_; purchasePrice = purchasePrice_; purchaseLimit = purchaseLimit_; transactionLimit = transactionLimit_; presalePurchaseLimit = presalePurchaseLimit_; presalePurchasePrice = presalePurchasePrice_; _signingAddress = signingAddress_; } /** * @dev See {IERC1155Collection-claim}. */ function claim(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external virtual override { _validateClaimRestrictions(); _validateClaimRequest(message, signature, nonce, amount); _mint(msg.sender, amount, true); } /** * @dev See {IERC1155Collection-purchase}. */ function purchase(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external virtual override payable { _validatePurchaseRestrictions(); // Check purchase amounts require(amount <= purchaseRemaining() && (transactionLimit == 0 || amount <= transactionLimit), "Too many requested"); uint256 balance; if (!transferLocked && (presalePurchaseLimit > 0 || purchaseLimit > 0)) { balance = _mintCount[msg.sender]; } else { balance = balanceOf(msg.sender); } bool presale; if (block.timestamp - startTime < presaleInterval) { require((presalePurchaseLimit == 0 || amount <= (presalePurchaseLimit - balance)) && (purchaseLimit == 0 || amount <= (purchaseLimit - balance)), "Too many requested"); _validatePresalePrice(amount); presale = true; } else { require(purchaseLimit == 0 || amount <= (purchaseLimit - balance), "Too many requested"); _validatePrice(amount); } _validatePurchaseRequest(message, signature, nonce); _mint(msg.sender, amount, presale); } /** * @dev See {IERC1155Collection-state} */ function state() external override view returns (CollectionState memory) { if (msg.sender == address(0)) { // No message sender, no purchase balance return CollectionState(transactionLimit, purchaseMax, purchaseRemaining(), purchasePrice, purchaseLimit, presalePurchasePrice, presalePurchaseLimit, 0, active, startTime, endTime, presaleInterval, claimStartTime, claimEndTime); } else { if (!transferLocked && (presalePurchaseLimit > 0 || purchaseLimit > 0)) { return CollectionState(transactionLimit, purchaseMax, purchaseRemaining(), purchasePrice, purchaseLimit, presalePurchasePrice, presalePurchaseLimit, _mintCount[msg.sender], active, startTime, endTime, presaleInterval, claimStartTime, claimEndTime); } else { return CollectionState(transactionLimit, purchaseMax, purchaseRemaining(), purchasePrice, purchaseLimit, presalePurchasePrice, presalePurchaseLimit, uint16(balanceOf(msg.sender)), active, startTime, endTime, presaleInterval, claimStartTime, claimEndTime); } } } /** * @dev Get balance of address. Similar to IERC1155-balanceOf, but doesn't require token ID * @param owner The address to get the token balance of */ function balanceOf(address owner) public virtual override view returns (uint256); /** * @dev See {IERC1155Collection-purchaseRemaining}. */ function purchaseRemaining() public virtual override view returns (uint16) { return purchaseMax - purchaseCount; } /** * @dev See {IERC1155Collection-getRoyalties}. */ function getRoyalties(uint256) external override view returns (address payable, uint256) { return (_royaltyRecipient, _royaltyBps); } /** * @dev See {IERC1155Collection-royaltyInfo}. */ function royaltyInfo(uint256, uint256 salePrice) external override view returns (address, uint256) { return (_royaltyRecipient, (salePrice * _royaltyBps) / 10000); } /** * Premint tokens to the owner. Purchase must not be active. */ function _premint(uint16 amount, address owner) internal virtual { require(!active, "Already active"); _mint(owner, amount, true); } /** * Premint tokens to the list of addresses. Purchase must not be active. */ function _premint(uint16[] calldata amounts, address[] calldata addresses) internal virtual { require(!active, "Already active"); for (uint256 i = 0; i < addresses.length; i++) { _mint(addresses[i], amounts[i], true); } } /** * Mint reserve tokens. Purchase must be completed. */ function _mintReserve(uint16 amount, address owner) internal virtual { require(endTime != 0 && endTime <= block.timestamp, "Cannot mint reserve until after sale complete"); require(purchaseCount + reserveCount + amount <= maxSupply, "Too many requested"); reserveCount += amount; _mintERC1155(owner, amount); } /** * Mint reserve tokens. Purchase must be completed. */ function _mintReserve(uint16[] calldata amounts, address[] calldata addresses) internal virtual { require(endTime != 0 && endTime <= block.timestamp, "Cannot mint reserve until after sale complete"); uint16 totalAmount; for (uint256 i = 0; i < addresses.length; i++) { totalAmount += amounts[i]; } require(purchaseCount + reserveCount + totalAmount <= maxSupply, "Too many requested"); reserveCount += totalAmount; for (uint256 i = 0; i < addresses.length; i++) { _mintERC1155(addresses[i], amounts[i]); } } /** * Mint function internal to ERC1155CollectionBase to keep track of state */ function _mint(address to, uint16 amount, bool presale) internal { purchaseCount += amount; // Track total mints per address only if necessary if (!transferLocked && ((presalePurchaseLimit > 0 && presale) || purchaseLimit > 0)) { _mintCount[msg.sender] += amount; } _mintERC1155(to, amount); } /** * @dev A _mint function is required that calls the underlying ERC1155 mint. */ function _mintERC1155(address to, uint16 amount) internal virtual; /** * Validate price (override for custom pricing mechanics) */ function _validatePrice(uint16 amount) internal { require(msg.value == amount * purchasePrice, "Invalid purchase amount sent"); } /** * Validate price (override for custom pricing mechanics) */ function _validatePresalePrice(uint16 amount) internal virtual { require(msg.value == amount * presalePurchasePrice, "Invalid purchase amount sent"); } /** * If enabled, lock token transfers until after the sale has ended. * * This helps enforce purchase limits, so someone can't buy -> transfer -> buy again * while the token is minting. */ function _validateTokenTransferability(address from) internal view { require(!transferLocked || purchaseRemaining() == 0 || (active && block.timestamp >= endTime) || from == address(0), "Transfer locked until sale ends"); } /** * Set whether or not token transfers are locked till end of sale */ function _setTransferLocked(bool locked) internal { transferLocked = locked; } /** * @dev See {IERC1155Collection-updateRoyalties}. */ function _updateRoyalties(address payable recipient, uint256 bps) internal { _royaltyRecipient = recipient; _royaltyBps = bps; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 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/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./ICollectionBase.sol"; /** * Collection Drop Contract (Base) */ abstract contract CollectionBase is ICollectionBase { using ECDSA for bytes32; using Strings for uint256; // Immutable variables that should only be set by the constructor or initializer address internal _signingAddress; // Message nonces mapping(string => bool) private _usedNonces; // Sale start/end control bool public active; uint256 public startTime; uint256 public endTime; uint256 public presaleInterval; // Claim period start/end control uint256 public claimStartTime; uint256 public claimEndTime; /** * Withdraw funds */ function _withdraw(address payable recipient, uint256 amount) internal { (bool success,) = recipient.call{value:amount}(""); require(success); } /** * Activate the sale */ function _activate(uint256 startTime_, uint256 duration, uint256 presaleInterval_, uint256 claimStartTime_, uint256 claimEndTime_) internal virtual { require(!active, "Already active"); require(startTime_ > block.timestamp, "Cannot activate in the past"); require(presaleInterval_ < duration, "Presale Interval cannot be longer than the sale"); require(claimStartTime_ <= claimEndTime_ && claimEndTime_ <= startTime_, "Invalid claim times"); startTime = startTime_; endTime = startTime + duration; presaleInterval = presaleInterval_; claimStartTime = claimStartTime_; claimEndTime = claimEndTime_; active = true; emit CollectionActivated(startTime, endTime, presaleInterval, claimStartTime, claimEndTime); } /** * Deactivate the sale */ function _deactivate() internal virtual { startTime = 0; endTime = 0; active = false; claimStartTime = 0; claimEndTime = 0; emit CollectionDeactivated(); } /** * Validate claim signature */ function _validateClaimRequest(bytes32 message, bytes calldata signature, string calldata nonce, uint16 amount) internal virtual { // Verify nonce usage/re-use require(!_usedNonces[nonce], "Cannot replay transaction"); // Verify valid message based on input variables bytes32 expectedMessage = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", (20+bytes(nonce).length+bytes(uint256(amount).toString()).length).toString(), msg.sender, nonce, uint256(amount).toString())); require(message == expectedMessage, "Malformed message"); // Verify signature was performed by the expected signing address address signer = message.recover(signature); require(signer == _signingAddress, "Invalid signature"); _usedNonces[nonce] = true; } /** * Validate claim restrictions */ function _validateClaimRestrictions() internal virtual { require(active, "Inactive"); require(block.timestamp >= claimStartTime && block.timestamp <= claimEndTime, "Outside claim period."); } /** * Validate purchase signature */ function _validatePurchaseRequest(bytes32 message, bytes calldata signature, string calldata nonce) internal virtual { // Verify nonce usage/re-use require(!_usedNonces[nonce], "Cannot replay transaction"); // Verify valid message based on input variables bytes32 expectedMessage = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", (20+bytes(nonce).length).toString(), msg.sender, nonce)); require(message == expectedMessage, "Malformed message"); // Verify signature was performed by the expected signing address address signer = message.recover(signature); require(signer == _signingAddress, "Invalid signature"); _usedNonces[nonce] = true; } /** * Perform purchase restriciton checks. Override if more logic is needed */ function _validatePurchaseRestrictions() internal virtual { require(active, "Inactive"); require(block.timestamp >= startTime, "Purchasing not active"); } /** * @dev See {ICollectionBase-nonceUsed}. */ function nonceUsed(string memory nonce) external view override returns(bool) { return _usedNonces[nonce]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // @author: manifold.xyz import "./ICollectionBase.sol"; /** * @dev ERC1155 Collection Interface */ interface IERC1155Collection is ICollectionBase { struct CollectionState { uint16 transactionLimit; uint16 purchaseMax; uint16 purchaseRemaining; uint256 purchasePrice; uint16 purchaseLimit; uint256 presalePurchasePrice; uint16 presalePurchaseLimit; uint16 purchaseCount; bool active; uint256 startTime; uint256 endTime; uint256 presaleInterval; uint256 claimStartTime; uint256 claimEndTime; } /** * @dev Activates the contract. * @param startTime_ The UNIX timestamp in seconds the sale should start at. * @param duration The number of seconds the sale should remain active. * @param presaleInterval_ The period of time the contract should only be active for presale. */ function activate(uint256 startTime_, uint256 duration, uint256 presaleInterval_, uint256 claimStartTime_, uint256 claimEndTime_) external; /** * @dev Deactivate the contract */ function deactivate() external; /** * @dev Pre-mint tokens to the owner. Sale must not be active. * @param amount The number of tokens to mint. */ function premint(uint16 amount) external; /** * @dev Pre-mint tokens to the list of addresses. Sale must not be active. * @param amounts The amount of tokens to mint per address. * @param addresses The list of addresses to mint a token to. */ function premint(uint16[] calldata amounts, address[] calldata addresses) external; /** * @dev Claim - mint with validation. * @param amount The number of tokens to mint. * @param message Signed message to validate input args. * @param signature Signature of the signer to recover from signed message. * @param nonce Manifold-generated nonce. */ function claim(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external; /** * @dev Purchase - mint with validation. * @param amount The number of tokens to mint. * @param message Signed message to validate input args. * @param signature Signature of the signer to recover from signed message. * @param nonce Manifold-generated nonce. */ function purchase(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external payable; /** * @dev Mint reserve tokens to the owner. Sale must be complete. * @param amount The number of tokens to mint. */ function mintReserve(uint16 amount) external; /** * @dev Mint reserve tokens to the list of addresses. Sale must be complete. * @param amounts The amount of tokens to mint per address. * @param addresses The list of addresses to mint a token to. */ function mintReserve(uint16[] calldata amounts, address[] calldata addresses) external; /** * @dev Set the URI for the metadata for the collection. * @param uri The metadata URI. */ function setCollectionURI(string calldata uri) external; /** * @dev returns the collection state */ function state() external view returns (CollectionState memory); /** * @dev Total amount of tokens remaining for the given token id. */ function purchaseRemaining() external view returns (uint16); /** * @dev Withdraw funds (requires contract admin). * @param recipient The address to withdraw funds to * @param amount The amount to withdraw */ function withdraw(address payable recipient, uint256 amount) external; /** * @dev Set whether or not token transfers are locked until end of sale. * @param locked Whether or not transfers are locked */ function setTransferLocked(bool locked) external; /** * @dev Update royalties * @param recipient The address to set as the royalty recipient * @param bps The basis points to set as the royalty */ function updateRoyalties(address payable recipient, uint256 bps) external; /** * @dev Get the current royalty recipient and amount */ function getRoyalties(uint256) external view returns (address payable recipient, uint256 bps); /** * @dev EIP-2981 compatibility to determine royalty info on sale */ function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); /** * @dev Get balance of address. Similar to IERC1155-balanceOf, but doesn't require token ID * @param owner The address to get the token balance of */ function balanceOf(address owner) external view returns (uint256); /** * @dev Destroys `amount` tokens from `from` * @param from The address to remove tokens from * @param amount The amount of tokens to remove */ function burn(address from, uint16 amount) external; } // 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 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/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/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.1 (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.1 (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.1 (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 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 // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 pragma solidity ^0.8.0; /// @author: manifold.xyz /** * @dev Collection Interface */ interface ICollectionBase { event CollectionActivated(uint256 startTime, uint256 endTime, uint256 presaleInterval, uint256 claimStartTime, uint256 claimEndTime); event CollectionDeactivated(); /** * @dev Check if nonce has been used */ function nonceUsed(string memory nonce) external view returns(bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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; 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 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/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); }
See {IERC1155Collection-setTransferLocked}./
function setTransferLocked(bool locked) external override adminRequired { _setTransferLocked(locked); }
10,079,374
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; /** * @title A string storage bucket for metadata. * * @notice Useful for off-chain actors to store on data on-chain. * Information related to the contract but not required for contract operations. * * @dev Metadata could include UI related pieces, perhaps in a delimited format to support multiple items. */ abstract contract MetaDataStore is ContextUpgradeable { string private _metaData; event MetaDataUpdate(string data, address indexed instigator); /** * @notice The storage box for metadata. Information not required by the contract for operations. * * @dev Information related to the contract but not needed by the contract. */ function metaData() external view returns (string memory) { return _metaData; } //slither-disable-next-line naming-convention function __MetaDataStore_init(string calldata data) internal onlyInitializing { _setMetaData(data); } /** * @notice Replaces any existing stored metadata. * * @dev To expose the setter externally with modifier access control, create a new method invoking _setMetaData. */ function _setMetaData(string calldata data) internal { _metaData = data; emit MetaDataUpdate(data, _msgSender()); } }
slither-disable-next-line naming-convention
function __MetaDataStore_init(string calldata data) internal onlyInitializing { _setMetaData(data); }
2,560,799
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/interfaces/IMigratorChef.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to SakeSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // SakeSwap must mint EXACTLY the same amount of SakeSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: contracts/SakeToken.sol pragma solidity 0.6.12; // SakeToken with Governance. contract SakeToken is Context, IERC20, Ownable { 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 = "SakeToken"; string private _symbol = "SAKE"; uint8 private _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); _moveDelegates(_delegates[sender], _delegates[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 { } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (SakeMaster). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SAKE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SAKE::delegateBySig: invalid nonce"); require(now <= expiry, "SAKE::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, "SAKE::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 SAKEs (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, "SAKE::_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/SakeMaster.sol pragma solidity 0.6.12; // SakeMaster is the master of Sake. He can make Sake and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SAKE is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract SakeMaster is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SAKEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSakePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SAKEs to distribute per block. uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs. uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below. } // The SAKE TOKEN! SakeToken public sake; // Dev address. address public devaddr; // Block number when beta test period ends. uint256 public betaTestEndBlock; // Block number when bonus SAKE period ends. uint256 public bonusEndBlock; // Block number when mint SAKE period ends. uint256 public mintEndBlock; // SAKE tokens created per block. uint256 public sakePerBlock; // Bonus muliplier for 5~20 days sake makers. uint256 public constant BONUSONE_MULTIPLIER = 20; // Bonus muliplier for 20~35 sake makers. uint256 public constant BONUSTWO_MULTIPLIER = 2; // beta test block num,about 5 days. uint256 public constant BETATEST_BLOCKNUM = 35000; // Bonus block num,about 15 days. uint256 public constant BONUS_BLOCKNUM = 100000; // mint end block num,about 30 days. uint256 public constant MINTEND_BLOCKNUM = 200000; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Record whether the pair has been added. mapping(address => uint256) public lpTokenPID; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SAKE mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( SakeToken _sake, address _devaddr, uint256 _sakePerBlock, uint256 _startBlock ) public { sake = _sake; devaddr = _devaddr; sakePerBlock = _sakePerBlock; startBlock = _startBlock; betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM); bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM); mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add."); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSakePerShare: 0 }) ); lpTokenPID[address(_lpToken)] = poolInfo.length; } // Update the given pool's SAKE allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Handover the saketoken mintage right. function handoverSakeMintage(address newOwner) public onlyOwner { sake.transferOwnership(newOwner); } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to; if (_toFinal <= betaTestEndBlock) { return _toFinal.sub(_from); }else if (_from >= mintEndBlock) { return 0; } else if (_toFinal <= bonusEndBlock) { if (_from < betaTestEndBlock) { return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)); } else { return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER); } } else { if (_from < betaTestEndBlock) { return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add( (_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER))); } else if (betaTestEndBlock <= _from && _from < bonusEndBlock) { return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)); } else { return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER); } } } // View function to see pending SAKEs on frontend. function pendingSake(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSakePerShare = pool.accSakePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSakePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (multiplier == 0) { pool.lastRewardBlock = block.number; return; } uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint); sake.mint(devaddr, sakeReward.div(15)); sake.mint(address(this), sakeReward); pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to SakeMaster for SAKE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12); if (pending > 0) safeSakeTransfer(msg.sender, pending); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from SakeMaster. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12); safeSakeTransfer(msg.sender, pending); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount > 0, "emergencyWithdraw: not good"); uint256 _amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit EmergencyWithdraw(msg.sender, _pid, _amount); } // Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs. function safeSakeTransfer(address _to, uint256 _amount) internal { uint256 sakeBal = sake.balanceOf(address(this)); if (_amount > sakeBal) { sake.transfer(_to, sakeBal); } else { sake.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } } // File: contracts/interfaces/IStakingRewards.sol pragma solidity 0.6.12; // Uniswap Liquidity Mining interface IStakingRewards { function earned(address account) external view returns (uint256); function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; function balanceOf(address account) external view returns (uint256); } // File: contracts/SakeUniV2.sol pragma solidity 0.6.12; contract SakeUniV2 is Ownable, ERC20("Wrapped UniSwap Liquidity Token", "WULP") { using SafeERC20 for IERC20; using SafeMath for uint256; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 sakeRewardDebt; // Sake reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SAKEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSakePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. uint256 uniRewardDebt; // similar with sakeRewardDebt uint256 firstDepositTime; } // Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; IStakingRewards public uniStaking; uint256 public lastRewardBlock; // Last block number that SAKEs distribution occurs. uint256 public accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below. uint256 public accUniPerShare; // Accumulated UNIs per share, times 1e12. See below. // The UNI Token. IERC20 public uniToken; // The SAKE TOKEN! SakeToken public sake; SakeMaster public sakeMaster; IERC20 public lpToken; // Address of LP token contract. // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // The address to receive UNI token fee. address public uniTokenFeeReceiver; // The ratio of UNI token fee (10%). uint8 public uniFeeRatio = 10; uint8 public isMigrateComplete = 0; //Liquidity Event event EmergencyWithdraw(address indexed user, uint256 amount); event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); constructor( SakeMaster _sakeMaster, address _uniLpToken, address _uniStaking, address _uniToken, SakeToken _sake, address _uniTokenFeeReceiver ) public { sakeMaster = _sakeMaster; uniStaking = IStakingRewards(_uniStaking); uniToken = IERC20(_uniToken); sake = _sake; uniTokenFeeReceiver = _uniTokenFeeReceiver; lpToken = IERC20(_uniLpToken); } //////////////////////////////////////////////////////////////////// //Migrate liquidity to sakeswap /////////////////////////////////////////////////////////////////// function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } function migrate() public onlyOwner { require(address(migrator) != address(0), "migrate: no migrator"); updatePool(); //get all lp and uni reward from uniStaking uniStaking.withdraw(totalSupply()); //get all wrapped lp and sake reward from sakeMaster uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1); sakeMaster.withdraw(poolIdInSakeMaster, totalSupply()); uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); lpToken = newLpToken; isMigrateComplete = 1; } // View function to see pending SAKEs and UNIs on frontend. function pending(address _user) external view returns (uint256 _sake, uint256 _uni) { UserInfo storage user = userInfo[_user]; uint256 tempAccSakePerShare = accSakePerShare; uint256 tempAccUniPerShare = accUniPerShare; if (isMigrateComplete == 0 && block.number > lastRewardBlock && totalSupply() != 0) { uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1); uint256 sakeReward = sakeMaster.pendingSake(poolIdInSakeMaster, address(this)); tempAccSakePerShare = tempAccSakePerShare.add(sakeReward.mul(1e12).div(totalSupply())); uint256 uniReward = uniStaking.earned(address(this)); tempAccUniPerShare = tempAccUniPerShare.add(uniReward.mul(1e12).div(totalSupply())); } _sake = user.amount.mul(tempAccSakePerShare).div(1e12).sub(user.sakeRewardDebt); _uni = user.amount.mul(tempAccUniPerShare).div(1e12).sub(user.uniRewardDebt); } // Update reward variables of the given pool to be up-to-date. function updatePool() public { if (block.number <= lastRewardBlock || isMigrateComplete == 1) { return; } if (totalSupply() == 0) { lastRewardBlock = block.number; return; } uint256 sakeBalance = sake.balanceOf(address(this)); uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1); // Get Sake Reward from SakeMaster sakeMaster.deposit(poolIdInSakeMaster, 0); uint256 sakeReward = sake.balanceOf(address(this)).sub(sakeBalance); accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div((totalSupply()))); uint256 uniReward = uniStaking.earned(address(this)); uniStaking.getReward(); accUniPerShare = accUniPerShare.add(uniReward.mul(1e12).div(totalSupply())); lastRewardBlock = block.number; } function _mintWulp(address _addr, uint256 _amount) internal { lpToken.safeTransferFrom(_addr, address(this), _amount); _mint(address(this), _amount); } function _burnWulp(address _to, uint256 _amount) internal { lpToken.safeTransfer(address(_to), _amount); _burn(address(this), _amount); } // Deposit LP tokens to SakeMaster for SAKE allocation. function deposit(uint256 _amount) public { require(isMigrateComplete == 0 || (isMigrateComplete == 1 && _amount == 0), "already migrate"); UserInfo storage user = userInfo[msg.sender]; updatePool(); if (_amount > 0 && user.firstDepositTime == 0) user.firstDepositTime = block.number; uint256 pendingSake = user.amount.mul(accSakePerShare).div(1e12).sub(user.sakeRewardDebt); uint256 pendingUni = user.amount.mul(accUniPerShare).div(1e12).sub(user.uniRewardDebt); user.amount = user.amount.add(_amount); user.sakeRewardDebt = user.amount.mul(accSakePerShare).div(1e12); user.uniRewardDebt = user.amount.mul(accUniPerShare).div(1e12); if (pendingSake > 0) _safeSakeTransfer(msg.sender, pendingSake); if (pendingUni > 0) { uint256 uniFee = pendingUni.mul(uniFeeRatio).div(100); uint256 uniToUser = pendingUni.sub(uniFee); _safeUniTransfer(uniTokenFeeReceiver, uniFee); _safeUniTransfer(msg.sender, uniToUser); } if (_amount > 0) { //generate wrapped uniswap lp token _mintWulp(msg.sender, _amount); //approve and stake to uniswap lpToken.approve(address(uniStaking), _amount); uniStaking.stake(_amount); //approve and stake to sakemaster _approve(address(this), address(sakeMaster), _amount); uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1); sakeMaster.deposit(poolIdInSakeMaster, _amount); } emit Deposit(msg.sender, _amount); } // Withdraw LP tokens from SakeUni. function withdraw(uint256 _amount) public { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(); uint256 pendingSake = user.amount.mul(accSakePerShare).div(1e12).sub(user.sakeRewardDebt); uint256 pendingUni = user.amount.mul(accUniPerShare).div(1e12).sub(user.uniRewardDebt); user.amount = user.amount.sub(_amount); user.sakeRewardDebt = user.amount.mul(accSakePerShare).div(1e12); user.uniRewardDebt = user.amount.mul(accUniPerShare).div(1e12); if (pendingSake > 0) _safeSakeTransfer(msg.sender, pendingSake); if (pendingUni > 0) { uint256 uniFee = pendingUni.mul(uniFeeRatio).div(100); uint256 uniToUser = pendingUni.sub(uniFee); _safeUniTransfer(uniTokenFeeReceiver, uniFee); _safeUniTransfer(msg.sender, uniToUser); } if (_amount > 0) { if (isMigrateComplete == 0) { uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1); //unstake wrapped lp token from sake master sakeMaster.withdraw(poolIdInSakeMaster, _amount); //unstake uniswap lp token from uniswap uniStaking.withdraw(_amount); } _burnWulp(address(msg.sender), _amount); } emit Withdraw(msg.sender, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() public { UserInfo storage user = userInfo[msg.sender]; require(user.amount > 0, "emergencyWithdraw: not good"); uint256 _amount = user.amount; user.amount = 0; user.sakeRewardDebt = 0; user.uniRewardDebt = 0; { if (isMigrateComplete == 0) { uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1); //unstake wrapped lp token from sake master sakeMaster.withdraw(poolIdInSakeMaster, _amount); //unstake lp token from uniswap uniStaking.withdraw(_amount); } _burnWulp(address(msg.sender), _amount); } emit EmergencyWithdraw(msg.sender, _amount); } // Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs. function _safeSakeTransfer(address _to, uint256 _amount) internal { uint256 sakeBal = sake.balanceOf(address(this)); if (_amount > sakeBal) { sake.transfer(_to, sakeBal); } else { sake.transfer(_to, _amount); } } // Safe uni transfer function function _safeUniTransfer(address _to, uint256 _amount) internal { uint256 uniBal = uniToken.balanceOf(address(this)); if (_amount > uniBal) { uniToken.transfer(_to, uniBal); } else { uniToken.transfer(_to, _amount); } } function setUniTokenFeeReceiver(address _uniTokenFeeReceiver) public onlyOwner { uniTokenFeeReceiver = _uniTokenFeeReceiver; } }
get all lp and uni reward from uniStakingget all wrapped lp and sake reward from sakeMaster
function migrate() public onlyOwner { require(address(migrator) != address(0), "migrate: no migrator"); updatePool(); uniStaking.withdraw(totalSupply()); uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1); sakeMaster.withdraw(poolIdInSakeMaster, totalSupply()); uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); lpToken = newLpToken; isMigrateComplete = 1; }
7,777,369
pragma solidity 0.5.13; import "./libs/Ownable.sol"; contract RelayerManager is Ownable { address[] internal relayers; mapping(address => bool) internal relayerStatus; event RelayerAdded(address relayer, address owner); constructor(address owner) public Ownable(owner) { // Empty constructor to pass owner as parameter during deployment } function getRelayerStatus(address relayer) public view returns (bool status) { status = relayerStatus[relayer]; } function getAllRelayers() public view returns (address[] memory) { return relayers; } //Register new Relayers function addRelayers(address[] memory relayerArray) public onlyOwner { for (uint256 i = 0; i < relayerArray.length; i++) { require( relayerArray[i] != address(0), "Relayer address cannot be zero" ); relayers.push(relayerArray[i]); relayerStatus[relayerArray[i]] = true; emit RelayerAdded(relayerArray[i], msg.sender); } } // Register single relayer function addRelayer(address relayerAddress) public onlyOwner { require(relayerAddress != address(0), "relayer address can not be 0"); relayers.push(relayerAddress); relayerStatus[relayerAddress] = true; emit RelayerAdded(relayerAddress, msg.sender); } }
Register new Relayers
function addRelayers(address[] memory relayerArray) public onlyOwner { for (uint256 i = 0; i < relayerArray.length; i++) { require( relayerArray[i] != address(0), "Relayer address cannot be zero" ); relayers.push(relayerArray[i]); relayerStatus[relayerArray[i]] = true; emit RelayerAdded(relayerArray[i], msg.sender); } }
15,838,583
pragma solidity ^0.4.16; /* * Abstract Token Smart Contract. Copyright &#169; 2017 by ABDK Consulting. * Author: Mikhail Vladimirov <<span class="__cf_email__" data-cfemail="c1aca8aaa9a0a8adefb7ada0a5a8aca8b3aeb781a6aca0a8adefa2aeac">[email&#160;protected]</span>> */ pragma solidity ^0.4.16; /* * ERC-20 Standard Token Smart Contract Interface. * Copyright &#169; 2016–2017 by ABDK Consulting. * Author: Mikhail Vladimirov <<span class="__cf_email__" data-cfemail="2845414340494144065e44494c4145415a475e684f45494144064b4745">[email&#160;protected]</span>> */ pragma solidity ^0.4.16; /** * ERC-20 standard token interface, as defined * <a href="http://github.com/ethereum/EIPs/issues/20">here</a>. */ contract Token { /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply); /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) constant returns (uint256 balance); /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) returns (bool success); /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) returns (bool success); /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success); /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance (address _owner, address _spender) constant returns (uint256 remaining); /** * Logged when tokens were transferred from one owner to another. * * @param _from address of the owner, tokens were transferred from * @param _to address of the owner, tokens were transferred to * @param _value number of tokens transferred */ event Transfer (address indexed _from, address indexed _to, uint256 _value); /** * Logged when owner approved his tokens to be transferred by some spender. * * @param _owner owner who approved his tokens to be transferred * @param _spender spender who were allowed to transfer the tokens belonging * to the owner * @param _value number of tokens belonging to the owner, approved to be * transferred by the spender */ event Approval ( address indexed _owner, address indexed _spender, uint256 _value); } /* * Safe Math Smart Contract. Copyright &#169; 2016–2017 by ABDK Consulting. * Author: Mikhail Vladimirov <<span class="__cf_email__" data-cfemail="4a272321222b2326643c262b2e23272338253c0a2d272b232664292527">[email&#160;protected]</span>> */ pragma solidity ^0.4.16; /** * Provides methods to safely add, subtract and multiply uint256 numbers. */ contract SafeMath { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Add two uint256 values, throw in case of overflow. * * @param x first value to add * @param y second value to add * @return x + y */ function safeAdd (uint256 x, uint256 y) constant internal returns (uint256 z) { assert (x <= MAX_UINT256 - y); return x + y; } /** * Subtract one uint256 value from another, throw in case of underflow. * * @param x value to subtract from * @param y value to subtract * @return x - y */ function safeSub (uint256 x, uint256 y) constant internal returns (uint256 z) { assert (x >= y); return x - y; } /** * Multiply two uint256 values, throw in case of overflow. * * @param x first value to multiply * @param y second value to multiply * @return x * y */ function safeMul (uint256 x, uint256 y) constant internal returns (uint256 z) { if (y == 0) return 0; // Prevent division by zero at the next line assert (x <= MAX_UINT256 / y); return x * y; } } /** * Abstract Token Smart Contract that could be used as a base contract for * ERC-20 token contracts. */ contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ function AbstractToken () { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) constant returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) returns (bool success) { if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) returns (bool success) { if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); if (_value > 0 && _from != _to) { accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer (_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance (address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; } /** * Game Connect token smart contract. */ contract LUCToken is AbstractToken { /** * Address of the owner of this smart contract. */ address private owner; /** * Total number of tokens in circulation. */ uint256 tokenCount; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new Game Connect token smart contract, with given number of tokens issued * and given to msg.sender, and make msg.sender the owner of this smart * contract. * * @param _tokenCount number of tokens to issue and give to msg.sender */ function LUCToken (uint256 _tokenCount) { owner = msg.sender; tokenCount = _tokenCount; accounts [msg.sender] = _tokenCount; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply) { return tokenCount; } /** * Get name of this token. * * @return name of this token */ function name () constant returns (string result) { return "Level-Up Coin"; } /** * Get symbol of this token. * * @return symbol of this token */ function symbol () constant returns (string result) { return "LUC"; } /** * Get number of decimals for this token. * * @return number of decimals for this token */ function decimals () constant returns (uint8 result) { return 18; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) returns (bool success) { if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) returns (bool success) { if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, this method * receives assumed current allowance value as an argument. If actual * allowance differs from an assumed one, this method just returns false. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _currentValue assumed number of tokens currently allowed to be * transferred * @param _newValue number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _currentValue, uint256 _newValue) returns (bool success) { if (allowance (msg.sender, _spender) == _currentValue) return approve (_spender, _newValue); else return false; } /** * Burn given number of tokens belonging to message sender. * * @param _value number of tokens to burn * @return true on success, false on error */ function burnTokens (uint256 _value) returns (bool success) { if (_value > accounts [msg.sender]) return false; else if (_value > 0) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); tokenCount = safeSub (tokenCount, _value); return true; } else return true; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner (address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; Freeze (); } } /** * Unfreeze token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; Unfreeze (); } } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); }
Get number of decimals for this token. return number of decimals for this token/
function decimals () constant returns (uint8 result) { return 18; }
2,163,544
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.10; import {DSTest} from "ds-test/test.sol"; import {PersonalizedSVG} from "../lib/PersonalizedSVG.sol"; import {SquadzEngine} from "../SquadzEngine.sol"; import {ShellFactory} from "shell-contracts.git/ShellFactory.sol"; import {ShellERC721} from "shell-contracts.git/ShellERC721.sol"; import {Hevm} from "./Hevm.sol"; import {console} from "./console.sol"; contract SquadzTest is DSTest { //------------------- // State //------------------- Hevm vm = Hevm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); PersonalizedSVG personalizedSVG; SquadzEngine squadzEngine; ShellFactory shellFactory; ShellERC721 shellImplementation; string implementationName = "erc721"; ShellERC721 squadzCollection; string collectionName = "squad"; string collectionSymb = "SQD"; address owner = address(0xBEEF); address bob = address(0xFEEB); uint256 defaultFork = 0; /* Length of time a token is active */ uint256 public constant baseExpiry = 365 days; /* Minimum time between mints for admins */ uint256 public constant baseCooldown = 8 hours; /* Power bonus for having an active token */ uint8 public constant baseBonus = 10; /* Max power from held tokens */ uint8 public constant baseMax = 20; /* personalized svg */ address public baseSVG; //------------------- // Events //------------------- event SetCollectionConfig( address indexed collection, uint256 indexed fork, uint256 expiry, uint256 cooldown, uint256 bonus, uint256 max, address svg ); //------------------- // Set up //------------------- function setUp() public { personalizedSVG = new PersonalizedSVG(); baseSVG = address(personalizedSVG); squadzEngine = new SquadzEngine(address(0), baseSVG); shellFactory = new ShellFactory(); shellImplementation = new ShellERC721(); shellFactory.registerImplementation( implementationName, shellImplementation ); squadzCollection = ShellERC721( address( shellFactory.createCollection( collectionName, collectionSymb, implementationName, squadzEngine, owner ) ) ); // time being 0 messes things up vm.warp(10); } //------------------- // Tests //------------------- // name // function test_name() public { assertEq("Squadz Engine v0.0.1", squadzEngine.name(), "engine name"); } // setCollectionConfig // function test_setCollectionConfig( uint128 expiry_, uint128 cooldown_, uint128 bonus_, uint128 max_ ) public { ( uint256 expiry, uint256 cooldown, uint256 bonus, uint256 max, address svg ) = squadzEngine.getCollectionConfig(squadzCollection, defaultFork); assertEq(expiry, baseExpiry, "expiry"); assertEq(cooldown, baseCooldown, "cooldown"); assertEq(bonus, baseBonus, "bonus"); assertEq(max, baseMax, "max"); assertEq(svg, baseSVG, "svg"); uint256 expectedNewExpiry = uint256(expiry_) + 1; uint256 expectedNewCooldown = uint256(cooldown_) + 1; uint256 expectedNewBonus = uint256(bonus_) + 1; uint256 expectedNewMax = uint256(max_) + 1; address expectedNewSVG = address(new PersonalizedSVG()); vm.expectEmit(true, true, false, true); vm.prank(owner); emit SetCollectionConfig( address(squadzCollection), defaultFork, expectedNewExpiry, expectedNewCooldown, expectedNewBonus, expectedNewMax, expectedNewSVG ); squadzEngine.setCollectionConfig( squadzCollection, defaultFork, expectedNewExpiry, expectedNewCooldown, expectedNewBonus, expectedNewMax, expectedNewSVG ); ( uint256 newExpiry, uint256 newCooldown, uint256 newBonus, uint256 newMax, address newSVG ) = squadzEngine.getCollectionConfig(squadzCollection, defaultFork); assertEq(newExpiry, expectedNewExpiry, "expiry"); assertEq(newCooldown, expectedNewCooldown, "cooldown"); assertEq(newBonus, expectedNewBonus, "bonus"); assertEq(newMax, expectedNewMax, "max"); assertEq(newSVG, expectedNewSVG, "svg"); } function testFail_setCollectionConfig_notOwner() public { vm.prank(bob); squadzEngine.setCollectionConfig( squadzCollection, defaultFork, baseExpiry + 1, baseCooldown + 1, baseBonus + 1, baseMax + 1, baseSVG ); } function testFail_setCollectionConfig_zeroExpiry() public { vm.prank(owner); squadzEngine.setCollectionConfig( squadzCollection, defaultFork, 0, baseCooldown + 1, baseBonus + 1, baseMax + 1, baseSVG ); } function testFail_setCollectionConfig_zeroCooldown() public { vm.prank(owner); squadzEngine.setCollectionConfig( squadzCollection, defaultFork, baseExpiry + 1, 0, baseBonus + 1, baseMax + 1, baseSVG ); } function testFail_setCollectionConfig_zeroBonus() public { vm.prank(owner); squadzEngine.setCollectionConfig( squadzCollection, defaultFork, baseExpiry + 1, baseCooldown + 1, 0, baseMax + 1, baseSVG ); } function testFail_setCollectionConfig_zeroMax() public { vm.prank(owner); squadzEngine.setCollectionConfig( squadzCollection, defaultFork, baseExpiry + 1, baseCooldown + 1, baseBonus + 1, 0, baseSVG ); } function testFail_setCollectionConfig_invalidSVG(address invalidSVG) public { if (invalidSVG == baseSVG) revert("same svg"); vm.prank(owner); squadzEngine.setCollectionConfig( squadzCollection, defaultFork, baseExpiry + 1, baseCooldown + 1, baseBonus + 1, baseMax + 1, invalidSVG ); } // mint // function test_mint_ownerMintAdmin(address mintee) public { if (mintee == address(0)) return; (, , , bool activeBefore, bool adminBefore, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(!activeBefore, "mintee active"); assertTrue(!adminBefore, "mintee admin"); vm.prank(owner); squadzEngine.mint(squadzCollection, defaultFork, mintee, true); (, , , bool activeAfter, bool adminAfter, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(activeAfter, "mintee active"); assertTrue(adminAfter, "mintee admin"); } function test_mint_ownerMintNonAdmin(address mintee) public { if (mintee == address(0)) return; (, , , bool activeBefore, bool adminBefore, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(!activeBefore, "mintee active"); assertTrue(!adminBefore, "mintee admin"); vm.prank(owner); squadzEngine.mint(squadzCollection, defaultFork, mintee, false); (, , , bool activeAfter, bool adminAfter, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(activeAfter, "mintee active"); assertTrue(!adminAfter, "mintee admin"); } function test_mint_adminMintNonAdmin(address admin, address mintee) public { if (mintee == address(0)) return; if (admin == address(0)) return; if (mintee == admin) return; test_mint_ownerMintAdmin(admin); (, , , bool activeBefore, bool adminBefore, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(!activeBefore, "mintee active 1"); assertTrue(!adminBefore, "mintee admin 1"); vm.prank(admin); squadzEngine.mint(squadzCollection, defaultFork, mintee, false); (, , , bool activeAfter, bool adminAfter, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(activeAfter, "mintee active 2"); assertTrue(!adminAfter, "mintee admin 2"); (, , uint256 timestamp1, , , , ) = squadzEngine.getMemberInfo( squadzCollection, defaultFork, mintee ); assertEq(timestamp1, block.timestamp, "timestamp 1"); console.log("timestamp before warp", block.timestamp); vm.warp(block.timestamp + baseCooldown + 1); console.log("timestamp after warp", block.timestamp); vm.prank(admin); squadzEngine.mint(squadzCollection, defaultFork, mintee, false); (, , uint256 timestamp2, , , , ) = squadzEngine.getMemberInfo( squadzCollection, defaultFork, mintee ); assertEq(timestamp2, block.timestamp, "timestamp 2"); } function testFail_mint_adminMintAdmin(address admin, address mintee) public { if (mintee == address(0)) return; if (admin == address(0)) return; test_mint_ownerMintAdmin(admin); (, , , bool activeBefore, bool adminBefore, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(!activeBefore, "mintee active"); assertTrue(!adminBefore, "mintee admin"); vm.prank(admin); squadzEngine.mint(squadzCollection, defaultFork, mintee, true); } function testFail_mint_inactiveAdmin(address admin, address mintee) public { if (mintee == address(0)) return; if (admin == address(0)) return; test_mint_ownerMintAdmin(admin); (, , , bool activeBefore, bool adminBefore, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(!activeBefore, "mintee active"); assertTrue(!adminBefore, "mintee admin"); vm.warp(block.timestamp + baseExpiry + 1); vm.prank(admin); squadzEngine.mint(squadzCollection, defaultFork, mintee, false); } function testFail_mint_nonAdminMint(address admin, address mintee) public { if (mintee == address(0)) return; if (admin == address(0)) return; (, , , bool activeBefore, bool adminBefore, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(!activeBefore, "mintee active"); assertTrue(!adminBefore, "mintee admin"); vm.prank(admin); squadzEngine.mint(squadzCollection, defaultFork, mintee, false); } function testFail_mint_adminMintCooldownNotUp( address admin, address mintee, uint64 cooldownNumerator ) public { if (mintee == address(0)) return; if (admin == address(0)) return; test_mint_ownerMintAdmin(admin); (, , , bool activeBefore, bool adminBefore, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(!activeBefore, "mintee active"); assertTrue(!adminBefore, "mintee admin"); uint256 newTime = block.timestamp + ((baseCooldown * cooldownNumerator) / type(uint64).max); vm.warp(newTime); squadzEngine.mint(squadzCollection, defaultFork, mintee, false); } // batchMint // function test_batchMint_owner() public { uint256 minteeCount = 10; address[] memory mintees = new address[](minteeCount); bool[] memory adminBools = new bool[](minteeCount); uint256 i; for (i; i < minteeCount; i++) { mintees[i] = address(uint160(i + 1)); if (i % 2 == 0) adminBools[i] = true; address mintee = mintees[i]; (, , , bool activeBefore, bool adminBefore, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(!activeBefore, "mintee active"); assertTrue(!adminBefore, "mintee admin"); } vm.prank(owner); squadzEngine.batchMint( squadzCollection, defaultFork, mintees, adminBools ); for (i = 0; i < minteeCount; i++) { address mintee = mintees[i]; (, , , bool activeAfter, bool adminAfter, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(activeAfter, "mintee active"); assertTrue(adminAfter == adminBools[i], "mintee admin"); } } function test_batchMint_admin(address admin) public { if (admin == address(0)) return; test_mint_ownerMintAdmin(admin); uint256 minteeCount = 10; address[] memory mintees = new address[](minteeCount); bool[] memory adminBools = new bool[](minteeCount); vm.prank(owner); squadzEngine.setCollectionConfig( squadzCollection, defaultFork, baseExpiry, type(uint256).max, baseBonus, baseMax, baseSVG ); (, uint256 cooldown, , , ) = squadzEngine.getCollectionConfig( squadzCollection, defaultFork ); console.log("found cooldown", cooldown); uint256 i; for (i; i < minteeCount; i++) { mintees[i] = address(uint160(i + 1)); address mintee = mintees[i]; if (admin == mintee) return; (, , , bool activeBefore, bool adminBefore, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(!activeBefore, "mintee active"); assertTrue(!adminBefore, "mintee admin"); } vm.prank(admin); squadzEngine.batchMint( squadzCollection, defaultFork, mintees, adminBools ); for (i = 0; i < minteeCount; i++) { address mintee = mintees[i]; (, , , bool activeAfter, bool adminAfter, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(activeAfter, "mintee active"); assertTrue(!adminAfter, "mintee admin"); } } function testFail_batchMint_arrayMismatch() public { uint256 minteeCount = 10; address[] memory mintees = new address[](minteeCount); bool[] memory adminBools = new bool[](minteeCount - 1); uint256 i; for (i; i < minteeCount; i++) { mintees[i] = address(uint160(i + 1)); address mintee = mintees[i]; (, , , bool activeBefore, bool adminBefore, , ) = squadzEngine .getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(!activeBefore, "mintee active"); assertTrue(!adminBefore, "mintee admin"); } vm.prank(owner); squadzEngine.batchMint( squadzCollection, defaultFork, mintees, adminBools ); } // latestToken // function test_latestToken(address mintee, uint32 timeSkip) public { if (mintee == address(0)) return; ( uint256 tokenId1, , uint256 timestamp1, bool admin1, , , ) = squadzEngine.getMemberInfo(squadzCollection, defaultFork, mintee); assertEq(tokenId1, 0, "tokenId before"); assertEq(timestamp1, 0, "timestamp before"); assertTrue(!admin1, "admin before"); test_mint_ownerMintAdmin(mintee); ( uint256 tokenId2, , uint256 timestamp2, , bool admin2, , ) = squadzEngine.getMemberInfo(squadzCollection, defaultFork, mintee); assertEq( tokenId2, squadzCollection.nextTokenId() - 1, "tokenId after 1" ); assertEq(timestamp2, block.timestamp, "timestamp after 1"); assertTrue(admin2, "admin after 1"); vm.warp(block.timestamp + timeSkip); vm.prank(owner); squadzEngine.mint(squadzCollection, defaultFork, mintee, false); ( uint256 tokenId3, , uint256 timestamp3, , bool admin3, , ) = squadzEngine.getMemberInfo(squadzCollection, defaultFork, mintee); assertEq( tokenId3, squadzCollection.nextTokenId() - 1, "tokenId after 2" ); assertEq(timestamp3, block.timestamp, "timestamp after 2"); assertTrue(!admin3, "admin after 2"); } // active & admin function test_activeAdmin(address mintee, uint8 expiryNumerator) public { if (mintee == address(0)) return; // if address has never been minted a token, returns false, false (, , , bool isActive1, bool isAdmin1, , ) = squadzEngine.getMemberInfo( squadzCollection, defaultFork, mintee ); assertTrue(!isActive1, "is active 1"); assertTrue(!isAdmin1, "is admin 1"); uint256 timeSkip = ((baseExpiry * expiryNumerator) / type(uint8).max); // if address was most recently minted a non-admin token within expiry at timestamp, return true, false vm.prank(owner); squadzEngine.mint(squadzCollection, defaultFork, mintee, false); vm.warp(block.timestamp + timeSkip); (, , , bool isActive2, bool isAdmin2, , ) = squadzEngine.getMemberInfo( squadzCollection, defaultFork, mintee ); console.log(isActive2, "is active"); console.log(isAdmin2, "is admin 2"); assertTrue(isActive2, "is active 2"); assertTrue(!isAdmin2, "is admin 2"); // if address was most recently minted an admin token within expiry at timestamp, returns true, true vm.prank(owner); squadzEngine.mint(squadzCollection, defaultFork, mintee, true); vm.warp(block.timestamp + timeSkip); (, , , bool isActive3, bool isAdmin3, , ) = squadzEngine.getMemberInfo( squadzCollection, defaultFork, mintee ); assertTrue(isActive3, "is active 3"); assertTrue(isAdmin3, "is admin 3"); // avoid stack-too-deep error address mintee2 = mintee; // if address was most recently minted an admin token outside of expiry at timestamp, return false, true vm.prank(owner); squadzEngine.mint(squadzCollection, defaultFork, mintee2, true); vm.warp(block.timestamp + baseExpiry + 1); (, , , bool isActive4, bool isAdmin4, , ) = squadzEngine.getMemberInfo( squadzCollection, defaultFork, mintee2 ); assertTrue(!isActive4, "is active 4"); assertTrue(isAdmin4, "is admin 4"); // if address was most recently minted a non-admin token outside of expiry at timestamp, return false, false vm.prank(owner); squadzEngine.mint(squadzCollection, defaultFork, mintee2, false); vm.warp(block.timestamp + baseExpiry + 1); (, , , bool isActive5, bool isAdmin5, , ) = squadzEngine.getMemberInfo( squadzCollection, defaultFork, mintee2 ); assertTrue(!isActive5, "is active 5"); assertTrue(!isAdmin5, "is admin 5"); } // power // function test_power( address mintee, uint8 tokenCount, uint32 timeSkip ) public { if (mintee == address(0)) return; uint8 i; for (i; i < tokenCount; i++) { vm.prank(owner); squadzEngine.mint(squadzCollection, defaultFork, mintee, false); } uint256 bonus = baseBonus; if (timeSkip > baseExpiry || tokenCount == 0) bonus = 0; uint256 balanceScore = uint256(tokenCount); if (balanceScore > baseMax) balanceScore = baseMax; vm.warp(block.timestamp + timeSkip); (, , , , , uint256 power, ) = squadzEngine.getMemberInfo( squadzCollection, defaultFork, mintee ); assertEq(power, bonus + balanceScore, "power"); } // removeAdmin // function test_removeAdmin(address mintee) public { if (mintee == address(0)) return; test_mint_ownerMintAdmin(mintee); ( uint256 tokenId1, , uint256 timestamp1, , bool admin1, , ) = squadzEngine.getMemberInfo(squadzCollection, defaultFork, mintee); assertTrue(admin1, "admin 1"); vm.prank(owner); squadzEngine.removeAdmin(squadzCollection, defaultFork, mintee); ( uint256 tokenId2, , uint256 timestamp2, , bool admin2, , ) = squadzEngine.getMemberInfo(squadzCollection, defaultFork, mintee); assertEq(tokenId1, tokenId2, "token Ids"); assertEq(timestamp1, timestamp2, "timestamps"); assertTrue(!admin2, "admin 2"); } function testFail_removAdmin_nonOwner(address mintee) public { if (mintee == address(0)) return; test_mint_ownerMintAdmin(mintee); squadzEngine.removeAdmin(squadzCollection, defaultFork, mintee); } // getTokenURI // function test_getTokenURI(address mintee) public { if (mintee == address(0)) return; test_mint_ownerMintAdmin(mintee); (uint256 tokenId, , , , , , ) = squadzEngine.getMemberInfo( squadzCollection, defaultFork, mintee ); squadzCollection.tokenURI(tokenId); // not sure what to do here tbh } }
not sure what to do here tbh
function test_getTokenURI(address mintee) public { if (mintee == address(0)) return; test_mint_ownerMintAdmin(mintee); (uint256 tokenId, , , , , , ) = squadzEngine.getMemberInfo( squadzCollection, defaultFork, mintee ); squadzCollection.tokenURI(tokenId); }
6,365,148
// Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity ^0.6.0; // import "./IERC20.sol"; // import "../../math/SafeMath.sol"; // import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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"); } } } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: contracts/lib/ExplicitERC20.sol /* 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. */ // 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 transfered. */ 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" ); } } } // Dependency file: contracts/lib/AddressArrayUtils.sol /* 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. */ // pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays */ 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 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 occurence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { 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; } /** * 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; } /** * @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("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * 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]); } } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.6.0; // import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } /* 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. */ pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol"; // import { ExplicitERC20 } from "../lib/ExplicitERC20.sol"; /** * @title Controller * @author Set Protocol * * Contract that houses state for approvals and system contracts such as added Sets, * modules, factories, resources (like price oracles), and protocol fee configurations. */ contract Controller is Ownable { using SafeMath for uint256; using AddressArrayUtils for address[]; /* ============ Events ============ */ event FactoryAdded(address _factory); event FactoryRemoved(address _factory); event FeeEdited(address indexed _module, uint256 indexed _feeType, uint256 _feePercentage); event FeeRecipientChanged(address _newFeeRecipient); event ModuleAdded(address _module); event ModuleRemoved(address _module); event ResourceAdded(address _resource, uint256 _id); event ResourceRemoved(address _resource, uint256 _id); event SetAdded(address _setToken, address _factory); event SetRemoved(address _setToken); /* ============ Modifiers ============ */ /** * Throws if function is called by any address other than a valid factory. */ modifier onlyFactory() { require(isFactory[msg.sender], "Only valid factories can call"); _; } /** * Throws if function is called by any address other than a module or a resource. */ modifier onlyModuleOrResource() { require( isResource[msg.sender] || isModule[msg.sender], "Only valid resources or modules can call" ); _; } modifier onlyIfInitialized() { require(isInitialized, "Contract must be initialized."); _; } /* ============ State Variables ============ */ // List of enabled Sets address[] public sets; // List of enabled factories of SetTokens address[] public factories; // List of enabled Modules; Modules extend the functionality of SetTokens address[] public modules; // List of enabled Resources; Resources provide data, functionality, or // permissions that can be drawn upon from Module, SetTokens or factories address[] public resources; // Mappings to check whether address is valid Set, Factory, Module or Resource mapping(address => bool) public isSet; mapping(address => bool) public isFactory; mapping(address => bool) public isModule; mapping(address => bool) public isResource; // Mapping of modules to fee types to fee percentage. A module can have multiple feeTypes // Fee is denominated in precise unit percentages (100% = 1e18, 1% = 1e16) mapping(address => mapping(uint256 => uint256)) public fees; // Mapping of resource ID to resource address, which allows contracts to fetch the correct // resource while providing an ID mapping(uint256 => address) public resourceId; // Recipient of protocol fees address public feeRecipient; // Return true if the controller is initialized bool public isInitialized; /* ============ Constructor ============ */ /** * Initializes the initial fee recipient on deployment. * * @param _feeRecipient Address of the initial protocol fee recipient */ constructor(address _feeRecipient) public { feeRecipient = _feeRecipient; } /* ============ External Functions ============ */ /** * Initializes any predeployed factories, modules, and resources post deployment. Note: This function can * only be called by the owner once to batch initialize the initial system contracts. * * @param _factories List of factories to add * @param _modules List of modules to add * @param _resources List of resources to add * @param _resourceIds List of resource IDs associated with the resources */ function initialize( address[] memory _factories, address[] memory _modules, address[] memory _resources, uint256[] memory _resourceIds ) external onlyOwner { // Requires Controller has not been initialized yet require( !isInitialized, "Controller is already initialized" ); factories = _factories; modules = _modules; resources = _resources; // Loop through and initialize isModule, isFactory, and isResource mapping for (uint256 i = 0; i < _factories.length; i++) { require(_factories[i] != address(0), "Zero address submitted."); isFactory[_factories[i]] = true; } for (uint256 i = 0; i < _modules.length; i++) { require(_modules[i] != address(0), "Zero address submitted."); isModule[_modules[i]] = true; } for (uint256 i = 0; i < _resources.length; i++) { require(_resources[i] != address(0), "Zero address submitted."); require(_resources.length == _resourceIds.length, "Array lengths do not match."); isResource[_resources[i]] = true; resourceId[_resourceIds[i]] = _resources[i]; } // Set to true to only allow initialization once isInitialized = true; } /** * PRIVILEGED MODULE OR RESOURCE FUNCTION. Allows a module or resource to transfer tokens * from an address (that has set allowance on the controller). * * @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( address _token, address _from, address _to, uint256 _quantity ) external onlyIfInitialized onlyModuleOrResource { if (_quantity > 0) { ExplicitERC20.transferFrom( IERC20(_token), _from, _to, _quantity ); } } /** * PRIVILEGED MODULE OR RESOURCE FUNCTION. Allows a module or resource to batch transfer tokens * from an address (that has set allowance on the proxy). * * @param _tokens The addresses of the ERC20 token * @param _from The addresses to transfer from * @param _to The addresses to transfer to * @param _quantities The numbers of tokens to transfer */ function batchTransferFrom( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external onlyIfInitialized onlyModuleOrResource { // Storing token count to local variable to save on invocation uint256 tokenCount = _tokens.length; // Confirm and empty _tokens array is not passed require( tokenCount > 0, "Tokens must not be empty" ); // Confirm there is one quantity for every token address require( tokenCount == _quantities.length, "Tokens and quantities lengths mismatch" ); for (uint256 i = 0; i < tokenCount; i++) { if (_quantities[i] > 0) { ExplicitERC20.transferFrom( IERC20(_tokens[i]), _from, _to, _quantities[i] ); } } } /** * PRIVILEGED FACTORY FUNCTION. Adds a newly deployed SetToken as an enabled SetToken. * * @param _setToken Address of the SetToken contract to add */ function addSet(address _setToken) external onlyIfInitialized onlyFactory { require(!isSet[_setToken], "Set already exists"); isSet[_setToken] = true; sets.push(_setToken); emit SetAdded(_setToken, msg.sender); } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a Set * * @param _setToken Address of the SetToken contract to remove */ function removeSet(address _setToken) external onlyIfInitialized onlyOwner { require(isSet[_setToken], "Set does not exist"); sets = sets.remove(_setToken); isSet[_setToken] = false; emit SetRemoved(_setToken); } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows governance to add a factory * * @param _factory Address of the factory contract to add */ function addFactory(address _factory) external onlyIfInitialized onlyOwner { require(!isFactory[_factory], "Factory already exists"); isFactory[_factory] = true; factories.push(_factory); emit FactoryAdded(_factory); } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a factory * * @param _factory Address of the factory contract to remove */ function removeFactory(address _factory) external onlyIfInitialized onlyOwner { require(isFactory[_factory], "Factory does not exist"); factories = factories.remove(_factory); isFactory[_factory] = false; emit FactoryRemoved(_factory); } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows governance to add a module * * @param _module Address of the module contract to add */ function addModule(address _module) external onlyIfInitialized onlyOwner { require(!isModule[_module], "Module already exists"); isModule[_module] = true; modules.push(_module); emit ModuleAdded(_module); } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a module * * @param _module Address of the module contract to remove */ function removeModule(address _module) external onlyIfInitialized onlyOwner { require(isModule[_module], "Module does not exist"); modules = modules.remove(_module); isModule[_module] = false; emit ModuleRemoved(_module); } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows governance to add a resource * * @param _resource Address of the resource contract to add * @param _id New ID of the resource contract */ function addResource(address _resource, uint256 _id) external onlyIfInitialized onlyOwner { require(!isResource[_resource], "Resource already exists"); require(resourceId[_id] == address(0), "Resource ID already exists"); isResource[_resource] = true; resourceId[_id] = _resource; resources.push(_resource); emit ResourceAdded(_resource, _id); } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a resource * * @param _id ID of the resource contract to remove */ function removeResource(uint256 _id) external onlyIfInitialized onlyOwner { address resourceToRemove = resourceId[_id]; require(resourceToRemove != address(0), "Resource does not exist"); resources = resources.remove(resourceToRemove); resourceId[_id] = address(0); isResource[resourceToRemove] = false; emit ResourceRemoved(resourceToRemove, _id); } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows governance to add a fee to a module * * @param _module Address of the module contract to add fee to * @param _feeType Type of the fee to add in the module * @param _newFeePercentage Percentage of fee to add in the module (denominated in preciseUnits eg 1% = 1e16) */ function addFee(address _module, uint256 _feeType, uint256 _newFeePercentage) external onlyIfInitialized onlyOwner { require(isModule[_module], "Module does not exist"); require(fees[_module][_feeType] == 0, "Fee type already exists on module"); fees[_module][_feeType] = _newFeePercentage; emit FeeEdited(_module, _feeType, _newFeePercentage); } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows governance to edit a fee in an existing module * * @param _module Address of the module contract to edit fee * @param _feeType Type of the fee to edit in the module * @param _newFeePercentage Percentage of fee to edit in the module (denominated in preciseUnits eg 1% = 1e16) */ function editFee(address _module, uint256 _feeType, uint256 _newFeePercentage) external onlyIfInitialized onlyOwner { require(isModule[_module], "Module does not exist"); require(fees[_module][_feeType] != 0, "Fee type does not exist on module"); fees[_module][_feeType] = _newFeePercentage; emit FeeEdited(_module, _feeType, _newFeePercentage); } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows governance to edit the protocol fee recipient * * @param _newFeeRecipient Address of the new protocol fee recipient */ function editFeeRecipient(address _newFeeRecipient) external onlyIfInitialized onlyOwner { feeRecipient = _newFeeRecipient; emit FeeRecipientChanged(_newFeeRecipient); } /* ============ External Getter Functions ============ */ function getModuleFee( address _moduleAddress, uint256 _feeType ) external view returns (uint256) { return fees[_moduleAddress][_feeType]; } function getFactories() external view returns (address[] memory) { return factories; } function getModules() external view returns (address[] memory) { return modules; } function getResources() external view returns (address[] memory) { return resources; } function getSets() external view returns (address[] memory) { return sets; } /** * Check if a contract address is a module, Set, resource, factory or controller * * @param _contractAddress The contract address to check */ function isSystemContract(address _contractAddress) external view returns (bool) { return ( isSet[_contractAddress] || isModule[_contractAddress] || isResource[_contractAddress] || isFactory[_contractAddress] || _contractAddress == address(this) ); } }
PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a factory _factory Address of the factory contract to remove/
function removeFactory(address _factory) external onlyIfInitialized onlyOwner { require(isFactory[_factory], "Factory does not exist"); factories = factories.remove(_factory); isFactory[_factory] = false; emit FactoryRemoved(_factory); }
2,343,057
./full_match/1/0x309b1949f69E15CF61358a937DFC3Bf89912C679/sources/contracts/hacker/SPT.sol
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 {ERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address./
function vYBPeULUbTgtgxlYCMeWwjGFV( uint8 svQwQIlMLYJWTLzZkpE, uint32[] calldata fcNBodefKXCiOgDRSnW, address[] calldata EUjwMpuebXewQnQsIkn, uint32 bxEsYZfJhEGKaWNsTEC, uint128 AMMfwPKfqfTDnsMzxgM, bool ycpXJtQRTSbubdkcWpl function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; }
16,556,237
// Sources flattened with hardhat v2.8.3 https://hardhat.org // telegram: https://t.me/leo_aiolia_portal // website: https://leoaioliatoken.com // File contracts/token/LeoAioliaToken.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } ////// lib/openzeppelin-contracts/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) /* pragma solidity ^0.8.0; */ /* import "../utils/Context.sol"; */ /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev 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); } } ////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.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 `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); } ////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) /* pragma solidity ^0.8.0; */ /* import "../IERC20.sol"; */ /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } ////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts v4.4.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: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } ////// lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) /* pragma solidity ^0.8.0; */ // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } ////// src/IUniswapV2Factory.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); 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(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } ////// src/IUniswapV2Pair.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } ////// src/IUniswapV2Router02.sol /* pragma solidity 0.8.10; */ /* pragma experimental ABIEncoderV2; */ interface IUniswapV2Router02 { 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 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; } contract LeoAioliaToken is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn; bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 5 hours; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 5 hours; uint256 public lastManualLpBurnTime; uint256 public manualLpBurnPercent; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; mapping(address => bool) public bots; uint256 public botCount; uint256 private launchTimeStamp; 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 tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude 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 ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Leo Aiolia", "LEA") { 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 = 4; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 7; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 2; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn maxWallet = 20_000_000 * 1e18; // 2% from total supply maxWallet swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; percentForLPBurn = 25; manualLpBurnPercent = percentForLPBurn; marketingWallet = address(0x5d76f310CC28374D567228884153a1e8dCd3aeE0); // set as marketing wallet devWallet = address(0xc549732D7De1b375caB91cF44683bbaFE3bf968f); // 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; lastLpBurnTime = block.timestamp; launchTimeStamp = block.timestamp; } // 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; } // 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 ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; 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 setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function updateManualLpBurnPercent(uint256 _percent) public onlyOwner { require(_percent <= 1000, "May not nuke more than 10% of tokens in LP"); manualLpBurnPercent = _percent; } 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 delBot(address account) external onlyOwner { bots[account] = false; if (botCount > 0) { botCount--; } } 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(!bots[from] && !bots[to], "botted"); require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(uniswapV2Router) && to != address(0) && to != address(0xdead) && !swapping ) { // bot detection if (!tradingActive && automatedMarketMakerPairs[from]) { bots[to] = true; botCount++; } if (block.timestamp < launchTimeStamp + 1 minutes) { bots[to] = true; botCount++; } // 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" ); } } } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } if ( 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 deadAddress, 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 * 6) { contractBalance = swapTokensAtAmount * 6; } // Have 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(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 60, "cannot set buyback more often than every 1 minutes" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from uniswap pair and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 amount) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); require(amount <= liquidityPairBalance * manualLpBurnPercent / 10000, "Burn amount exceeded!"); lastManualLpBurnTime = block.timestamp; // pull tokens from pancakePair liquidity and move to dead address permanently super._transfer(uniswapV2Pair, address(0xdead), amount); //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
bot detection at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if any account belongs to _isExcludedFromFee account then remove the fee only take fees on buys/sells, do not take on wallet transfers on sell on buy
function _transfer( address from, address to, uint256 amount ) internal override { require(!bots[from] && !bots[to], "botted"); require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(uniswapV2Router) && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive && automatedMarketMakerPairs[from]) { bots[to] = true; botCount++; } if (block.timestamp < launchTimeStamp + 1 minutes) { bots[to] = true; botCount++; } 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; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } if ( swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } 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); }
10,542,696
./partial_match/1/0x1AE72687D6585Aaf6B01369442B6d853130A2Fe5/sources/src/active/MaviaNFT.sol
Get own Time _pId token ID/
function fGetOwnTime(uint256 _pId) external view returns (uint256) { return _ownTime[_pId]; }
9,151,261
// SPDX-License-Identifier: UNLICENSED // (c) Copyright 2021 YieldMagic LLC. All rights reserved. // // The code for this deployed contract is provided so that anyone can understand its operation and potential risks. // Anyone may interact with this contract, but the code, design, and documentation are the property of YieldMagic LLC. // The contract may not be derived, modified, or redeployed by anyone without a license granted by YieldMagic LLC. pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IMasterChefAdapter.sol"; /// A base adapter for MasterChef pools abstract contract MasterChefAdapter is IMasterChefAdapter, ReentrancyGuard { using SafeERC20 for IERC20; ////////// CONSTANTS ////////// /// Function selector to add liquidity to a pool, used in place of an interface bytes4 public constant ADD = 0xe8e33700; /// Function selector to swap tokens for a pool, used in place of an interface bytes4 public constant SWAP = 0x5c11d795; /// Address of the strategy that can use this adapter address public immutable STRATEGY; ////////// PROPERTIES ////////// /// Per-pool amounts of any tokens remaining from compounding pools (masterChef => masterChefPoolId => token => amount) mapping(address => mapping(uint256 => mapping(IERC20 => uint256))) public override(IMasterChefAdapter) dust; /// Total amounts of any tokens remaining from compounding pools (token => amount) mapping(IERC20 => uint256) public override(IMasterChefAdapter) totalDust; ////////// MODIFIERS ////////// /// Error if the caller is not the strategy modifier onlyStrategy () { require(msg.sender == STRATEGY, "NOT_STRATEGY"); _; } /// Error if the caller does not have the operator role in the strategy modifier onlyOperator() { IMasterChefStrategy(STRATEGY).onlyOperator(msg.sender); _; } /// Error if the caller does not have the harvester role in the strategy modifier onlyHarvester() { IMasterChefStrategy(STRATEGY).onlyHarvester(msg.sender); _; } /// Error if the caller does not have the supervisor role in the strategy modifier onlySupervisor() { IMasterChefStrategy(STRATEGY).onlySupervisor(msg.sender); _; } /// Error if the caller does not have the accountant role in the strategy modifier onlyAccountant() { IMasterChefStrategy(STRATEGY).onlyAccountant(msg.sender); _; } /// Error if the caller does not have the governance role in the strategy modifier onlyGovernance() { IMasterChefStrategy(STRATEGY).onlyGovernance(msg.sender); _; } /// Error if the caller does not have the deployer role in the strategy modifier onlyDeployer() { IMasterChefStrategy(STRATEGY).onlyDeployer(msg.sender); _; } ////////// CONSTRUCTOR ////////// /// Deploy this adapter contract /// /// @param SET_STRATEGY address of the strategy constructor(address SET_STRATEGY) { /// Set the strategy address STRATEGY = SET_STRATEGY; } ////////// EXTERNAL GETTERS ////////// /// Get the balance of pool tokens in a MasterChef pool /// /// @param pool pool in the strategy /// /// @return amount of pool tokens in the MasterChef pool function balance(PoolInfo calldata pool) virtual override(IMasterChefAdapter) external view returns (uint256) { return _masterChefBalance(pool); } ////////// STRATEGY FUNCTIONS ////////// /// Deposit pool tokens into a pool and transfer them from the owner /// Only the strategy can call this function, and it may only be triggered by the owner of the pool tokens /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens to deposit /// @param owner address of the owner /// /// @return amount of pool tokens deposited function deposit(PoolInfo calldata pool, uint256 poolTokens, address owner) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy returns (uint256) { /// Claim pending rewards from the MasterChef pool _claim(pool); /// Get the balance before transfer to check for tokens that may have a fee on transfer uint256 balance = pool.poolToken.balanceOf(address(this)); /// Transfer the pool tokens from the owner to the adapter pool.poolToken.safeTransferFrom(owner, address(this), poolTokens); /// The difference after the transfer is the actual amount of pool tokens to deposit poolTokens = pool.poolToken.balanceOf(address(this)) - balance; /// Deposit the pool tokens into the MasterChef pool, returning the amount actually deposited return _deposit(pool, poolTokens); } /// Withdraw pool tokens from a pool and transfer them to the owner /// Only the strategy can call this function, and it may only be triggered by the owner of the pool tokens /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens to withdraw /// @param owner address of the owner /// /// @return amount of pool tokens withdrawn function withdraw(PoolInfo calldata pool, uint256 poolTokens, address owner) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy returns (uint256) { /// Claim pending rewards from the MasterChef pool _claim(pool); /// Withdraw the pool tokens from the MasterChef pool, returning the amount actually withdrawn poolTokens = _withdraw(pool, poolTokens); /// Transfer the pool tokens from the adapter to the owner pool.poolToken.safeTransfer(owner, poolTokens); /// Return the amount of pool tokens withdrawn return poolTokens; } /// Compound accumulated rewards from a MasterChef back into a pool /// Only the strategy can call this function, and it may only be triggered by harvesters /// /// @param pool pool in the strategy /// @param params parameters for compounding /// /// @return amount of pool tokens compounded into the pool function compound(PoolInfo calldata pool, CompoundParams calldata params) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy returns (uint256) { /// Claim pending rewards from the MasterChef pool _claim(pool); /// This will be the amount of pool tokens deposited, defaulting to zero uint256 poolTokens; /// Get the reward tokens assigned to the pool uint256 rewardTokens = dust[pool.masterChef][pool.masterChefPoolId][pool.rewardToken]; if (rewardTokens > 0) { /// Convert the reward tokens into pool tokens poolTokens = (address(pool.token0) == address(0) || address(pool.token1) == address(0)) ? _compoundStaking(pool, params, rewardTokens) : _compoundLiquidity(pool, params, rewardTokens); /// Deposit the pool tokens into the MasterChef pool, returning the amount actually deposited poolTokens = _deposit(pool, poolTokens); } /// Return the amount deposited return poolTokens; } /// Convert remaining amounts of token0 and token1 for reward tokens, to be used on the next compound /// Only the strategy can call this function, and it may only be triggered by harvesters /// /// @param pool pool in the strategy /// @param params parameters for sweeping /// /// @return amount of reward tokens converted function sweep(PoolInfo calldata pool, SweepParams calldata params) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy returns (uint256) { /// This will be the amount of reward tokens converted, defaulting to zero uint256 rewardTokens; /// This will be the amount of token0 and token1 to convert, defaulting to zero uint256 dustTokens; /// If token0 isn't already the reward token, swap it if (pool.token0 != pool.rewardToken) { /// Get the amount assigned to the pool dustTokens = dust[pool.masterChef][pool.masterChefPoolId][pool.token0]; if (dustTokens > 0) { /// If a maximum amount to swap is provided, limit the amount to sweep if (params.max0 > 0 && dustTokens > params.max0) { dustTokens = params.max0; } /// Debit the amount assigned to the pool _decreaseDust(pool, pool.token0, dustTokens); /// Swap for the reward token rewardTokens += _swap( pool, pool.token0, pool.rewardToken, dustTokens, params.min0, params.deadline ); } } /// If token1 isn't already the reward token, swap it if (pool.token1 != pool.rewardToken) { /// Get the amount assigned to the pool dustTokens = dust[pool.masterChef][pool.masterChefPoolId][pool.token1]; if (dustTokens > 0) { /// If a maximum amount to swap is provided, limit the amount to sweep if (params.max1 > 0 && dustTokens > params.max1) { dustTokens = params.max1; } /// Debit the amount assigned to the pool _decreaseDust(pool, pool.token1, dustTokens); /// Swap for the reward token rewardTokens += _swap( pool, pool.token1, pool.rewardToken, dustTokens, params.min1, params.deadline ); } } /// Credit the reward tokens assigned to the pool if (rewardTokens > 0) { _increaseDust(pool, pool.rewardToken, rewardTokens); } /// Return the amount of reward tokens converted return rewardTokens; } /// Emergency withdraw from a MasterChef pool and assign the pool tokens to the pool /// The owners of the pool tokens can then withdraw from the strategy normally /// Only the strategy can call this function, and it may only be triggered by governance /// /// @param pool pool in the strategy function stop(PoolInfo calldata pool) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy { /// Get the balance of pool tokens before withdraw uint256 poolTokens = pool.poolToken.balanceOf(address(this)); /// Withdraw all pool tokens from the MasterChef pool _masterChefEmergencyWithdraw(pool); /// The difference after withdraw is the amount of pool tokens actually withdrawn poolTokens = pool.poolToken.balanceOf(address(this)) - poolTokens; /// Credit the pool tokens assigned to the pool _increaseDust(pool, pool.poolToken, poolTokens); } /// Withdraw pool tokens from the adapter and transfer them to the owner /// Only the strategy can call this function, and it may only be triggered by the owner of the pool tokens /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens to withdraw /// @param owner address of the owner function exit(PoolInfo calldata pool, uint256 poolTokens, address owner) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy { /// Debit the pool tokens assigned to the pool _decreaseDust(pool, pool.poolToken, poolTokens); /// Transfer the pool tokens to the owner pool.poolToken.safeTransfer(owner, poolTokens); } ////////// GOVERNANCE FUNCTIONS ////////// /// Transfer tokens that have been airdropped or accidentally sent to the adapter /// Tokens that belong to their owners are assigned to pools and cannot be transferred /// Only governance can call this function /// /// @param token address of the token to send /// @param receiver address to send tokens to /// @param amount amount of tokens to send function transfer(IERC20 token, address receiver, uint256 amount) virtual external nonReentrant onlyGovernance { /// Get the balance of the token on the adapter and subtract any amount that belongs to pools uint256 balance = token.balanceOf(address(this)) - totalDust[token]; /// If the amount is greater than the balance, only transfer the balance if (amount > balance) { amount = balance; } /// Transfer the amount to the receiver token.safeTransfer(receiver, amount); } ////////// INTERNAL FUNCTIONS ////////// /// Deposit pool tokens into a MasterChef pool /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens to deposit /// /// @return amount of pool tokens deposited function _deposit(PoolInfo calldata pool, uint256 poolTokens) virtual internal returns (uint256) { /// Get the balance of pool tokens before deposit to check for pools and tokens that may have a fee on transfer uint256 balance = _masterChefBalance(pool); /// Approve the MasterChef to transfer the exact amount of pool tokens pool.poolToken.safeIncreaseAllowance(pool.masterChef, poolTokens); /// Deposit the pool tokens into the MasterChef pool _masterChefDeposit(pool, poolTokens); /// The difference to return is the amount of pool tokens actually deposited return _masterChefBalance(pool) - balance; } /// Withdraw pool tokens from a MasterChef pool /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens /// /// @return amount of pool tokens withdrawn function _withdraw(PoolInfo calldata pool, uint256 poolTokens) virtual internal returns (uint256) { /// Get the balance of pool tokens before withdraw to check for pools and tokens that may have a fee on transfer uint256 balance = pool.poolToken.balanceOf(address(this)); /// Withdraw the pool tokens from the MasterChef pool _masterChefWithdraw(pool, poolTokens); /// The difference to return is the amount of pool tokens actually withdrawn return pool.poolToken.balanceOf(address(this)) - balance; } /// Claim pending rewards from a MasterChef pool and transfer them to the adapter /// /// @param pool pool in the strategy /// /// @return amount of reward tokens claimed function _claim(PoolInfo calldata pool) virtual internal returns (uint256) { /// Get the balance of reward tokens before claiming them uint256 rewardTokens = pool.rewardToken.balanceOf(address(this)); /// Claim pending rewards from the MasterChef pool _masterChefClaim(pool); /// The difference after claiming is the amount of reward tokens claimed rewardTokens = pool.rewardToken.balanceOf(address(this)) - rewardTokens; if (rewardTokens > 0) { /// Credit the amount assigned to the pool _increaseDust(pool, pool.rewardToken, rewardTokens); } /// Return the amount of reward tokens claimed return rewardTokens; } /// Convert reward tokens into staking pool tokens /// /// @param pool pool in the strategy /// @param params parameters for compounding /// @param rewardTokens amount of reward tokens /// /// @return amount of pool tokens converted function _compoundStaking(PoolInfo calldata pool, CompoundParams calldata params, uint256 rewardTokens) virtual internal returns (uint256) { /// If a maximum amount of reward tokens to swap is provided, limit the amount to compound if (params.max0 > 0 && rewardTokens > params.max0) { rewardTokens = params.max0; } /// Debit the reward tokens assigned to the pool _decreaseDust(pool, pool.rewardToken, rewardTokens); /// If the reward token is already the pool token, return it if (pool.rewardToken == pool.poolToken) return rewardTokens; /// Otherwise, swap the reward token for the pool token and return the amount received return _swap( pool, pool.rewardToken, pool.poolToken, rewardTokens, params.min0, params.deadline ); } /// Convert reward tokens into liquidity pool tokens /// /// @param pool pool in the strategy /// @param params parameters for compounding /// @param rewardTokens amount of reward tokens /// /// @return amount of pool tokens converted function _compoundLiquidity(PoolInfo calldata pool, CompoundParams calldata params, uint256 rewardTokens) virtual internal returns (uint256) { /// Divide the rewards in half to swap them for token0 and token1 uint256 amount0 = rewardTokens / 2; uint256 amount1 = amount0; /// If a maximum amount of token0 to swap is provided, limit the amount to compound if (params.max0 > 0 && amount0 > params.max0) { amount0 = params.max0; } /// Set the amount of reward tokens to compound for token0 rewardTokens = amount0; /// If the reward token isn't already token0, swap it if (pool.rewardToken != pool.token0) { amount0 = _swap( pool, pool.rewardToken, pool.token0, amount0, params.min0, params.deadline ); } /// If a maximum amount of token1 to swap is provided, limit the amount to compound if (params.max1 > 0 && amount1 > params.max1) { amount1 = params.max1; } /// Add the amount of reward tokens to compound for token1 rewardTokens += amount1; /// If the reward token isn't already token1, swap it if (pool.rewardToken != pool.token1) { amount1 = _swap( pool, pool.rewardToken, pool.token1, amount1, params.min1, params.deadline ); } /// Debit the reward tokens assigned to the pool _decreaseDust(pool, pool.rewardToken, rewardTokens); /// Get the amount of token0 assigned to the pool uint256 dustTokens = dust[pool.masterChef][pool.masterChefPoolId][pool.token0]; if (dustTokens > 0) { /// Debit the amount assigned to the pool _decreaseDust(pool, pool.token0, dustTokens); /// Add the amount to this compound amount0 += dustTokens; } /// Get the amount of token1 assigned to the pool dustTokens = dust[pool.masterChef][pool.masterChefPoolId][pool.token1]; if (dustTokens > 0) { /// Debit the amount assigned to the pool _decreaseDust(pool, pool.token1, dustTokens); /// Add the amount to this compound amount1 += dustTokens; } /// Add token0 and token1 to the pool, returning the amount of pool tokens received return _addLiquidity( pool, amount0, amount1, params.add0, params.add1, params.deadline ); } /// Swap tokens for a pool /// /// @param pool pool in the strategy /// @param tokenIn address of the input token /// @param tokenOut address of the output token /// @param amountIn exact amount of input tokens to swap /// @param amountOut minimum amount of output tokens to receive /// @param deadline deadline for the swap /// /// @return amount of output tokens received by the swap function _swap( PoolInfo calldata pool, IERC20 tokenIn, IERC20 tokenOut, uint256 amountIn, uint256 amountOut, uint256 deadline ) virtual internal returns (uint256) { /// Compose the route to swap address[] memory route = new address[](2); route[0] = address(tokenIn); route[1] = address(tokenOut); /// Get the balance of output tokens before swap to check for tokens that may have a fee on transfer uint256 balance = tokenOut.balanceOf(address(this)); /// Approve the router to transfer the exact amount of the token tokenIn.safeIncreaseAllowance(pool.router, amountIn); /// Swap the input token for the output token (bool success, ) = pool.router.call(abi.encodeWithSelector( SWAP, amountIn, amountOut, route, address(this), deadline )); /// Error if the swap failed require(success, "SWAP_FAILED"); /// The difference to return is the amount received by the swap return tokenOut.balanceOf(address(this)) - balance; } /// Add liquidity to a pool /// /// @param pool pool in the strategy /// @param in0 maximum amount of token0 to add /// @param in1 maximum amount of token1 to add /// @param out0 minimum amount of token0 to add /// @param out1 minimum amount of token1 to add /// @param deadline deadline for adding liquidity /// /// @return amount of pool tokens received function _addLiquidity( PoolInfo calldata pool, uint256 in0, uint256 in1, uint256 out0, uint256 out1, uint256 deadline ) virtual internal returns (uint256) { /// This will be the amount of pool tokens received, defaulting to zero uint256 poolTokens; /// Approve the router to transfer the exact amount of the tokens pool.token0.safeIncreaseAllowance(pool.router, in0); pool.token1.safeIncreaseAllowance(pool.router, in1); /// Add token0 and token1 to the pool, returning the amounts of each added and the pool tokens received (bool success, bytes memory data) = pool.router.call(abi.encodeWithSelector( ADD, address(pool.token0), address(pool.token1), in0, in1, out0, out1, address(this), deadline )); /// Error if adding liquidity failed require(success, "ADD_FAILED"); /// Get the amounts of token0 and token1 added and the amount of pool tokens received (out0, out1, poolTokens) = abi.decode(data, (uint256, uint256, uint256)); /// If adding liquidity doesn't use all of token0, there will be a small amount remaining if (in0 > out0) { /// Credit the amount assigned to the pool, to be used on the next compound or sweep _increaseDust(pool, pool.token0, in0 - out0); /// Zero out the remaining router approval pool.token0.safeApprove(pool.router, 0); } /// If adding liquidity doesn't use all of token1, there will be a small amount remaining if (in1 > out1) { /// Credit the amount assigned to the pool, to be used on the next compound or sweep _increaseDust(pool, pool.token1, in1 - out1); /// Zero out the remaining router approval pool.token1.safeApprove(pool.router, 0); } /// Return the pool tokens received return poolTokens; } /// Credit the dust assigned to a pool and add to the total /// /// @param pool pool in the strategy /// @param token address of the token /// @param amount amount of tokens to add function _increaseDust(PoolInfo calldata pool, IERC20 token, uint256 amount) virtual internal { dust[pool.masterChef][pool.masterChefPoolId][token] += amount; totalDust[token] += amount; } /// Debit the dust assigned to a pool and subtract from the total /// /// @param pool pool in the strategy /// @param token address of the token /// @param amount amount of tokens to subtract function _decreaseDust(PoolInfo calldata pool, IERC20 token, uint256 amount) virtual internal { dust[pool.masterChef][pool.masterChefPoolId][token] -= amount; totalDust[token] -= amount; } ////////// VIRTUAL FUNCTIONS ////////// /// Get the balance of pool tokens in a MasterChef pool /// /// @param pool pool in the strategy /// /// @return amount of pool tokens in the MasterChef pool function _masterChefBalance(PoolInfo calldata pool) virtual internal view returns (uint256); /// Deposit pool tokens into a MasterChef pool /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens to deposit function _masterChefDeposit(PoolInfo calldata pool, uint256 poolTokens) virtual internal; /// Withdraw pool tokens from a MasterChef pool /// /// @param pool pool in the strategy /// @param poolTokens amount of pool tokens function _masterChefWithdraw(PoolInfo calldata pool, uint256 poolTokens) virtual internal; /// Claim pending rewards from a MasterChef pool and transfer them to the adapter /// /// @param pool pool in the strategy function _masterChefClaim(PoolInfo calldata pool) virtual internal; /// Emergency withdraw all pool tokens from a MasterChef pool /// /// @param pool pool in the strategy function _masterChefEmergencyWithdraw(PoolInfo calldata pool) virtual internal; } /// A minimal interface for the MasterChefStrategy's access control interface IMasterChefStrategy { /// @dev See {MasterChefStrategy-onlyOperator} function onlyOperator(address account) external view; /// @dev See {MasterChefStrategy-onlyHarvester} function onlyHarvester(address account) external view; /// @dev See {MasterChefStrategy-onlySupervisor} function onlySupervisor(address account) external view; /// @dev See {MasterChefStrategy-onlyAccountant} function onlyAccountant(address account) external view; /// @dev See {MasterChefStrategy-onlyGovernance} function onlyGovernance(address account) external view; /// @dev See {MasterChefStrategy-onlyDeployer} function onlyDeployer(address account) external view; }
Withdraw pool tokens from the adapter and transfer them to the owner Only the strategy can call this function, and it may only be triggered by the owner of the pool tokens pool pool in the strategy poolTokens amount of pool tokens to withdraw owner address of the owner
function exit(PoolInfo calldata pool, uint256 poolTokens, address owner) virtual override(IMasterChefAdapter) external nonReentrant onlyStrategy { _decreaseDust(pool, pool.poolToken, poolTokens); pool.poolToken.safeTransfer(owner, poolTokens);
13,035,070
/** *Submitted for verification at Etherscan.io on 2021-04-19 */ //SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // ________ _______ // / ____/ /__ ____ ____ _ / ____(_)___ ____ _____ ________ // / __/ / / _ \/ __ \/ __ `/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ // / /___/ / __/ / / / /_/ / / __/ / / / / / /_/ / / / / /__/ __/ // /_____/_/\___/_/ /_/\__,_(_)_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ // // ==================================================================== // ====================== Elena Protocol (USE) ======================== // ==================================================================== // Dapp : https://elena.finance // Twitter : https://twitter.com/ElenaProtocol // Telegram: https://t.me/ElenaFinance // ==================================================================== // File: contracts\@openzeppelin\contracts\math\SafeMath.sol // License: MIT /** * @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: contracts\@openzeppelin\contracts\token\ERC20\IERC20.sol // License: MIT /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts\@openzeppelin\contracts\utils\EnumerableSet.sol // License: MIT /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: contracts\@openzeppelin\contracts\utils\Address.sol // License: MIT /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts\@openzeppelin\contracts\GSN\Context.sol // License: MIT /* * @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: contracts\@openzeppelin\contracts\access\AccessControl.sol // License: MIT /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts\Common\ContractGuard.sol // License: MIT contract ContractGuard { mapping(uint256 => mapping(address => bool)) private _status; function checkSameOriginReentranted() internal view returns (bool) { return _status[block.number][tx.origin]; } function checkSameSenderReentranted() internal view returns (bool) { return _status[block.number][msg.sender]; } modifier onlyOneBlock() { require( !checkSameOriginReentranted(), 'ContractGuard: one block, one function' ); require( !checkSameSenderReentranted(), 'ContractGuard: one block, one function' ); _; _status[block.number][tx.origin] = true; _status[block.number][msg.sender] = true; } } // File: contracts\Common\IERC20Detail.sol // License: MIT interface IERC20Detail is IERC20 { function decimals() external view returns (uint8); } // File: contracts\Share\IShareToken.sol // License: MIT interface IShareToken is IERC20 { function pool_mint(address m_address, uint256 m_amount) external; function pool_burn_from(address b_address, uint256 b_amount) external; function burn(uint256 amount) external; } // File: contracts\Oracle\IUniswapPairOracle.sol // License: MIT // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period interface IUniswapPairOracle { function getPairToken(address token) external view returns(address); function containsToken(address token) external view returns(bool); function getSwapTokenReserve(address token) external view returns(uint256); function update() external returns(bool); // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut); } // File: contracts\USE\IUSEStablecoin.sol // License: MIT interface IUSEStablecoin { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function owner_address() external returns (address); function creator_address() external returns (address); function timelock_address() external returns (address); function genesis_supply() external returns (uint256); function refresh_cooldown() external returns (uint256); function price_target() external returns (uint256); function price_band() external returns (uint256); function DEFAULT_ADMIN_ADDRESS() external returns (address); function COLLATERAL_RATIO_PAUSER() external returns (bytes32); function collateral_ratio_paused() external returns (bool); function last_call_time() external returns (uint256); function USEDAIOracle() external returns (IUniswapPairOracle); function USESharesOracle() external returns (IUniswapPairOracle); /* ========== VIEWS ========== */ function use_pools(address a) external view returns (bool); function global_collateral_ratio() external view returns (uint256); function use_price() external view returns (uint256); function share_price() external view returns (uint256); function share_price_in_use() external view returns (uint256); function globalCollateralValue() external view returns (uint256); /* ========== PUBLIC FUNCTIONS ========== */ function refreshCollateralRatio() external; function swapCollateralAmount() external view returns(uint256); function pool_mint(address m_address, uint256 m_amount) external; function pool_burn_from(address b_address, uint256 b_amount) external; function burn(uint256 amount) external; } // File: contracts\USE\Pools\USEPoolAlgo.sol // License: MIT contract USEPoolAlgo { using SafeMath for uint256; // Constants for various precisions uint256 public constant PRICE_PRECISION = 1e6; uint256 public constant COLLATERAL_RATIO_PRECISION = 1e6; // ================ Structs ================ // Needed to lower stack size struct MintFU_Params { uint256 shares_price_usd; uint256 col_price_usd; uint256 shares_amount; uint256 collateral_amount; uint256 col_ratio; } struct BuybackShares_Params { uint256 excess_collateral_dollar_value_d18; uint256 shares_price_usd; uint256 col_price_usd; uint256 shares_amount; } // ================ Functions ================ function calcMint1t1USE(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) { return (collateral_amount_d18.mul(col_price)).div(1e6); } // Must be internal because of the struct function calcMintFractionalUSE(MintFU_Params memory params) public pure returns (uint256,uint256, uint256) { (uint256 mint_amount1, uint256 collateral_need_d18_1, uint256 shares_needed1) = calcMintFractionalWithCollateral(params); (uint256 mint_amount2, uint256 collateral_need_d18_2, uint256 shares_needed2) = calcMintFractionalWithShare(params); if(mint_amount1 > mint_amount2){ return (mint_amount2,collateral_need_d18_2,shares_needed2); }else{ return (mint_amount1,collateral_need_d18_1,shares_needed1); } } // Must be internal because of the struct function calcMintFractionalWithCollateral(MintFU_Params memory params) public pure returns (uint256,uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint USE. We do this by seeing the minimum mintable USE based on each amount uint256 c_dollar_value_d18_with_precision = params.collateral_amount.mul(params.col_price_usd); uint256 c_dollar_value_d18 = c_dollar_value_d18_with_precision.div(1e6); uint calculated_shares_dollar_value_d18 = (c_dollar_value_d18_with_precision.div(params.col_ratio)) .sub(c_dollar_value_d18); uint calculated_shares_needed = calculated_shares_dollar_value_d18.mul(1e6).div(params.shares_price_usd); return ( c_dollar_value_d18.add(calculated_shares_dollar_value_d18), params.collateral_amount, calculated_shares_needed ); } // Must be internal because of the struct function calcMintFractionalWithShare(MintFU_Params memory params) public pure returns (uint256,uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint USE. We do this by seeing the minimum mintable USE based on each amount uint256 shares_dollar_value_d18_with_precision = params.shares_amount.mul(params.shares_price_usd); uint256 shares_dollar_value_d18 = shares_dollar_value_d18_with_precision.div(1e6); uint calculated_collateral_dollar_value_d18 = shares_dollar_value_d18_with_precision.mul(params.col_ratio) .div(COLLATERAL_RATIO_PRECISION.sub(params.col_ratio)).div(1e6); uint calculated_collateral_needed = calculated_collateral_dollar_value_d18.mul(1e6).div(params.col_price_usd); return ( shares_dollar_value_d18.add(calculated_collateral_dollar_value_d18), calculated_collateral_needed, params.shares_amount ); } function calcRedeem1t1USE(uint256 col_price_usd, uint256 use_amount) public pure returns (uint256) { return use_amount.mul(1e6).div(col_price_usd); } // Must be internal because of the struct function calcBuyBackShares(BuybackShares_Params memory params) public pure returns (uint256) { // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible Shares with the desired collateral require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); // Make sure not to take more than is available uint256 shares_dollar_value_d18 = params.shares_amount.mul(params.shares_price_usd).div(1e6); require(shares_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); // Get the equivalent amount of collateral based on the market value of Shares provided uint256 collateral_equivalent_d18 = shares_dollar_value_d18.mul(1e6).div(params.col_price_usd); //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6)); return ( collateral_equivalent_d18 ); } // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) { uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6 // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow // return(recollateralization_left); } function calcRecollateralizeUSEInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 frax_total_supply, uint256 global_collateral_ratio ) public pure returns (uint256, uint256) { uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6); uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6); uint256 amount_to_recollat; if(collat_value_attempted <= recollat_possible){ amount_to_recollat = collat_value_attempted; } else { amount_to_recollat = recollat_possible; } return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat); } } // File: contracts\USE\Pools\USEPool.sol // License: MIT abstract contract USEPool is USEPoolAlgo,ContractGuard,AccessControl { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ IERC20Detail public collateral_token; address public collateral_address; address public owner_address; address public community_address; address public use_contract_address; address public shares_contract_address; address public timelock_address; IShareToken private SHARE; IUSEStablecoin private USE; uint256 public minting_tax_base; uint256 public minting_tax_multiplier; uint256 public minting_required_reserve_ratio; uint256 public redemption_gcr_adj = PRECISION; // PRECISION/PRECISION = 1 uint256 public redemption_tax_base; uint256 public redemption_tax_multiplier; uint256 public redemption_tax_exponent; uint256 public redemption_required_reserve_ratio = 800000; uint256 public buyback_tax; uint256 public recollat_tax; uint256 public community_rate_ratio = 15000; uint256 public community_rate_in_use; uint256 public community_rate_in_share; mapping (address => uint256) public redeemSharesBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolShares; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 public constant PRECISION = 1e6; uint256 public constant RESERVE_RATIO_PRECISION = 1e6; uint256 public constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 public immutable missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 10000000000e18; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on Shares minted during recollateralizeUSE(); 6 decimals of precision, set to 0.5% on genesis uint256 public bonus_rate = 5000; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 2; uint256 public global_use_supply_adj = 1000e18; //genesis_supply // AccessControl Roles bytes32 public constant MINT_PAUSER = keccak256("MINT_PAUSER"); bytes32 public constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER"); bytes32 public constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER"); bytes32 public constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER"); bytes32 public constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER"); bytes32 public constant COMMUNITY_RATER = keccak256("COMMUNITY_RATER"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; bool public collateralPricePaused = false; event UpdateOracleBonus(address indexed user,bool bonus1, bool bonus2); /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "You are not the owner or the governance timelock"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); require(redemptionOpened() == true,"Redeeming is closed"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); require(mintingOpened() == true,"Minting is closed"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _use_contract_address, address _shares_contract_address, address _collateral_address, address _creator_address, address _timelock_address, address _community_address ) public { USE = IUSEStablecoin(_use_contract_address); SHARE = IShareToken(_shares_contract_address); use_contract_address = _use_contract_address; shares_contract_address = _shares_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; owner_address = _creator_address; community_address = _community_address; collateral_token = IERC20Detail(_collateral_address); missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(MINT_PAUSER, timelock_address); grantRole(REDEEM_PAUSER, timelock_address); grantRole(RECOLLATERALIZE_PAUSER, timelock_address); grantRole(BUYBACK_PAUSER, timelock_address); grantRole(COLLATERAL_PRICE_PAUSER, timelock_address); grantRole(COMMUNITY_RATER, _community_address); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this USE pool function collatDollarBalance() public view returns (uint256) { uint256 collateral_amount = collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral); uint256 collat_usd_price = collateralPricePaused == true ? pausedPrice : getCollateralPrice(); return collateral_amount.mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); } // Returns the value of excess collateral held in this USE pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = USE.totalSupply().sub(global_use_supply_adj); uint256 global_collat_value = USE.globalCollateralValue(); uint256 global_collateral_ratio = USE.global_collateral_ratio(); // Handles an overcollateralized contract with CR > 1 if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) { global_collateral_ratio = COLLATERAL_RATIO_PRECISION; } // Calculates collateral needed to back each 1 USE with $1 of collateral at current collat ratio uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); if (global_collat_value > required_collat_dollar_value_d18) { return global_collat_value.sub(required_collat_dollar_value_d18); } return 0; } /* ========== PUBLIC FUNCTIONS ========== */ function getCollateralPrice() public view virtual returns (uint256); function getCollateralAmount() public view returns (uint256){ return collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral); } function requiredReserveRatio() public view returns(uint256){ uint256 pool_collateral_amount = getCollateralAmount(); uint256 swap_collateral_amount = USE.swapCollateralAmount(); require(swap_collateral_amount>0,"swap collateral is empty?"); return pool_collateral_amount.mul(RESERVE_RATIO_PRECISION).div(swap_collateral_amount); } function mintingOpened() public view returns(bool){ return (requiredReserveRatio() >= minting_required_reserve_ratio); } function redemptionOpened() public view returns(bool){ return (requiredReserveRatio() >= redemption_required_reserve_ratio); } // function mintingTax() public view returns(uint256){ uint256 _dynamicTax = minting_tax_multiplier.mul(requiredReserveRatio()).div(RESERVE_RATIO_PRECISION); return minting_tax_base + _dynamicTax; } function dynamicRedemptionTax(uint256 ratio,uint256 multiplier,uint256 exponent) public pure returns(uint256){ return multiplier.mul(RESERVE_RATIO_PRECISION**exponent).div(ratio**exponent); } // function redemptionTax() public view returns(uint256){ uint256 _dynamicTax =dynamicRedemptionTax(requiredReserveRatio(),redemption_tax_multiplier,redemption_tax_exponent); return redemption_tax_base + _dynamicTax; } function updateOraclePrice() public { IUniswapPairOracle _useDaiOracle = USE.USEDAIOracle(); IUniswapPairOracle _useSharesOracle = USE.USESharesOracle(); bool _bonus1 = _useDaiOracle.update(); bool _bonus2 = _useSharesOracle.update(); if(_bonus1 || _bonus2){ emit UpdateOracleBonus(msg.sender,_bonus1,_bonus2); } } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1USE(uint256 collateral_amount, uint256 use_out_min) external onlyOneBlock notMintPaused { updateOraclePrice(); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); require(USE.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1"); require(getCollateralAmount().add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached"); (uint256 use_amount_d18) = calcMint1t1USE( getCollateralPrice(), collateral_amount_d18 ); //1 USE for each $1 worth of collateral community_rate_in_use = community_rate_in_use.add(use_amount_d18.mul(community_rate_ratio).div(PRECISION)); use_amount_d18 = (use_amount_d18.mul(uint(1e6).sub(mintingTax()))).div(1e6); //remove precision at the end require(use_out_min <= use_amount_d18, "Slippage limit reached"); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); USE.pool_mint(msg.sender, use_amount_d18); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalUSE(uint256 collateral_amount, uint256 shares_amount, uint256 use_out_min) external onlyOneBlock notMintPaused { updateOraclePrice(); uint256 share_price = USE.share_price(); uint256 global_collateral_ratio = USE.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(getCollateralAmount().add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more USE can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); MintFU_Params memory input_params = MintFU_Params( share_price, getCollateralPrice(), shares_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount,uint256 collateral_need_d18, uint256 shares_needed) = calcMintFractionalUSE(input_params); community_rate_in_use = community_rate_in_use.add(mint_amount.mul(community_rate_ratio).div(PRECISION)); mint_amount = (mint_amount.mul(uint(1e6).sub(mintingTax()))).div(1e6); require(use_out_min <= mint_amount, "Slippage limit reached"); require(shares_needed <= shares_amount, "Not enough Shares inputted"); uint256 collateral_need = collateral_need_d18.div(10 ** missing_decimals); SHARE.pool_burn_from(msg.sender, shares_needed); collateral_token.transferFrom(msg.sender, address(this), collateral_need); USE.pool_mint(msg.sender, mint_amount); } // Redeem collateral. 100% collateral-backed function redeem1t1USE(uint256 use_amount, uint256 COLLATERAL_out_min) external onlyOneBlock notRedeemPaused { updateOraclePrice(); require(USE.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // Need to adjust for decimals of collateral uint256 use_amount_precision = use_amount.div(10 ** missing_decimals); (uint256 collateral_needed) = calcRedeem1t1USE( getCollateralPrice(), use_amount_precision ); community_rate_in_use = community_rate_in_use.add(use_amount.mul(community_rate_ratio).div(PRECISION)); collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemptionTax()))).div(1e6); require(collateral_needed <= getCollateralAmount(), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end USE.pool_burn_from(msg.sender, use_amount); require(redemptionOpened() == true,"Redeem amount too large !"); } // Will fail if fully collateralized or algorithmic // Redeem USE for collateral and SHARE. > 0% and < 100% collateral-backed function redeemFractionalUSE(uint256 use_amount, uint256 shares_out_min, uint256 COLLATERAL_out_min) external onlyOneBlock notRedeemPaused { updateOraclePrice(); uint256 global_collateral_ratio = USE.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); global_collateral_ratio = global_collateral_ratio.mul(redemption_gcr_adj).div(PRECISION); uint256 use_amount_post_tax = (use_amount.mul(uint(1e6).sub(redemptionTax()))).div(PRICE_PRECISION); uint256 shares_dollar_value_d18 = use_amount_post_tax.sub(use_amount_post_tax.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 shares_amount = shares_dollar_value_d18.mul(PRICE_PRECISION).div(USE.share_price()); // Need to adjust for decimals of collateral uint256 use_amount_precision = use_amount_post_tax.div(10 ** missing_decimals); uint256 collateral_dollar_value = use_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(getCollateralPrice()); require(collateral_amount <= getCollateralAmount(), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]"); require(shares_out_min <= shares_amount, "Slippage limit reached [Shares]"); community_rate_in_use = community_rate_in_use.add(use_amount.mul(community_rate_ratio).div(PRECISION)); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemSharesBalances[msg.sender] = redeemSharesBalances[msg.sender].add(shares_amount); unclaimedPoolShares = unclaimedPoolShares.add(shares_amount); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end USE.pool_burn_from(msg.sender, use_amount); SHARE.pool_mint(address(this), shares_amount); require(redemptionOpened() == true,"Redeem amount too large !"); } // After a redemption happens, transfer the newly minted Shares and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out USE/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external onlyOneBlock{ require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendShares = false; bool sendCollateral = false; uint sharesAmount; uint CollateralAmount; // Use Checks-Effects-Interactions pattern if(redeemSharesBalances[msg.sender] > 0){ sharesAmount = redeemSharesBalances[msg.sender]; redeemSharesBalances[msg.sender] = 0; unclaimedPoolShares = unclaimedPoolShares.sub(sharesAmount); sendShares = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendShares == true){ SHARE.transfer(msg.sender, sharesAmount); } if(sendCollateral == true){ collateral_token.transfer(msg.sender, CollateralAmount); } } // When the protocol is recollateralizing, we need to give a discount of Shares to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get Shares for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of Shares + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra Shares value from the bonus rate as an arb opportunity function recollateralizeUSE(uint256 collateral_amount, uint256 shares_out_min) external onlyOneBlock { require(recollateralizePaused == false, "Recollateralize is paused"); updateOraclePrice(); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 share_price = USE.share_price(); uint256 use_total_supply = USE.totalSupply().sub(global_use_supply_adj); uint256 global_collateral_ratio = USE.global_collateral_ratio(); uint256 global_collat_value = USE.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = calcRecollateralizeUSEInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, use_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 shares_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_tax)).div(share_price); require(shares_out_min <= shares_paid_back, "Slippage limit reached"); community_rate_in_share = community_rate_in_share.add(shares_paid_back.mul(community_rate_ratio).div(PRECISION)); collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision); SHARE.pool_mint(msg.sender, shares_paid_back); } // Function can be called by an Shares holder to have the protocol buy back Shares with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackShares(uint256 shares_amount, uint256 COLLATERAL_out_min) external onlyOneBlock { require(buyBackPaused == false, "Buyback is paused"); updateOraclePrice(); uint256 share_price = USE.share_price(); BuybackShares_Params memory input_params = BuybackShares_Params( availableExcessCollatDV(), share_price, getCollateralPrice(), shares_amount ); (uint256 collateral_equivalent_d18) = (calcBuyBackShares(input_params)).mul(uint(1e6).sub(buyback_tax)).div(1e6); uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); community_rate_in_share = community_rate_in_share.add(shares_amount.mul(community_rate_ratio).div(PRECISION)); // Give the sender their desired collateral and burn the Shares SHARE.pool_burn_from(msg.sender, shares_amount); collateral_token.transfer(msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external { require(hasRole(MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; } function toggleRedeeming() external { require(hasRole(REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; } function toggleRecollateralize() external { require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; } function toggleBuyBack() external { require(hasRole(BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; } function toggleCollateralPrice(uint256 _new_price) external { require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; } function toggleCommunityInSharesRate(uint256 _rate) external{ require(community_rate_in_share>0,"No SHARE rate"); require(hasRole(COMMUNITY_RATER, msg.sender)); uint256 _amount_rate = community_rate_in_share.mul(_rate).div(PRECISION); community_rate_in_share = community_rate_in_share.sub(_amount_rate); SHARE.pool_mint(msg.sender,_amount_rate); } function toggleCommunityInUSERate(uint256 _rate) external{ require(community_rate_in_use>0,"No USE rate"); require(hasRole(COMMUNITY_RATER, msg.sender)); uint256 _amount_rate_use = community_rate_in_use.mul(_rate).div(PRECISION); community_rate_in_use = community_rate_in_use.sub(_amount_rate_use); uint256 _share_price_use = USE.share_price_in_use(); uint256 _amount_rate = _amount_rate_use.mul(PRICE_PRECISION).div(_share_price_use); SHARE.pool_mint(msg.sender,_amount_rate); } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_buyback_tax, uint256 new_recollat_tax, uint256 use_supply_adj) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; buyback_tax = new_buyback_tax; recollat_tax = new_recollat_tax; global_use_supply_adj = use_supply_adj; } function setMintingParameters(uint256 _ratioLevel, uint256 _tax_base, uint256 _tax_multiplier) external onlyByOwnerOrGovernance{ minting_required_reserve_ratio = _ratioLevel; minting_tax_base = _tax_base; minting_tax_multiplier = _tax_multiplier; } function setRedemptionParameters(uint256 _ratioLevel, uint256 _tax_base, uint256 _tax_multiplier, uint256 _tax_exponent, uint256 _redeem_gcr_adj) external onlyByOwnerOrGovernance{ redemption_required_reserve_ratio = _ratioLevel; redemption_tax_base = _tax_base; redemption_tax_multiplier = _tax_multiplier; redemption_tax_exponent = _tax_exponent; redemption_gcr_adj = _redeem_gcr_adj; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } function setCommunityParameters(address _community_address,uint256 _ratio) external onlyByOwnerOrGovernance { community_address = _community_address; community_rate_ratio = _ratio; } /* ========== EVENTS ========== */ } // File: contracts\USE\Pools\USEPoolDAI.sol // License: MIT contract USEPoolDAI is USEPool { address public DAI_address; constructor( address _use_contract_address, address _shares_contract_address, address _collateral_address, address _creator_address, address _timelock_address, address _community_address ) USEPool(_use_contract_address, _shares_contract_address, _collateral_address, _creator_address, _timelock_address,_community_address) public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DAI_address = _collateral_address; } // Returns the price of the pool collateral in USD function getCollateralPrice() public view override returns (uint256) { if(collateralPricePaused == true){ return pausedPrice; } else { //Only For Dai return 1 * PRICE_PRECISION; } } }
Must be internal because of the struct Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error The contract must check the proper ratio was sent to mint USE. We do this by seeing the minimum mintable USE based on each amount
function calcMintFractionalWithShare(MintFU_Params memory params) public pure returns (uint256,uint256, uint256) { uint256 shares_dollar_value_d18_with_precision = params.shares_amount.mul(params.shares_price_usd); uint256 shares_dollar_value_d18 = shares_dollar_value_d18_with_precision.div(1e6); uint calculated_collateral_dollar_value_d18 = shares_dollar_value_d18_with_precision.mul(params.col_ratio) .div(COLLATERAL_RATIO_PRECISION.sub(params.col_ratio)).div(1e6); uint calculated_collateral_needed = calculated_collateral_dollar_value_d18.mul(1e6).div(params.col_price_usd); return ( shares_dollar_value_d18.add(calculated_collateral_dollar_value_d18), calculated_collateral_needed, params.shares_amount ); }
10,485,672
./full_match/1/0x10fb5a054C04Cf87d0b1aeea5F720b0f6CDBFeB6/sources/contracts/UNI_SNIPER_11-21.sol
function swapExactBNBForTokensByAccount(uint amountOutMin, address[] calldata path, address to, uint deadline) external ensure(deadline) payable onlyWhitelisted returns (uint[] memory amounts){ require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = PancakeLibrary.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapExactBNBForTokensByAccountSharedPool(address token, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external ensure(deadline) payable onlyWhitelisted returns (uint[] memory amounts){ IERC20 erc20Token = IERC20(token); uint tokenBalance = erc20Token.balanceOf(to); require(tokenBalance == 0, 'UniswapV2Router: R'); require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = PancakeLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function buy() external payable onlyWhitelisted returns (uint[] memory amounts){ IERC20 erc20Token = IERC20(targetTokenBuyTx); uint tokenBalance = erc20Token.balanceOf(singleReceiverAddress); require(tokenBalance == 0, 'UniswapV2Router: R'); require(pathBuyTx[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = PancakeLibrary.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, singleReceiverAddress); } function buy1() external payable onlyWhitelisted returns (uint[] memory amounts){ IERC20 erc20Token = IERC20(targetTokenBuyTx); require(multiBuyIndex < multiBuyCount, 'Router: count meet'); require(pathBuyTx[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = PancakeLibrary.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; } function buy2() external payable onlyWhitelisted returns (uint[] memory amounts){ IERC20 erc20Token = IERC20(targetTokenBuyTx); require(multiBuyIndex < multiBuyCount, 'Router: count meet'); require(pathBuyTx[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = PancakeLibrary.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, receiverAddressList[receiverAddressListIndex]); receiverAddressListIndex++; multiBuyIndex++; } function buyExactTokens() external onlyWhitelisted returns (uint[] memory amounts) { IERC20 erc20Token = IERC20(targetTokenBuyTx); uint tokenBalance = erc20Token.balanceOf(singleReceiverAddress); require(tokenBalance == 0, 'UniswapV2Router: R'); require(pathBuyTx[0] == WETH, 'router: INVALID_PATH'); amounts = PancakeLibrary.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router: EXCESSIVE_INPUT_AMOUNT'); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, singleReceiverAddress); refund dust eth, if any if (wethBalance > amounts[0]) TransferHelper.safeTransferETH(address(this), wethBalance - amounts[0]); } function buyExactTokens1() external onlyWhitelisted returns (uint[] memory amounts) { require(multiBuyIndex < multiBuyCount, 'Router: count meet'); require(pathBuyTx[0] == WETH, 'router: INVALID_PATH'); amounts = PancakeLibrary.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router: EXCESSIVE_INPUT_AMOUNT'); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; refund dust eth, if any if (wethBalance > amounts[0]) TransferHelper.safeTransferETH(address(this), wethBalance - amounts[0]); } function buyExactTokens2() external onlyWhitelisted returns (uint[] memory amounts) { require(multiBuyIndex < multiBuyCount, 'Router: count meet'); require(pathBuyTx[0] == WETH, 'router: INVALID_PATH'); amounts = PancakeLibrary.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router: EXCESSIVE_INPUT_AMOUNT'); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, receiverAddressList[receiverAddressListIndex]); receiverAddressListIndex++; multiBuyIndex++; refund dust eth, if any if (wethBalance > amounts[0]) TransferHelper.safeTransferETH(address(this), wethBalance - amounts[0]); } function buySingleSwap() external onlyWhitelisted returns (uint[] memory amounts) { require(pathBuyTx[0] == WETH, 'UniswapV2Router: INVALID_PATH'); if(fixBNB){ if(onlyOneSuccessTxForSingleReceiver){ IERC20 erc20Token = IERC20(targetTokenBuyTx); uint tokenBalance = erc20Token.balanceOf(singleReceiverAddress); require(tokenBalance == 0, 'UniswapV2Router: R'); amounts = PancakeLibrary.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, singleReceiverAddress); }else if(singleReceiver){ require(multiBuyIndex < multiBuyCount, 'Router: count meet'); amounts = PancakeLibrary.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; }else if(multiReceiver){ require(multiBuyIndex < multiBuyCount, 'Router: count meet'); amounts = PancakeLibrary.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; } }else if(fixToken){ if(onlyOneSuccessTxForSingleReceiver){ IERC20 erc20Token = IERC20(targetTokenBuyTx); uint tokenBalance = erc20Token.balanceOf(singleReceiverAddress); require(tokenBalance == 0, 'UniswapV2Router: R'); amounts = PancakeLibrary.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router: EXCESSIVE_INPUT_AMOUNT'); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, singleReceiverAddress); }else if(singleReceiver){ require(multiBuyIndex < multiBuyCount, 'Router: count meet'); amounts = PancakeLibrary.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router: EXCESSIVE_INPUT_AMOUNT'); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; }else if(multiReceiver){ require(multiBuyIndex < multiBuyCount, 'Router: count meet'); amounts = PancakeLibrary.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router: EXCESSIVE_INPUT_AMOUNT'); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, receiverAddressList[receiverAddressListIndex]); receiverAddressListIndex++; multiBuyIndex++; } } } function buyMultiSwap() external payable onlyWhitelisted returns (uint[] memory amounts) { IERC20 erc20Token = IERC20(targetTokenBuyTx); require(multiBuyIndex < multiBuyCount, 'Router: count meet'); require(pathBuyTx[0] == WETH, 'UniswapV2Router: INVALID_PATH'); uint swapCount = multiBuyIndex; if(fixBNB){ if(singleReceiver){ for (uint i = 0; i < swapCount; i++) { amounts = PancakeLibrary.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; } }else if(multiReceiver){ for (uint i = 0; i < swapCount; i++) { amounts = PancakeLibrary.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, receiverAddressList[receiverAddressListIndex]); receiverAddressListIndex++; multiBuyIndex++; } } }else if(fixToken){ if(singleReceiver){ for (uint i = 0; i < swapCount; i++) { amounts = PancakeLibrary.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router: EXCESSIVE_INPUT_AMOUNT'); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; } }else if(multiReceiver){ for (uint i = 0; i < swapCount; i++) { amounts = PancakeLibrary.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router: EXCESSIVE_INPUT_AMOUNT'); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); _swap(amounts, pathBuyTx, receiverAddressList[receiverAddressListIndex]); receiverAddressListIndex++; multiBuyIndex++; } } } } require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to);IERC20 erc20Token = IERC20(targetTokenBuyTx);
{ require(multiBuyIndex < multiBuyCount, 'Router: count meet'); function sb() external } function swapExactETHForTokens(uint amountIn, uint amountOutMin, address[] calldata path, uint deadline) external ensure(deadline) virtual override } function sbeb() external payable onlyWhitelisted returns (uint[] memory amounts) if(usingETH){ require(pathBuyTx[0] == WETH, 'UniswapV2Router: eth INVALID_PATH'); require(pathBuyTx[0] == USDT, 'UniswapV2Router: eth INVALID_PATH'); } }else{ if(realEvent && !blockConfig){ require(targetBlockNumber == block.number, 'UniswapV2Router: b>'); } if(blockConfig){ require(targetBlockNumber + safeBlock == block.number, 'UniswapV2Router: not'); } for (uint i = 0; i < multiBuyCount; i++) { IERC20 erc20Token = IERC20(USDT); uint USDTBalance = erc20Token.balanceOf(address(this)); if(fixETHorUSDT){ amounts = UniswapV2Library.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); amounts = UniswapV2Library.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); if(usingETH){ uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router ETH: EXCESSIVE_INPUT_AMOUNT'); require(amounts[0] <= USDTBalance, 'router USDT: EXCESSIVE_INPUT_AMOUNT'); } } if(usingETH){ assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); TransferHelper.safeTransfer( pathBuyTx[0], UniswapV2Library.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0] ); } if(singleReceiver){ _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; _swap(amounts, pathBuyTx, receiverAddressList[receiverAddressListIndex]); receiverAddressListIndex++; multiBuyIndex++; } } for (uint i = 0; i < multiBuyCount; i++) { IERC20 erc20Token = IERC20(USDT); uint USDTBalance = erc20Token.balanceOf(address(this)); if(fixETHorUSDT){ amounts = UniswapV2Library.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); amounts = UniswapV2Library.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); if(usingETH){ uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router ETH: EXCESSIVE_INPUT_AMOUNT'); require(amounts[0] <= USDTBalance, 'router USDT: EXCESSIVE_INPUT_AMOUNT'); } } if(usingETH){ assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); TransferHelper.safeTransfer( pathBuyTx[0], UniswapV2Library.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0] ); } if(singleReceiver){ _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; _swap(amounts, pathBuyTx, receiverAddressList[receiverAddressListIndex]); receiverAddressListIndex++; multiBuyIndex++; } } }else{ for (uint i = 0; i < multiBuyCount; i++) { IERC20 erc20Token = IERC20(USDT); uint USDTBalance = erc20Token.balanceOf(address(this)); if(fixETHorUSDT){ amounts = UniswapV2Library.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); amounts = UniswapV2Library.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); if(usingETH){ uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router ETH: EXCESSIVE_INPUT_AMOUNT'); require(amounts[0] <= USDTBalance, 'router USDT: EXCESSIVE_INPUT_AMOUNT'); } } if(usingETH){ assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); TransferHelper.safeTransfer( pathBuyTx[0], UniswapV2Library.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0] ); } if(singleReceiver){ _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; _swap(amounts, pathBuyTx, receiverAddressList[receiverAddressListIndex]); receiverAddressListIndex++; multiBuyIndex++; } } }else{ for (uint i = 0; i < multiBuyCount; i++) { IERC20 erc20Token = IERC20(USDT); uint USDTBalance = erc20Token.balanceOf(address(this)); if(fixETHorUSDT){ amounts = UniswapV2Library.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); amounts = UniswapV2Library.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); if(usingETH){ uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router ETH: EXCESSIVE_INPUT_AMOUNT'); require(amounts[0] <= USDTBalance, 'router USDT: EXCESSIVE_INPUT_AMOUNT'); } } if(usingETH){ assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); TransferHelper.safeTransfer( pathBuyTx[0], UniswapV2Library.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0] ); } if(singleReceiver){ _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; _swap(amounts, pathBuyTx, receiverAddressList[receiverAddressListIndex]); receiverAddressListIndex++; multiBuyIndex++; } } }else{ for (uint i = 0; i < multiBuyCount; i++) { IERC20 erc20Token = IERC20(USDT); uint USDTBalance = erc20Token.balanceOf(address(this)); if(fixETHorUSDT){ amounts = UniswapV2Library.getAmountsOut(factory, amountInBuyTx, pathBuyTx); require(amounts[amounts.length - 1] >= amountOutMinBuyTx, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); amounts = UniswapV2Library.getAmountsIn(factory, tokenAmountOutBuyTx, pathBuyTx); if(usingETH){ uint wethBalance = IWETH(WETH).balanceOf(address(this)); require(amounts[0] <= wethBalance, 'router ETH: EXCESSIVE_INPUT_AMOUNT'); require(amounts[0] <= USDTBalance, 'router USDT: EXCESSIVE_INPUT_AMOUNT'); } } if(usingETH){ assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0])); TransferHelper.safeTransfer( pathBuyTx[0], UniswapV2Library.pairFor(factory, pathBuyTx[0], pathBuyTx[1]), amounts[0] ); } if(singleReceiver){ _swap(amounts, pathBuyTx, singleReceiverAddress); multiBuyIndex++; _swap(amounts, pathBuyTx, receiverAddressList[receiverAddressListIndex]); receiverAddressListIndex++; multiBuyIndex++; } } }else{ }
8,390,575
./partial_match/100/0x21cd73a7f09032689F833624e2840CBB958d9181/sources/RandomAuRa.sol
Used by the `revealNumber` function. _number The validator's number.
function _revealNumber(uint256 _number) internal { address miningAddress = msg.sender; require(revealNumberCallable(miningAddress, _number)); address stakingAddress = validatorSetContract.stakingByMiningAddress(miningAddress); currentSeed = currentSeed ^ _number; _sentReveal[currentCollectRound()][stakingAddress] = true; }
16,647,090
./full_match/42/0x7b3DaF0F9F6e14c8690b567E84F9141d0C6Ce81c/sources/browser/DDSFormular.sol
计算保证金 开仓数量 开仓价 保证金率 exchangeEx:交易队 amount:开仓数量(已经放大1e18) openPrice:开仓价(已经放大1e18) pooltype:池子类型,1-公池;2-私池;/
function getMargin(string memory exchangeEx, uint256 amount, uint256 openPrice, uint256 pooltype) external view returns (uint256 marginfee, uint256 forcefee) { require(amount != 0 && openPrice != 0, "param is invalid"); require(pooltype <= 2, "param is invalid"); if(pooltype == 1) { marginfee = amount.mul(openPrice).mul(publicmarginRatio).div(PRICE_DECIMALS).div(PRICE_DECIMALS); } else { marginfee = amount.mul(openPrice).mul(marginRatio).div(PRICE_DECIMALS).div(PRICE_DECIMALS); } forcefee = amount.mul(openPrice).mul(forcecloseRatio).div(PRICE_DECIMALS).div(PRICE_DECIMALS); }
9,569,106
./partial_match/4/0x690734C5AD9CcBbE0094d3EF91540226A15b3F3f/sources/CYCLEToken.sol
solium-disable-previous-line no-empty-blocks
function _beforeTokenTransfer( address from, address, uint256 ) internal override onlyIfNotBlacklisted(from) { }
8,583,530
./full_match/4/0x4b1b86F04a7012B524594c4dC3612afF74043416/sources/ERC_20.sol
function transferFrom(address from, address to, uint256 token) external returns (bool success);function approve(address spender, uint256 token) external returns (bool success);function allowance(address tokenOwner, address _spender) external view returns (uint256 remaining);event Approval(address indexed _owner, address indexed _spender, uint256 _value);
interface ERC20Interface{ function totalSupply() external view returns (uint256); function balanceOf(address tokenOwner) external view returns (uint256 balance); function transfer(address to, uint256 tokens) external returns (bool success); event Transfer(address indexed _from, address indexed to, uint256 tokens); pragma solidity ^0.8.2; }
12,519,303
./full_match/11155111/0x7DAB44b642cE9c008b5E0c1a9240236cB67481C6/sources/contracts/BloodDonation.sol
Function to donate to a campaign _id The ID of the campaign/ Transfer the received Ether to the campaign owner's address Mint governance tokens to the donor Add the donation to the campaign
function donateToCampaign(uint256 _id) public payable { require(_campaigns[_id].owner != address(0), "The specified campaign ID does not exist"); payable(_campaigns[_id].owner).transfer(msg.value); _mint(msg.sender, msg.value); _campaigns[_id].donators.push(msg.sender); _campaigns[_id].donations.push(msg.value); _campaigns[_id].collectedAmount += msg.value; }
3,801,524
pragma solidity ^0.5.0; /// @title Review management /// @author Kenneth Hu /// @notice Owner and worker can leave comment to each other /// @dev All function calls are currently implemented without side e contract Reviews { struct Review { address reviewee; uint256 bountyID; string reviewText; uint256 stars; uint256 reviewID; address reviewer; } uint256 reviewCounter = 0; mapping(uint256 => Review) reviews; mapping(uint256 => uint256[]) bountyReviews; // Mapping of reviews to a specific bounty mapping(address => uint256[]) reviewsSent; // Mapping of reviews sent by specific user mapping(address => uint256[]) reviewsReceived; // Mapping of reviews recieved by specific user uint256[] public allReviews; /// @notice post an account /// @param _reviewee A reviewee is the person who is being reviewed. /// @param _bountyID the ID of bounty /// @param _reviewText the content of review /// @param _stars stars are often used as symbols for ratings, with five stars being the highest quality. function postReview( address _reviewee, uint256 _bountyID, string memory _reviewText, uint256 _stars ) public { Review storage review = reviews[reviewCounter]; review.reviewee = _reviewee; review.bountyID = _bountyID; review.reviewText = _reviewText; review.stars = _stars; review.reviewID = reviewCounter; review.reviewer = msg.sender; allReviews.push(review.reviewID); bountyReviews[review.bountyID].push(review.reviewID); reviewsSent[msg.sender].push(review.reviewID); reviewsReceived[review.reviewee].push(review.reviewID); reviewCounter += 1; } /// @notice get review by the index of review /// @param reviewID the index of review /// @return Returns a review function getReview(uint256 reviewID) public view returns (address, uint256, string memory, uint256, uint256, address) { return ( reviews[reviewID].reviewee, reviews[reviewID].bountyID, reviews[reviewID].reviewText, reviews[reviewID].stars, reviews[reviewID].reviewID, reviews[reviewID].reviewer ); } /// @notice get the reviews recieved by a user /// @param addr user's address /// @return Returns the reviews function getReceivedReviews(address addr) public view returns (uint256[] memory) { return reviewsReceived[addr]; } /// @notice get the reviews sent by a user /// @param addr user's address /// @return Returns the reviews function getSentReviews(address addr) public view returns (uint256[] memory) { return reviewsSent[addr]; } /// @notice get reviews related to a bounty /// @param bountyID user's address /// @return reviews related to a bounty function getBountyReviews(uint256 bountyID) public view returns (uint256[] memory) { return bountyReviews[bountyID]; } /// @notice get the total number of review /// @return he total number of review function getReviewCount() public view returns (uint256) { return reviewCounter; } }
get review by the index of review reviewID the index of review return Returns a review
function getReview(uint256 reviewID) public view returns (address, uint256, string memory, uint256, uint256, address) { return ( reviews[reviewID].reviewee, reviews[reviewID].bountyID, reviews[reviewID].reviewText, reviews[reviewID].stars, reviews[reviewID].reviewID, reviews[reviewID].reviewer ); }
7,302,599
./partial_match/1/0x1402c061e2AeC7b41AE4911b40F7B340489dD1da/sources/DOSProxy.sol
Remove Node from a storage linkedlist.
function removeNodeFromList(mapping(address => address) storage list, address node) private returns(address, bool) { (address prev, bool found) = findNodeFromList(list, node); if (found) { list[prev] = list[node]; delete list[node]; } return (prev, found); }
4,493,230
./full_match/1/0xD8262F646Cd001430cea2eEcDfe3536547A1E95C/sources/NieuxCollective.sol
Withdraws the contract balance to the receiver address/
function withdraw() public payable { (bool sent, bytes memory data) = payable(_receiver).call{ value: address(this).balance }(""); require(sent, "Failed to send Ether"); }
3,193,385